From alan.gauld at btinternet.com Tue Jun 1 09:31:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Jun 2010 08:31:03 +0100 Subject: [Tutor] playing game across internet: suggestions for design? References: Message-ID: "Alex Hall" wrote >> Actually since there are only two players in Battleships you >> could dispense with a server and do a peer to peer game. > When you say 'peer to peer', is this still with Python sockets? It > sounds like what I am looking for! Yes, it just means both participants use the same program - no need for separate client/server versions and both listen for and send messages to the other. Each acts as a server for the other if you like. The trickiest bit is to establish the initial setup, you usually need to do a bit of polling until you get connected (because unlike with a server you can't assume the other end is ready when you start). > Or, creating a server and both of us being clients: I have a > server (not my own machine, but I rent space on an > iPowerWeb.com server) so I could do this, But your server would need to have Python installed which you say later it doesn't... >> You could even make it a web app with cookies to >> record which player is which. > I need a lot of keyboard interaction and popup dialogs with lists > and > input controls, and my server does not have Python on it. Good > thought, though; maybe I could strip this one down and port to js... The screen interactiion would be javascript but the main data manipulation - keepuing the state/score etc - would be on the server. HTH, Alan G. From imsam100 at yahoo.co.in Tue Jun 1 15:14:25 2010 From: imsam100 at yahoo.co.in (saurabh agrawal) Date: Tue, 1 Jun 2010 18:44:25 +0530 (IST) Subject: [Tutor] matmolplot Message-ID: <653910.6478.qm@web94602.mail.in2.yahoo.com> Hi, I am trying to make plot using following code:-----------#!/usr/bin/pythonimport numpy as npimport matplotlib.pyplot as pltimport stringfrom pylab import savefigfrom sys import argv #input file as first argumentf1=argv[1]f = open(f1,'r')line=f.readlines()f.close() f2 = f1.split(".")#f3 = f2[0].split("-") l1=[];l2=[]for lines in line:??lin=lines.split()??l1.append(float(lin[0]))??l2.append(float(lin[1]))??#print max(l2)??for i in range(len(l2)):??plt.axvline(x=l1[i], ymin=0, ymax=l2[i], linewidth=2, color='r')?? plt.axis([350, 650, 0.0, max(l2)])plt.grid(True)savefig(f2[0]+"-"+"uv.png",dpi=(600/8))plt.show()---------------- My problem is the output plot I am getting is not showing correct values in the plot as are in the input file (MS.txt - attached). It looks like it is scaled to lower value. Please help. Regards, Saurabh -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: MS.txt URL: From breamoreboy at yahoo.co.uk Tue Jun 1 17:45:54 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 01 Jun 2010 16:45:54 +0100 Subject: [Tutor] matmolplot In-Reply-To: <653910.6478.qm@web94602.mail.in2.yahoo.com> References: <653910.6478.qm@web94602.mail.in2.yahoo.com> Message-ID: On 01/06/2010 14:14, saurabh agrawal wrote: > Hi, > I am trying to make plot using following code:-----------#!/usr/bin/pythonimport numpy as npimport matplotlib.pyplot as pltimport stringfrom pylab import savefigfrom sys import argv > #input file as first argumentf1=argv[1]f = open(f1,'r')line=f.readlines()f.close() > f2 = f1.split(".")#f3 = f2[0].split("-") > l1=[];l2=[]for lines in line: lin=lines.split() l1.append(float(lin[0])) l2.append(float(lin[1])) #print max(l2) for i in range(len(l2)): plt.axvline(x=l1[i], ymin=0, ymax=l2[i], linewidth=2, color='r') > plt.axis([350, 650, 0.0, max(l2)])plt.grid(True)savefig(f2[0]+"-"+"uv.png",dpi=(600/8))plt.show()---------------- > My problem is the output plot I am getting is not showing correct values in the plot as are in the input file (MS.txt - attached). It looks like it is scaled to lower value. > Please help. > Regards, > Saurabh > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If I've managed to reformat your code correctly, the problem is the call to plt.axis which sets xmin to 350, compare this to your data values where the lowest value of x is 233.27. Note that there is also a matplotlib mailing list. HTH. Mark Lawrence. From evert.rol at gmail.com Tue Jun 1 17:59:52 2010 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 1 Jun 2010 17:59:52 +0200 Subject: [Tutor] matmolplot In-Reply-To: <7C0C6E92-89A3-4AFF-9D77-72BD89224DDB@googlemail.com> References: <653910.6478.qm@web94602.mail.in2.yahoo.com> <0B02FC4D-CB18-478A-A621-436627C881DD@gmail.com> <7C0C6E92-89A3-4AFF-9D77-72BD89224DDB@googlemail.com> Message-ID: <620AEF67-09D7-4FD6-918B-5E9D7DF918A6@gmail.com> Sorry, forgot to reply-to-all previously. > Hi, > > I am trying to make plot using following code: > ----------- > for i in range(len(l2)): > plt.axvline(x=l1[i], ymin=0, ymax=l2[i], linewidth=2, color='r') axvline uses the [0, 1] range for it coordinates, not the coordinates set by the y-axis (which are set by the data): http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axvline (which states "With the default values of ymin = 0 and ymax = 1, this line will always span the vertical extent of the axes, regardless of the ylim settings...") You don't readily notice it, since your data lies in roughly the same [0, 1] interval. If your data were in the [0, 10] interval, you would have immediately spotted it. Why don't you use eg: plt.bar(left=l1, height=l2) (which also removes the extra for loop) Evert > plt.axis([350, 650, 0.0, max(l2)]) > plt.grid(True) > savefig(f2[0]+"-"+"uv.png",dpi=(600/8)) > plt.show() > ---------------- > > My problem is the output plot I am getting is not showing correct values in the plot as are in the input file (MS.txt - attached). It looks like it is scaled to lower value. From jf_byrnes at comcast.net Tue Jun 1 22:19:17 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 01 Jun 2010 15:19:17 -0500 Subject: [Tutor] OOP clarification needed Message-ID: <4C056B45.4040802@comcast.net> Whenever I teach myself a new language I have great difficulty understanding the nuts and bolts of it's OO implementation. Compared to some older procedural languages I always end up becoming confused by the large number of built in methods. When reading through code examples I many times get hung up on trying to figure out just where some methods come from. Case in point is this code snippet from a chapter on Tkinter. def viewer(imgdir, kind=Toplevel, cols=None): """ make thumb links window for an image directory: one thumb button per image; use kind=Tk to show in main app window, or Frame container (pack); imgfile differs per loop: must save with a default; photoimage objs must be saved: erased if reclaimed; """ win = kind() win.title('Viewer: ' + imgdir) thumbs = makeThumbs(imgdir) What is the relationship between kind=Toplevel in the first line and win=kind() further down. Isn't "kind" a variable and "kind()" a method? I've probable overlooked something fundamental but a explanation would be appreciated. Regards, Jim From steve at alchemy.com Tue Jun 1 22:29:15 2010 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 1 Jun 2010 13:29:15 -0700 Subject: [Tutor] OOP clarification needed In-Reply-To: <4C056B45.4040802@comcast.net> References: <4C056B45.4040802@comcast.net> Message-ID: <20100601202915.GB18863@dragon.alchemy.com> On Tue, Jun 01, 2010 at 03:19:17PM -0500, Jim Byrnes wrote: > def viewer(imgdir, kind=Toplevel, cols=None): > win = kind() > > What is the relationship between kind=Toplevel in the first line and > win=kind() further down. Isn't "kind" a variable and "kind()" a method? kind is a variable. Specifically, the second parameter passed to the viewer() function defined here. By saying kind() here, you are invoking it on the assumption that kind's value is a reference to some kind of callable object. So in theory you could pass a function as the "kind" parameter of viewer() and that function would get called, and its return value stored in "win". In this case, though, the intent is for "kind" to refer to an object class (the kind of widget this viewer is contained in or whatever). Recalling that object classes are themselves callable objects (specifically, calling them is how you construct new instances of a class), "win" will end up referring to a newly-constructed instance of whatever object class was passed as "kind". If no "kind" parameter was given, it will default to tk.Toplevel. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From talbertc at usgs.gov Tue Jun 1 23:40:33 2010 From: talbertc at usgs.gov (Colin Talbert) Date: Tue, 1 Jun 2010 15:40:33 -0600 Subject: [Tutor] parse text file Message-ID: I am also experiencing this same problem. (Also on a OSM bz2 file). It appears to be working but then partway through reading a file it simple ends. I did track down that file length is always 900000 so it appears to be related to some sort of buffer constraint. Any other ideas? import bz2 input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") try: all_data = input_file.read() print str(len(all_data)) finally: input_file.close() Colin Talbert GIS Specialist US Geological Survey - Fort Collins Science Center 2150 Centre Ave. Bldg. C Fort Collins, CO 80526 (970) 226-9425 talbertc at usgs.gov -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jun 2 00:44:53 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 01 Jun 2010 18:44:53 -0400 Subject: [Tutor] parse text file In-Reply-To: References: Message-ID: <4C058D65.7030000@gmail.com> On 6/1/2010 5:40 PM, Colin Talbert wrote: > > I am also experiencing this same problem. (Also on a OSM bz2 > file). It appears to be working but then partway through reading a > file it simple ends. I did track down that file length is always > 900000 so it appears to be related to some sort of buffer constraint. > > > Any other ideas? How big is the file? Is it necessary to read the entire thing at once? Try opening with mode rb > > import bz2 > > input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") > try: > all_data = input_file.read() > print str(len(all_data)) > finally: > input_file.close() > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bmleddige at hotmail.com Wed Jun 2 00:04:13 2010 From: bmleddige at hotmail.com (Benjamin Leddige) Date: Tue, 1 Jun 2010 16:04:13 -0600 Subject: [Tutor] Generating Birthdays Message-ID: I have to create a program that generates random birthdays while using lists. How do i go about doing this? Do i create two separate lists for for the months and days or how can i go about writing this? Thanks _________________________________________________________________ The New Busy is not the too busy. Combine all your e-mail accounts with Hotmail. http://www.windowslive.com/campaign/thenewbusy?tile=multiaccount&ocid=PID28326::T:WLMTAGL:ON:WL:en-US:WM_HMP:042010_4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 2 01:21:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Jun 2010 00:21:39 +0100 Subject: [Tutor] OOP clarification needed References: <4C056B45.4040802@comcast.net> Message-ID: "Jim Byrnes" wrote > Whenever I teach myself a new language I have great difficulty > understanding the nuts and bolts of it's OO implementation. Do you understand the OO concepts OK? Is it only the language semantics you struggle with or the underlying OO concepts? > some older procedural languages I always end up becoming confused by > the large number of built in methods. C is one of the simplest procedural languages around and yet it comes with a huge library of functions (several hundred in some cases). The size of the library should be easier to manage using OOP than with older function/procedure based libraries, because the functions are not just logically grouped in the documentation but in the code too. > Case in point is this code snippet from a chapter on Tkinter. > > def viewer(imgdir, kind=Toplevel, cols=None): > """ > make thumb links window for an image directory: > one thumb button per image; use kind=Tk to show > in main app window, or Frame container (pack); > imgfile differs per loop: must save with a default; > photoimage objs must be saved: erased if reclaimed; > """ > win = kind() > win.title('Viewer: ' + imgdir) > thumbs = makeThumbs(imgdir) > > > What is the relationship between kind=Toplevel in the first line and > win=kind() further down. kind is a parameter ogf the function with a default value of Toplevel. Toplevel being a class. Recall that in Python classes are objects too and can be assigned to variables. This is similar to Smalltalk, Lisp, Objective C and Delphi(Object Pascal) but different to C++ and Java (actually I'm not sure about Java?). > Isn't "kind" a variable and "kind()" a method? No kind() is an invocation of a callable object. In Python callables tend to be either functions or classes or methods of objects. In this case it is an instantiation of a class. In C++ or Java it would look something like: win = new kind(); Because classes can be treated as objects and passed to functions this instantiates whatever kind of object was passed into viewer. As the comment says this could be the top level window Tk or a generic Frame container or the default Toplevel. So long as the new object supports all the methods that will be invoked Python doesn't care. This is polymorphism... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jun 2 01:25:58 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Jun 2010 00:25:58 +0100 Subject: [Tutor] Generating Birthdays References: Message-ID: "Benjamin Leddige" wrote > I have to create a program that generates random birthdays > while using lists. This sounds like a homework assignment. We don't do homework for you but if you tell us what you've tried and where you are stuck we will try to make helpful suggestions. > How do i go about doing this? Do i create two separate lists for > for the months and days or how can i go about writing this? First can you explain more about what you want to do. Getting the problem clear in your head (and ours) is the first step. What exactly is a "random birthday"? What makes it different to a random date? And do you know how to generate randomness in your programs? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jun 2 01:37:18 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Jun 2010 09:37:18 +1000 Subject: [Tutor] Generating Birthdays In-Reply-To: References: Message-ID: <201006020937.19919.steve@pearwood.info> On Wed, 2 Jun 2010 08:04:13 am Benjamin Leddige wrote: > I have to create a program that generates random birthdays while > using lists. How do i go about doing this? Do i create two separate > lists for for the months and days or how can i go about writing this? If you didn't use a separate list for months and days, what could you do? What would you do if you were doing this by hand? Write out the steps you would do by hand, and then do the same thing in Python. E.g. this is what I would do by hand, *if* I didn't have to use lists: To pick a random birthday, choose a random number between 1 and 365, then find out which date of the year (month and day) that is. You can't do that because you have to use lists. So what would you do instead? -- Steven D'Aprano From steve at pearwood.info Wed Jun 2 02:03:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Jun 2010 10:03:00 +1000 Subject: [Tutor] OOP clarification needed In-Reply-To: <4C056B45.4040802@comcast.net> References: <4C056B45.4040802@comcast.net> Message-ID: <201006021003.01041.steve@pearwood.info> On Wed, 2 Jun 2010 06:19:17 am Jim Byrnes wrote: > Whenever I teach myself a new language I have great difficulty > understanding the nuts and bolts of it's OO implementation. Compared > to some older procedural languages I always end up becoming confused > by the large number of built in methods. When reading through code > examples I many times get hung up on trying to figure out just where > some methods come from. > > Case in point is this code snippet from a chapter on Tkinter. > > def viewer(imgdir, kind=Toplevel, cols=None): > """ > make thumb links window for an image directory: > one thumb button per image; use kind=Tk to show > in main app window, or Frame container (pack); > imgfile differs per loop: must save with a default; > photoimage objs must be saved: erased if reclaimed; > """ > win = kind() > win.title('Viewer: ' + imgdir) > thumbs = makeThumbs(imgdir) > > > What is the relationship between kind=Toplevel in the first line and > win=kind() further down. Isn't "kind" a variable and "kind()" a > method? I've probable overlooked something fundamental but a > explanation would be appreciated. This has nothing to do with object oriented programming. Apart from the call to win.title(), there's nothing object oriented in this. The call to kind() is not a method but a function call, no different from (say) len(x) or cos(x), except that kind() takes no argument. What you're actually getting confused by here is higher-order programming. In simple languages, you have two sorts of things: code (functions and classes), and variables (data and instances), and they are completely different stuff. Functions take data as arguments, operate on the data, and produce new data. Here's a couple of examples from Python: def plusone(x): return x+1 def plustwo(x): return x+2 Both functions take a single argument, which must be a number, does something with that number, and returns a new number. But in higher-order programming, we realise that functions themselves can be data. You can write a function that takes a function as data, operates on the function, and produces something new. Here's a trivial example: def print_table(func, start, stop): print ' x =', # Note the comma. results = [] for x in range(start, stop): print x, result = func(x) results.append(result) print print 'f(x) =', for item in results: print item, print You then call this like: print_table(plustwo, 1, 7) and you get something like this: x = 1 2 3 4 5 6 f(x) = 3 4 5 6 7 8 In the example you give, you have an argument named "kind". It is expected to be some sort of function or class, and gets the default value of TopLevel if not supplied. In the body of the function, this function or class is called, to produce a value which is then named "win". Judging by the default value and the name of the inner variable, I would say it is expected to produce a window object, so any function or class that returns a window object will be suitable. -- Steven D'Aprano From steve at pearwood.info Wed Jun 2 02:12:06 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Jun 2010 10:12:06 +1000 Subject: [Tutor] parse text file In-Reply-To: References: Message-ID: <201006021012.07227.steve@pearwood.info> On Wed, 2 Jun 2010 07:40:33 am Colin Talbert wrote: > I am also experiencing this same problem. (Also on a OSM bz2 > file). It appears to be working but then partway through reading a > file it simple ends. I did track down that file length is always > 900000 so it appears to be related to some sort of buffer constraint. Without seeing your text file, and the code you use to read the text file, there's no way of telling what is going on, but I can guess the most likely causes: (1) Your text file is actually only 900,000 bytes long, and so there's no problem at all. (2) There's a bug in your code so that you stop reading after 900,000 bytes. (3) You're on Windows, and the text file contains an End-Of-File character ^Z after 900,000 bytes, and Windows supports that for backward compatibility with DOS. And a distant (VERY distant) number 4, there's a bug in the implementation of read() in Python which somehow nobody has noticed before now. As for your second issue, reading bz2 files: > import bz2 > > input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") You're opening a binary file in text mode. I'm pretty sure that is not going to work well. Try passing 'rb' as the mode instead. > try: > all_data = input_file.read() > print str(len(all_data)) You don't need to call str() before calling print. print is perfectly happy to operate on integers: print len(all_data) will work. -- Steven D'Aprano From jf_byrnes at comcast.net Wed Jun 2 17:22:00 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 02 Jun 2010 10:22:00 -0500 Subject: [Tutor] OOP clarification needed In-Reply-To: <20100601202915.GB18863@dragon.alchemy.com> References: <4C056B45.4040802@comcast.net> <20100601202915.GB18863@dragon.alchemy.com> Message-ID: <4C067718.6080108@comcast.net> Steve Willoughby wrote: > On Tue, Jun 01, 2010 at 03:19:17PM -0500, Jim Byrnes wrote: >> def viewer(imgdir, kind=Toplevel, cols=None): >> win = kind() >> >> What is the relationship between kind=Toplevel in the first line and >> win=kind() further down. Isn't "kind" a variable and "kind()" a method? > > kind is a variable. Specifically, the second parameter passed to the viewer() > function defined here. > > By saying kind() here, you are invoking it on the assumption that kind's > value is a reference to some kind of callable object. So in theory you > could pass a function as the "kind" parameter of viewer() and that function > would get called, and its return value stored in "win". > > In this case, though, the intent is for "kind" to refer to an object class > (the kind of widget this viewer is contained in or whatever). Recalling that > object classes are themselves callable objects (specifically, calling them > is how you construct new instances of a class), "win" will end up referring > to a newly-constructed instance of whatever object class was passed as "kind". > If no "kind" parameter was given, it will default to tk.Toplevel. > Thanks for the explanation. I didn't understand how (or why) "kind" could change to "kind()". Sometimes I can manage to trip myself up over the silliest things. Regards, Jim From jf_byrnes at comcast.net Wed Jun 2 17:37:53 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 02 Jun 2010 10:37:53 -0500 Subject: [Tutor] OOP clarification needed In-Reply-To: References: <4C056B45.4040802@comcast.net> Message-ID: <4C067AD1.5020207@comcast.net> Alan Gauld wrote: > "Jim Byrnes" wrote > >> Whenever I teach myself a new language I have great difficulty >> understanding the nuts and bolts of it's OO implementation. > > Do you understand the OO concepts OK? > Is it only the language semantics you struggle with > or the underlying OO concepts? I believe I understand the theory, but struggle with the actual implementation. >> some older procedural languages I always end up becoming confused by >> the large number of built in methods. > > C is one of the simplest procedural languages around > and yet it comes with a huge library of functions (several > hundred in some cases). The size of the library should be easier > to manage using OOP than with older function/procedure based > libraries, because the functions are not just logically grouped > in the documentation but in the code too. I don't know C, I was thinking more along the lines of Basic or Rexx.I could sit down and read through a list of keywords and built in functions and it would be compact enough that I would have a good idea of what was available. I can't seem to do that with the OO languages, but of course I am older now also. >> Case in point is this code snippet from a chapter on Tkinter. >> >> def viewer(imgdir, kind=Toplevel, cols=None): >> """ >> make thumb links window for an image directory: >> one thumb button per image; use kind=Tk to show >> in main app window, or Frame container (pack); >> imgfile differs per loop: must save with a default; >> photoimage objs must be saved: erased if reclaimed; >> """ >> win = kind() >> win.title('Viewer: ' + imgdir) >> thumbs = makeThumbs(imgdir) >> >> >> What is the relationship between kind=Toplevel in the first line and >> win=kind() further down. > > kind is a parameter ogf the function with a default value of Toplevel. > Toplevel being a class. Recall that in Python classes are objects > too and can be assigned to variables. This is similar to Smalltalk, > Lisp, Objective C and Delphi(Object Pascal) but different to C++ > and Java (actually I'm not sure about Java?). > >> Isn't "kind" a variable and "kind()" a method? > > No kind() is an invocation of a callable object. > In Python callables tend to be either functions > or classes or methods of objects. > In this case it is an instantiation of a class. > In C++ or Java it would look something like: > > win = new kind(); > > Because classes can be treated as objects and passed to functions > this instantiates whatever kind of object was passed into viewer. > As the comment says this could be the top level window Tk or > a generic Frame container or the default Toplevel. So long as the > new object supports all the methods that will be invoked Python > doesn't care. This is polymorphism... > I had completely forgotten about the callable object. I saw the ()'s and wrongly started to think of it as a method. Thanks for the explanation. Regards, Jim From jf_byrnes at comcast.net Wed Jun 2 17:46:12 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 02 Jun 2010 10:46:12 -0500 Subject: [Tutor] OOP clarification needed In-Reply-To: <201006021003.01041.steve@pearwood.info> References: <4C056B45.4040802@comcast.net> <201006021003.01041.steve@pearwood.info> Message-ID: <4C067CC4.9040704@comcast.net> Steven D'Aprano wrote: >> >> Case in point is this code snippet from a chapter on Tkinter. >> >> def viewer(imgdir, kind=Toplevel, cols=None): >> """ >> make thumb links window for an image directory: >> one thumb button per image; use kind=Tk to show >> in main app window, or Frame container (pack); >> imgfile differs per loop: must save with a default; >> photoimage objs must be saved: erased if reclaimed; >> """ >> win = kind() >> win.title('Viewer: ' + imgdir) >> thumbs = makeThumbs(imgdir) >> >> > > In the example you give, you have an argument named "kind". It is > expected to be some sort of function or class, and gets the default > value of TopLevel if not supplied. In the body of the function, this > function or class is called, to produce a value which is then > named "win". Judging by the default value and the name of the inner > variable, I would say it is expected to produce a window object, so any > function or class that returns a window object will be suitable. > I completely overlooked this expectation, which led to my confusion. Thanks for the explanation. Regards, Jim From bgailer at gmail.com Wed Jun 2 18:14:44 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 02 Jun 2010 12:14:44 -0400 Subject: [Tutor] parse text file In-Reply-To: References: <4C058D65.7030000@gmail.com> Message-ID: <4C068374.70009@gmail.com> Please always reply-all so a copy goes to the list. On 6/1/2010 6:49 PM, Colin Talbert wrote: > > Bob thanks for your response, > The file is about 9.3 gig and no I don't want read the whole > thing at once. I want to read it in line by line. Still it will read > in to the same point (900000 characters) and then act as if it came to > the end of the file. Below is the code I using for this: > > > import bz2 > > input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","rb") > for uline in input_file: > print linecount > linecount+=1 > > > > > > > > > Colin Talbert > GIS Specialist > US Geological Survey - Fort Collins Science Center > 2150 Centre Ave. Bldg. C > Fort Collins, CO 80526 > > (970) 226-9425 > talbertc at usgs.gov > > > > From: bob gailer > To: Colin Talbert > Cc: tutor at python.org > Date: 06/01/2010 04:43 PM > Subject: Re: [Tutor] parse text file > > > ------------------------------------------------------------------------ > > > > On 6/1/2010 5:40 PM, Colin Talbert wrote: > > I am also experiencing this same problem. (Also on a OSM bz2 > file). It appears to be working but then partway through reading a > file it simple ends. I did track down that file length is always > 900000 so it appears to be related to some sort of buffer constraint. > > > Any other ideas? > > How big is the file? > > Is it necessary to read the entire thing at once? > > Try opening with mode rb > > > import bz2 > > input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") > try: > all_data = input_file.read() > print str(len(all_data)) > finally: > input_file.close() -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 2 23:41:41 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Jun 2010 07:41:41 +1000 Subject: [Tutor] parse text file In-Reply-To: References: <201006021012.07227.steve@pearwood.info> Message-ID: <201006030741.41477.steve@pearwood.info> Hi Colin, I'm taking the liberty of replying to your message back to the list, as others hopefully may be able to make constructive comments. When replying, please ensure that you reply to the tutor mailing list rather than then individual. On Thu, 3 Jun 2010 12:20:10 am Colin Talbert wrote: > > Without seeing your text file, and the code you use to read the text > > file, there's no way of telling what is going on, but I can guess > > the most likely causes: > > Since the file is 9.2 gig it wouldn't make sense to send it to you. And I am very glad you didn't try *smiles* However, a file of that size changes things drastically. You can't expect to necessarily be able to read the entire 9.2 gigabyte BZ2 file into memory at once, let along the unpacked 131 GB text file, EVEN if your computer has more than 9.2 GB of memory. So your tests need to take this into account. > > (2) There's a bug in your code so that you stop reading after > > 900,000 bytes. > The code is simple enough that I'm pretty sure there is not a > bug in it. > > import bz2 > input_file = > bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') print > len(input_file) > > returns 900000 I'm pretty sure that this is not your code, because you can't call len() on a bz2 file. If you try, you get an error: >>> x = bz2.BZ2File('test.bz2', 'w') # create a temporary file >>> x.write("some data") >>> x.close() >>> input_file = bz2.BZ2File('test.bz2', 'r') # open it >>> print len(input_file) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'bz2.BZ2File' has no len() So whatever your code actually is, I'm fairly sure it isn't what you say here. -- Steven D'Aprano From talbertc at usgs.gov Thu Jun 3 16:45:52 2010 From: talbertc at usgs.gov (Colin Talbert) Date: Thu, 3 Jun 2010 08:45:52 -0600 Subject: [Tutor] parse text file In-Reply-To: <201006030741.41477.steve@pearwood.info> References: <201006021012.07227.steve@pearwood.info> <201006030741.41477.steve@pearwood.info> Message-ID: Hello Steven, Thanks for the reply. Also this is my first post to tutor at python so I'll reply all in the future. However, a file of that size changes things drastically. You can't expect to necessarily be able to read the entire 9.2 gigabyte BZ2 file into memory at once, let along the unpacked 131 GB text file, EVEN if your computer has more than 9.2 GB of memory. So your tests need to take this into account. I thought when you did a for uline in input_file each single line would go into memory independently, not the entire file. I'm pretty sure that this is not your code, because you can't call len() on a bz2 file. If you try, you get an error: You are so correct. I'd been trying numerous things to read in this file and had deleted the code that I meant to put here and so wrote this from memory incorrectly. The code that I wrote should have been: import bz2 input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') str=input_file.read() len(str) Which indeed does return only 900000. Which is also the number returned when you sum the length of all the lines returned in a for line in file with: import bz2 input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') lengthz = 0 for uline in input_file: lengthz = lengthz + len(uline) print lengthz Thanks again for you help and sorry for the bad code in the previous submittal. Colin Talbert GIS Specialist US Geological Survey - Fort Collins Science Center 2150 Centre Ave. Bldg. C Fort Collins, CO 80526 (970) 226-9425 talbertc at usgs.gov From: Steven D'Aprano To: tutor at python.org Date: 06/02/2010 03:42 PM Subject: Re: [Tutor] parse text file Sent by: tutor-bounces+talbertc=usgs.gov at python.org Hi Colin, I'm taking the liberty of replying to your message back to the list, as others hopefully may be able to make constructive comments. When replying, please ensure that you reply to the tutor mailing list rather than then individual. On Thu, 3 Jun 2010 12:20:10 am Colin Talbert wrote: > > Without seeing your text file, and the code you use to read the text > > file, there's no way of telling what is going on, but I can guess > > the most likely causes: > > Since the file is 9.2 gig it wouldn't make sense to send it to you. And I am very glad you didn't try *smiles* However, a file of that size changes things drastically. You can't expect to necessarily be able to read the entire 9.2 gigabyte BZ2 file into memory at once, let along the unpacked 131 GB text file, EVEN if your computer has more than 9.2 GB of memory. So your tests need to take this into account. > > (2) There's a bug in your code so that you stop reading after > > 900,000 bytes. > The code is simple enough that I'm pretty sure there is not a > bug in it. > > import bz2 > input_file = > bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') print > len(input_file) > > returns 900000 I'm pretty sure that this is not your code, because you can't call len() on a bz2 file. If you try, you get an error: >>> x = bz2.BZ2File('test.bz2', 'w') # create a temporary file >>> x.write("some data") >>> x.close() >>> input_file = bz2.BZ2File('test.bz2', 'r') # open it >>> print len(input_file) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'bz2.BZ2File' has no len() So whatever your code actually is, I'm fairly sure it isn't what you say here. -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Thu Jun 3 17:50:42 2010 From: oberoc at gmail.com (Tino Dai) Date: Thu, 3 Jun 2010 11:50:42 -0400 Subject: [Tutor] Misc question about scoping Message-ID: Hi All, Is there a way to express this: isThumbnail = False if size == "thumbnail": isThumbnail = True like this: [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] and the scoping extending to one level above without resorting to the global keyword? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jun 3 18:06:18 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Jun 2010 02:06:18 +1000 Subject: [Tutor] OOP clarification needed In-Reply-To: <4C067AD1.5020207@comcast.net> References: <4C056B45.4040802@comcast.net> <4C067AD1.5020207@comcast.net> Message-ID: On 06/03/10 01:37, Jim Byrnes wrote: > >>> some older procedural languages I always end up becoming confused by >>> the large number of built in methods. >> >> C is one of the simplest procedural languages around >> and yet it comes with a huge library of functions (several >> hundred in some cases). The size of the library should be easier >> to manage using OOP than with older function/procedure based >> libraries, because the functions are not just logically grouped >> in the documentation but in the code too. > > I don't know C, I was thinking more along the lines of Basic or Rexx.I > could sit down and read through a list of keywords and built in > functions and it would be compact enough that I would have a good idea > of what was available. I can't seem to do that with the OO languages, > but of course I am older now also. When I learned Visual Basic, I definitely remembered the thousands of pages of documentation for thousands of functions. Python is probably isn't much different in the size of the number of functions included in the stdlib, but IMHO help() and pydoc aids much better in navigating the docs compared to context sensitive help. Python's keywords are just: help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print as else import raise assert except in return break exec is try class finally lambda while continue for not with def from or yield del global pass I don't think there are many non-esoteric languages with significantly less keywords than python. and the builtin functions: abs all any apply basestring bin bool buffer bytearray bytes callable chr classmethod cmp coerce compile complex delattr dict dir divmod enumerate eval execfile exit file filter float format frozenset getattr globals hasattr hash help hex id input int intern isinstance issubclass iter len list locals long map max min next object oct open ord pow print property quit range raw_input reduce reload repr reversed round set setattr slice sorted staticmethod str sum super tuple type unichr unicode vars xrange zip and unlike some languages, the list of python's built-ins actually gets smaller with py3k (84 items in 2.6.4 and 71 items in 3.1.2, excluding Exceptions) I never actually sit down and read through all the built-in function's documentation; I just skim through this list, make a mental note of what they appears to be doing from their name, and only read their documentation as the need to use them arises. From bgailer at gmail.com Thu Jun 3 18:50:55 2010 From: bgailer at gmail.com (bob gailer) Date: Thu, 03 Jun 2010 12:50:55 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: Message-ID: <4C07DD6F.7080505@gmail.com> On 6/3/2010 11:50 AM, Tino Dai wrote: > Hi All, > > Is there a way to express this: > isThumbnail = False > if size == "thumbnail": > isThumbnail = True > How I do that is: isThumbnail = size == "thumbnail": > like this: > [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] > and the scoping extending to one level above without resorting to > the global keyword? I have no idea what you mean by that. Please provide context. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Thu Jun 3 19:10:41 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Jun 2010 18:10:41 +0100 Subject: [Tutor] Misc question about scoping References: Message-ID: "Tino Dai" wrote > Is there a way to express this: > isThumbnail = False > if size == "thumbnail": > isThumbnail = True > > like this: > [ isThumbnail = True if size == "thumbnail" isThumbnail = > False ] Bob showed one way, you could also do: isThumbnail = True if size == "thumbnail" else False > and the scoping extending to one level above without resorting > to the > global keyword? Not sure what this has to do with scoping or the use of global? global is only needed inside a function if you are modifying a value defined outside the function. If the assignment is inside a function and the definition of isThumbnail is outside then you need to use global. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 3 19:15:45 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Jun 2010 18:15:45 +0100 Subject: [Tutor] parse text file References: <201006021012.07227.steve@pearwood.info><201006030741.41477.steve@pearwood.info> Message-ID: "Colin Talbert" wrote > I thought when you did a for uline in input_file each single line > would go > into memory independently, not the entire file. Thats true but your code snippet showed you using read() which reads the whole file... > I'm pretty sure that this is not your code, because you can't call > len() > on a bz2 file. If you try, you get an error: > > You are so correct. I'd been trying numerous things to read in this > file > and had deleted the code that I meant to put here and so wrote this > from > memory incorrectly. The code that I wrote should have been: > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > str=input_file.read() > len(str) This again usees read() which reads the whole file. > Which is also the number returned when you sum the length of all the > lines > returned in a for line in file with: > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > lengthz = 0 > for uline in input_file: > lengthz = lengthz + len(uline) I'm not sure how for line in file will work for binary files. It may read the whole thing since the concept of lines really only applies to text. So it may be the same result as using read() Try looping using read(n) where n is some buffer size (1024 might be a good value?). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Thu Jun 3 20:35:41 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 03 Jun 2010 14:35:41 -0400 Subject: [Tutor] parse text file In-Reply-To: References: <201006021012.07227.steve@pearwood.info> <201006030741.41477.steve@pearwood.info> Message-ID: <4C07F5FD.2010207@ieee.org> Colin Talbert wrote: > > You are so correct. I'd been trying numerous things to read in this file > and had deleted the code that I meant to put here and so wrote this from > memory incorrectly. The code that I wrote should have been: > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > str=input_file.read() > len(str) > > Which indeed does return only 900000. > > Which is also the number returned when you sum the length of all the lines > returned in a for line in file with: > > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > lengthz = 0 > for uline in input_file: > lengthz = lengthz + len(uline) > > print lengthz > > > > Seems to me for such a large file you'd have to use bz2.BZ2Decompressor. I have no experience with it, but its purpose is for sequential decompression -- decompression where not all the data is simultaneously available in memory. DaveA From talbertc at usgs.gov Thu Jun 3 21:02:22 2010 From: talbertc at usgs.gov (Colin Talbert) Date: Thu, 3 Jun 2010 13:02:22 -0600 Subject: [Tutor] parse text file In-Reply-To: <4C07F5FD.2010207@ieee.org> References: <201006021012.07227.steve@pearwood.info> <201006030741.41477.steve@pearwood.info> <4C07F5FD.2010207@ieee.org> Message-ID: Dave, I think you are probably right about using decompressor. I couldn't find any example of it in use and wasn't having any luck getting it to work based on the documentation. Maybe I should try harder on this front. Colin Talbert GIS Specialist US Geological Survey - Fort Collins Science Center 2150 Centre Ave. Bldg. C Fort Collins, CO 80526 (970) 226-9425 talbertc at usgs.gov From: Dave Angel To: Colin Talbert Cc: Steven D'Aprano , tutor at python.org Date: 06/03/2010 12:36 PM Subject: Re: [Tutor] parse text file Colin Talbert wrote: > > You are so correct. I'd been trying numerous things to read in this file > and had deleted the code that I meant to put here and so wrote this from > memory incorrectly. The code that I wrote should have been: > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > str=input_file.read() > len(str) > > Which indeed does return only 900000. > > Which is also the number returned when you sum the length of all the lines > returned in a for line in file with: > > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > lengthz = 0 > for uline in input_file: > lengthz = lengthz + len(uline) > > print lengthz > > > > Seems to me for such a large file you'd have to use bz2.BZ2Decompressor. I have no experience with it, but its purpose is for sequential decompression -- decompression where not all the data is simultaneously available in memory. DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at gmail.com Thu Jun 3 21:21:06 2010 From: denis.spir at gmail.com (spir) Date: Thu, 3 Jun 2010 21:21:06 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: References: Message-ID: <20100603212106.48a34745@o> On Thu, 3 Jun 2010 11:50:42 -0400 Tino Dai wrote: > Hi All, > > Is there a way to express this: > isThumbnail = False > if size == "thumbnail": > isThumbnail = True > > like this: > [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] > and the scoping extending to one level above without resorting to the > global keyword? If you are not in a function, then your question does not make sense for python. If you are in a function, then isThumbnail must have been defined before and you must use global, yes. Thus, maybe no need for complicated expression: isThumbnail = False; def f(size): global isThumbnail if size == "thumbnail": isThumbnail = True > Thanks, > Tino -- ________________________________ vit esse estrany ? spir.wikidot.com From vincent at vincentdavis.net Thu Jun 3 21:41:31 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Thu, 3 Jun 2010 13:41:31 -0600 Subject: [Tutor] parse text file In-Reply-To: References: <201006021012.07227.steve@pearwood.info> <201006030741.41477.steve@pearwood.info> <4C07F5FD.2010207@ieee.org> Message-ID: On Thu, Jun 3, 2010 at 1:02 PM, Colin Talbert wrote: > > Dave, > I think you are probably right about using decompressor. I > couldn't find any example of it in use and wasn't having any luck getting it > to work based on the documentation. Maybe I should try harder on this > front. > Is it possible write a python script to transfer this to a hdf5 file? Would this help? Thanks Vincent > Colin Talbert > GIS Specialist > US Geological Survey - Fort Collins Science Center > 2150 Centre Ave. Bldg. C > Fort Collins, CO 80526 > > (970) 226-9425 > talbertc at usgs.gov > > > > From: Dave Angel To: > Colin Talbert > Cc: Steven D'Aprano , tutor at python.org Date: 06/03/2010 > 12:36 PM Subject: Re: [Tutor] parse text file > ------------------------------ > > > > Colin Talbert wrote: > > > > You are so correct. I'd been trying numerous things to read in this file > > > and had deleted the code that I meant to put here and so wrote this from > > memory incorrectly. The code that I wrote should have been: > > > > import bz2 > > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > > str=input_file.read() > > len(str) > > > > Which indeed does return only 900000. > > > > Which is also the number returned when you sum the length of all the > lines > > returned in a for line in file with: > > > > > > import bz2 > > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > > lengthz = 0 > > for uline in input_file: > > lengthz = lengthz + len(uline) > > > > print lengthz > > > > > > > > > Seems to me for such a large file you'd have to use > bz2.BZ2Decompressor. I have no experience with it, but its purpose is > for sequential decompression -- decompression where not all the data is > simultaneously available in memory. > > DaveA > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jun 4 00:03:34 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 3 Jun 2010 18:03:34 -0400 Subject: [Tutor] sockets, servers, clients, broadcasts...? Message-ID: Hi all, I am a CS major, so I have had the required networking class. I get the principles of networking, sockets, and packets, but I have never had to actually implement any such principles in any program. Now I have this Battleship game (not a school assignment, just a summer project) that I am trying to make playable over the internet, since I have not written the AI and playing Battleship against oneself is rather boring. Right now I am just trying to figure out how to implement something like the following: *you start the program and select "online game" *you select "server" or "client" (say you choose "server") *somehow, your instance of the program starts up a server that broadcasts something; your enemy has selected "client", and is now (SOMEHOW) listening for the signal your server is broadcasting *the signal is picked up, and, SOMEHOW, you and your opponent connect and can start sending and receiving data. First, how does the client know where to look for the server? I am not above popping up the server's ip and making the client type it in, but a better solution would be great. How do I make it so that the client can find the server correctly? The above IP is one thing, but are ports important here? Not a big deal if they are, but I am not sure. Does someone have an example of this process? Thanks. I know I have emailed this list (and other lists) before about this, but my peer-to-peer has not even started to look promising yet, since this is my first time ever doing anything remotely like this from a programming perspective, in any language. For now, it is all a frustrating and confusing tangle of Socket objects and low-level calls, but hopefully things will start to clear up over the next few days. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From sander.sweers at gmail.com Fri Jun 4 00:12:27 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 4 Jun 2010 00:12:27 +0200 Subject: [Tutor] parse text file In-Reply-To: References: <201006021012.07227.steve@pearwood.info> <201006030741.41477.steve@pearwood.info> <4C07F5FD.2010207@ieee.org> Message-ID: On 3 June 2010 21:02, Colin Talbert wrote: > I couldn't find any example of it in use and wasn't having any luck getting > it to work based on the documentation. Good examples of the bz2 module can be found at [1]. greets Sander [1] http://www.doughellmann.com/PyMOTW/bz2/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Jun 4 00:21:45 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 03 Jun 2010 15:21:45 -0700 Subject: [Tutor] Misc question about scoping In-Reply-To: References: Message-ID: On 6/3/2010 8:50 AM Tino Dai said... > Hi All, > > Is there a way to express this: > isThumbnail = False > if size == "thumbnail": > isThumbnail = True > > like this: > [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] > and the scoping extending to one level above without resorting to the > global keyword? If by 'extending one level above' you mean 'outside the current scope', then yes if isThumbnail is mutable. ie, something like: isThumbnail = [False] # create scope def inner(size): isThumbnail[0] = bool(size == "thumbnail") inner('not thumbnail') print isThumbnail inner('thumbnail') print isThumbnail From alan.gauld at btinternet.com Fri Jun 4 00:58:54 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Jun 2010 23:58:54 +0100 Subject: [Tutor] sockets, servers, clients, broadcasts...? References: Message-ID: "Alex Hall" wrote > *somehow, your instance of the program starts up a server that > broadcasts something; your enemy has selected "client", and is now > (SOMEHOW) listening for the signal your server is broadcasting > *the signal is picked up, and, SOMEHOW, you and your opponent > connect > and can start sending and receiving data. You can use IP broadcasts to do this but its not very network friendly. The usual approach is for the IP address/port to be published in some way - thats how email, ftp, the web etc all work. The ports are standardised(25 for SMTP, 80 for WWW etc) but the IP address needs to be published. I'd certainly start with that approach and add broadcast and auro-discovery as a feature later. > First, how does the client know where to look for the server? I am > not > above popping up the server's ip and making the client type it in, > but > a better solution would be great. I'd get it working using a fixed IP first, wiorry about broadcasting after the basics are there. > How do I make it so that the client can find the server correctly? > The > above IP is one thing, but are ports important here? Yes, you need IP address plus port number. Best done in a config file or similar. For peer to peer you can have a list of addresses and poll them till you get a response but if you are using DHCP you will need a range and broadcast starts to be better. For now I'd stick with each process displaing the IP address and the users typing them in. > they are, but I am not sure. Does someone have an example of this > process? Any internet protocol, incluiding SMTP email or FTP... For a more peer to peer approach think about IM clients. Netmeeting etc > from a programming perspective, in any language. For now, it is all > a > frustrating and confusing tangle of Socket objects and low-level > calls, Get the basics first. You still need to work out your command protocol to play the game. That will be challenging enough to start with. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 4 01:00:13 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 3 Jun 2010 23:00:13 +0000 (GMT) Subject: [Tutor] Fw: Misc question about scoping In-Reply-To: References: Message-ID: <285118.11629.qm@web86704.mail.ird.yahoo.com> Fowarding to the list. Remember to use Reply ALL when replying. Alan G. "Tino Dai" wrote >>> >>> >>>>>>> Is there a way to express this: >>>>>>>> isThumbnail = False >>>>>>>> if size == "thumbnail": >>>>>>>> isThumbnail = True >>>> >>>>>>>> like this: >>>>>>>> [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] >>>> >>> >>>Bob showed one way, you could also do: >>> >>>>>>isThumbnail = True if size == "thumbnail" else False >>> >>> >>> >>>>>>> and the scoping extending to one level above without resorting to the >>>>>>>>global keyword? >>>> >>> >>>Not sure what this has to do with scoping or the use of global? >>>>>>global is only needed inside a function if you are modifying a >>>>>>value defined outside the function. >>> >>>>>>If the assignment is inside a function and the definition of >>>>>>isThumbnail is outside then you need to use global. >>> >>>>>>HTH, >>> >>> >> >>Hi Bob, Alan, and Joel, >> >> I may have used scoping in an incorrect way. To clear things up, let me try to explain my general issue: >> >> I have code that is unpythonic in many places. It works, but it's ugly. One of those unpythonic places is I'm initializing some variable such as a list,dict, or whatever outside of if/while/for in block to use later. So, I'm cleaning those places up. >> >> For example, my present code looks like: >> L = [] # Needed or L doesn't exist outside of for loop below >> for o in a: >> if o.someAttribute > someConstant: >> L.append(o.someOtherAttribute) >>>> >> .... later in code .... >> >> >> Would like my code to resemble (don't know if this code works): >> L = [o.someOtherAttribute if o.someAttribute > someConstant else pass for o in a] >>>> >> .... later in code .... >> >> >> Does that make more sense? >> >>TIA, >>Tino >>On Thu, Jun 3, 2010 at 1:10 PM, Alan Gauld wrote: >> >Here is some actual code that I working on right now: > >First iteration: >>answerDict={} >for key in qas[0].fk_question.q_WidgetChoice.all(): > answerDict[str(key.widgetChoice)]=0 > >Second iteration: >answerDict=dict([(str(key.widgetChoice),0) for key in qas[0].fk_question.q_widgetChoice.all()]) > >Third iteration: >answerDict=dict(map(lambda x: \ > (str(x.widgetChoice),0),qas[0].fk_question.q_WidgetChoice.all())) > >The third iteration is what I'm looking for. > >-Tino >On Thu, Jun 3, 2010 at 1:39 PM, Tino Dai wrote: > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 4 01:46:45 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 4 Jun 2010 09:46:45 +1000 Subject: [Tutor] parse text file In-Reply-To: References: <201006030741.41477.steve@pearwood.info> Message-ID: <201006040946.45839.steve@pearwood.info> On Fri, 4 Jun 2010 12:45:52 am Colin Talbert wrote: > I thought when you did a for uline in input_file each single line > would go into memory independently, not the entire file. for line in file: reads one line at a time, but file.read() tries to read everything in one go. However, it should fail with MemoryError, not just stop silently. > I'm pretty sure that this is not your code, because you can't call > len() on a bz2 file. If you try, you get an error: > > You are so correct. I'd been trying numerous things to read in this > file and had deleted the code that I meant to put here and so wrote > this from memory incorrectly. The code that I wrote should have > been: > > import bz2 > input_file = bz2.BZ2File(r'C:\temp\planet-latest.osm.bz2','rb') > str=input_file.read() > len(str) > > Which indeed does return only 900000. Unfortunately, I can't download your bz2 file myself to test it, but I think I *may* have found the problem. It looks like the current bz2 module only supports files written as a single stream, and not multiple stream files. This is why the BZ2File class has no "append" mode. See this bug report: http://bugs.python.org/issue1625 My hypothesis is that your bz2 file consists of either multiple streams, or multiple bz2 files concatenated together, and the BZ2File class stops reading after the first. I can test my hypothesis: >>> bz2.BZ2File('a.bz2', 'w').write('this is the first chunk of text') >>> bz2.BZ2File('b.bz2', 'w').write('this is the second chunk of text') >>> bz2.BZ2File('c.bz2', 'w').write('this is the third chunk of text') >>> # concatenate the files ... d = file('concate.bz2', 'w') >>> for name in "abc": ... f = file('%c.bz2' % name, 'rb') ... d.write(f.read()) ... >>> d.close() >>> >>> bz2.BZ2File('concate.bz2', 'r').read() 'this is the first chunk of text' And sure enough, BZ2File only sees the first chunk of text! But if I open it in a stand-alone bz2 utility (I use the Linux application Ark), I can see all three chunks of text. So I think we have a successful test of the hypothesis. Assuming this is the problem you are having, you have a number of possible solutions: (1) Re-create the bz2 file from a single stream. (2) Use another application to expand the bz2 file and then read directly from that, skipping BZ2File altogether. (3) Upgrade to Python 2.7 or 3.2, and hope the patch is applied. (4) Backport the patch to your version of Python and apply it yourself. (5) Write your own bz2 utility. Not really a very appetising series of choices there, I must admit. Probably (1) or (2) are the least worst. -- Steven D'Aprano From steve at pearwood.info Fri Jun 4 01:56:42 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 4 Jun 2010 09:56:42 +1000 Subject: [Tutor] Fw: Misc question about scoping In-Reply-To: <285118.11629.qm@web86704.mail.ird.yahoo.com> References: <285118.11629.qm@web86704.mail.ird.yahoo.com> Message-ID: <201006040956.42937.steve@pearwood.info> On Fri, 4 Jun 2010 09:00:13 am ALAN GAULD quoted Tino Dai who wrote: > "Tino Dai" wrote [...] > >> I have code that is unpythonic in many places. It works, but > >> it's ugly. One of those unpythonic places is I'm initializing some > >> variable such as a list,dict, or whatever outside of if/while/for > >> in block to use later. So, I'm cleaning those places up. > >> > >> For example, my present code looks like: > >> L = [] # Needed or L doesn't exist outside of for loop > >> below for o in a: > >> if o.someAttribute > someConstant: > >> L.append(o.someOtherAttribute) > >> > >> .... later in code .... > >> There's nothing unpythonic about that code. For loops existed in Python since the very earliest days, which is *at least* 1991, while list comprehensions are a newcomer. But if you insist on a list comprehension, you can re-write the above for-loop as: L = [o.someOtherAttribute for o in a if o.someAttribute > someConstant] -- Steven D'Aprano From steve at pearwood.info Fri Jun 4 02:13:28 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 4 Jun 2010 10:13:28 +1000 Subject: [Tutor] Misc question about scoping In-Reply-To: References: Message-ID: <201006041013.28220.steve@pearwood.info> On Fri, 4 Jun 2010 03:10:41 am Alan Gauld wrote: > "Tino Dai" wrote > > > Is there a way to express this: > > isThumbnail = False > > if size == "thumbnail": > > isThumbnail = True > > > > like this: > > [ isThumbnail = True if size == "thumbnail" isThumbnail = > > False ] > > Bob showed one way, you could also do: > > isThumbnail = True if size == "thumbnail" else False That is technically correct, you could do that. That's a good example of the syntax of the `if` expression, but it's a bad example of where to use it: (1) it only works in Python 2.5 or better; and (2) experienced Python programmers will laugh at you :) with all due respect to Alan who suggested it. It really is an unnecessarily complicated and verbose way of doing a simple assignment, nearly as bad as writing this: if len(mystring) == 0: n = 0 else: n = len(mystring) instead of just n = len(mystring) -- Steven D'Aprano From goodpotatoes at yahoo.com Fri Jun 4 02:57:07 2010 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Thu, 3 Jun 2010 17:57:07 -0700 (PDT) Subject: [Tutor] From SQL Blobs to Python Buffers to Actual Files In-Reply-To: <201006041013.28220.steve@pearwood.info> References: <201006041013.28220.steve@pearwood.info> Message-ID: <210017.22457.qm@web51906.mail.re2.yahoo.com> Environment: Sybase/ODBC/Windows/Python2.5 I have been given a legacy database, and need to read the binaryfiles out to a disk. The table has columns "filename" and "binaryFile", where the binaryFile is a BLOB My python script so far is: import pyodbc cnxn=pyodbc.Connection("DSN=sybasedatabase") cursor=cnxn.cursor() p=cursor.execute("select top 1 * from FOO..Table").fetchone() #p contains ('UsersOldFile.rtf', ) #I tried to write this out to the disk as: myfile=open(p[0],'wb') myfile.write(p[1]) myfile.close() #but all I get is gibberish. Is there another way to handle the buffer, or something else I'm missing? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 4 06:18:44 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 4 Jun 2010 14:18:44 +1000 Subject: [Tutor] From SQL Blobs to Python Buffers to Actual Files In-Reply-To: <210017.22457.qm@web51906.mail.re2.yahoo.com> References: <201006041013.28220.steve@pearwood.info> <210017.22457.qm@web51906.mail.re2.yahoo.com> Message-ID: <201006041418.44223.steve@pearwood.info> On Fri, 4 Jun 2010 10:57:07 am GoodPotatoes wrote: > I have been given a legacy database, and need to read the binaryfiles > out to a disk. The table has columns "filename" and "binaryFile", > where the binaryFile is a BLOB > > My python script so far is: > > import pyodbc > cnxn=pyodbc.Connection("DSN=sybasedatabase") > cursor=cnxn.cursor() > p=cursor.execute("select top 1 * from FOO..Table").fetchone() > #p contains ('UsersOldFile.rtf', size 1496, offset 0 at 0x010C04E0>) > > #I tried to write this out to the disk as: > myfile=open(p[0],'wb') > myfile.write(p[1]) > myfile.close() > > #but all I get is gibberish. Is there another way to handle the > buffer, or something else I'm missing? What do you mean "gibberish"? I would expect a binary blob to look exactly like random binary characters, in other words, gibberish, so what makes you think this is not working perfectly? What do you get if you print the binary blob, and what do you expect to get? -- Steven D'Aprano From trezorg at gmail.com Fri Jun 4 09:21:44 2010 From: trezorg at gmail.com (Igor Nemilentsev) Date: Fri, 4 Jun 2010 07:21:44 +0000 (UTC) Subject: [Tutor] video watermark Message-ID: Hi everyone. Can someone suggest a python module so that it would be able to do a video processing and adding watermark in video? -- "If it's not loud, it doesn't work!" -- Blank Reg, from "Max Headroom" From alan.gauld at btinternet.com Fri Jun 4 10:08:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Jun 2010 09:08:02 +0100 Subject: [Tutor] Misc question about scoping References: <201006041013.28220.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> isThumbnail = True if size == "thumbnail" else False > > That is technically correct, you could do that. That's a good > example of > the syntax of the `if` expression, but it's a bad example of where > to > use it: In the sense that an equality test will always give a real boolean value as a result I agree. But in the more generic case where we use an expressiioon as a boolean it can be usful. Specifically if the test involves boolean operators Python does not return True/False but the values of the operands. In that case using the if/else form yields a real boolean result. eg flag = True if (smoeValue or another) else False is different to flag = someValue or another Which was why I thought it worth pointing out that the if/else could be used. > with all due respect to Alan who suggested it. It really is an > unnecessarily complicated and verbose way of doing a > simple assignment, In the case of an equality test I agree. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at gmail.com Fri Jun 4 10:42:54 2010 From: denis.spir at gmail.com (spir) Date: Fri, 4 Jun 2010 10:42:54 +0200 Subject: [Tutor] sockets, servers, clients, broadcasts...? In-Reply-To: References: Message-ID: <20100604104254.33e4a8ef@o> On Thu, 3 Jun 2010 18:03:34 -0400 Alex Hall wrote: > Hi all, > I am a CS major, so I have had the required networking class. I get > the principles of networking, sockets, and packets, but I have never > had to actually implement any such principles in any program. Now I > have this Battleship game (not a school assignment, just a summer > project) that I am trying to make playable over the internet, since I > have not written the AI and playing Battleship against oneself is > rather boring. > > Right now I am just trying to figure out how to implement something > like the following: > *you start the program and select "online game" > *you select "server" or "client" (say you choose "server") > *somehow, your instance of the program starts up a server that > broadcasts something; your enemy has selected "client", and is now > (SOMEHOW) listening for the signal your server is broadcasting > *the signal is picked up, and, SOMEHOW, you and your opponent connect > and can start sending and receiving data. > > First, how does the client know where to look for the server? I am not > above popping up the server's ip and making the client type it in, but > a better solution would be great. > How do I make it so that the client can find the server correctly? The > above IP is one thing, but are ports important here? Not a big deal if > they are, but I am not sure. Does someone have an example of this > process? I'm far to be a specialist in this field, so this is just reasoning by watching your requirements. First, such a game seems to match peer-to-peer relation. This would be different if you implemented complicated game logic, like in the case of an AI playing. For peers to connect, a general solution is them to register on a dedicated public interface (the same can be used to publish a server's IP, indeed). Then, your app first reads data there to know which (address,port) pair(s) are available. But since you seem to be still exploring data exchange issues, you'd better concentrate on this basic mechanism first, choose and try one of numerous possible solutions, then only address higher-level problems. In the meanwhile, just put IPs and ports in a config file or even hardcode them as constants. About client-server, as said above, this model does not really seem to match your use case, I guess. But this is still an interesting alternative. I would set my own post as server and players as clients. So, when playing myself, I would be a local client. This indeed allows two other guys playing using your post as server (and you maybe watching the game ;-). But this does not make much sense if the server does not have any relevant info to deliver (eg playing hints). Denis ________________________________ vit esse estrany ? spir.wikidot.com From john_re at fastmail.us Fri Jun 4 12:51:21 2010 From: john_re at fastmail.us (giovanni_re) Date: Fri, 04 Jun 2010 03:51:21 -0700 Subject: [Tutor] BerkeleyTIP Join June Global Free SW HW Culture Mtgs via VOIP or in Berkeley Message-ID: <1275648681.6809.1378441381@webmail.messagingengine.com> Hi Python Tutor people :) Who leads this group? I put together a global meeting (via voip) that 1) has an interest in Python, 2) and that Python learners, users & developers might be interested in. BerkeleyTIP is a meeting about All Free SW HW & Culture. It is Educational, Productive, & Social. For Learning about, Sharing, & Producing, All Free SW HW & Culture. TIP == Talks, Installfest, Project & Programming Party http://sites.google.com/site/berkeleytip I put these meetings together in my nonexistent "free" time, as a volunteer contribution to the various communities. When i can make the time, I send out one announcement per month with the monthly videos to various free SW HW & Culture groups. Would you all would like to have me send your list the monthly announcements about the global via VOIP Free SW, HW & Culture meetings, BerkeleyTIP global? Please let me know. :) Below is the June announcement, so you know what they are like. We have a python video this month, too: Scientific data visualization using Mayavi2, Gael Varoquaux, Python4ScienceUCB Best wishes :) ===== You're invited to join in with the friendly people at the BerkeleyTIP global meeting - newbie to Ph.D. - everyone is invited. Get a headset & join using VOIP online, or come to Berkeley. 1st step: Join the mailing list: http://groups.google.com/group/BerkTIPGlobal Watch the videos. Discuss them on VOIP. 8 great videos/talks this month - see below. Starting off year 3 of BerkeleyTIP :) Join with us at the LOCATION TO BE DETERMINED at the University of California at Berkeley, or join from your home via VOIP, or send this email locally, create a local meeting, & join via VOIP: Tip: a wifi cafe is a great place to meet. :) JUNE 5 & 20 AT UCB MEETING LOCATIONS TO BE DETERMINED. PLEASE VIEW THE BTIP WEBSITE & MAILING LIST PAGES FOR THE LATEST DETIALS. http://sites.google.com/site/berkeleytip http://groups.google.com/group/BerkTIPGlobal BerkeleyTIP - Educational, Productive, Social For Learning about, Sharing, & Producing, All Free SW HW & Culture. TIP == Talks, Installfest, Project & Programming Party http://sites.google.com/site/berkeleytip ===== CONTENTS: 1) 2010 JUNE VIDEOS; 2) 2010 JUNE MEETING DAYS, TIMES, LOCATIONS; 3) LOCAL MEETING AT U. C. Berkeley LOCATION TO BE DETERMINED; 4) HOT TOPICS; 5) PLEASE RSVP PROBABILISTICALLY, THANKS :) ; 6) INSTALLFEST; SPECIAL: FREE 7th Annual BERKELEY WORLD MUSIC FESTIVAL June 5 Sat; 7) ARRIVING FIRST AT THE MEETING: MAKE A "BerkeleyTIP" SIGN; 8) IRC: #berkeleytip on irc.freenode.net; 9) VOIP FOR GLOBAL MEETING; 10) VOLUNTEERING, TO DOs; 11) MAILING LISTS: BerkeleyTIP-Global, LocalBerkeley, Announce; 12) ANYTHING I FORGOT TO MENTION?; 13) FOR FORWARDING ======================================================================= ===== 1) 2010 JUNE VIDEOS Super Computing for Business, Brian Modra, CLUG State of the Linux Union 2010, Jim Zemlin, Linux Foundation Journaled Soft-Updates, Dr. Kirk McKusick, BSDCan 2010 Scientific data visualization using Mayavi2, Gael Varoquaux, Python4ScienceUCB Bringing OLPC to children in Afghanistan, Carol Ruth Silver, OLPC-SF Text-to-Speech in Ubuntu with Kttsd Kmouth Festival, blip.tv Rabbi Rabbs, the UnixRabbi, leads a group of Unix geeks, Comedy, UUASC, BS"D, 2003 The Great Debate - Are We Alone?, Geoff Marcy and Dan Werthimer, SETI at UC Berkeley Thanks to all the speakers, organizations, & videographers. :) [Please alert the speakers that their talks are scheduled for June for BTIP (if you are with the group that recorded their talk), because I may not have time to do that. Thanks. :) ] URLs for video download & full details: http://sites.google.com/site/berkeleytip/talk-videos Download & watch these talks before the BTIP meetings. Discuss at the meeting. Email the mailing list, tell us what videos you'll watch & want to discuss: http://groups.google.com/group/BerkTIPGlobal Know any other video sources? - please email me. _Your_ group should video record & post online your meeting's talks! ===== 2) 2010 JUNE MEETING DAYS, TIMES, LOCATIONS In person meetings on 1st Saturday & 3rd Sunday, every month. June 5 & 20, 12N-3P USA-Pacific time, Saturday, Sunday Online only meeting using VOIP: June 14 & 29, 5-6P USA-Pacific time, Monday, Tuesday Mark your calendars. 5 Sat 12N-3P PDST = 3-6P EDST = 19-22 UTC 14 Mon 5-6P PDST = 8-9P EDST = 0- 1 UTC Tues 15 20 Sun 12N-3P PDST = 3-6P EDST = 19-22 UTC 29 Tues 5-6P PDST = 8-9P EDST = 0- 1 UTC Wed 30 USA-PacificDaylightSavingsTime is -7 hours UTC, due to daylight savings currently. Times listed above should be double checked by you for accuracy. ===== 3) LOCAL MEETING AT U. C. BERKELEY - LOCATION TO BE DETERMINED http://sites.google.com/site/berkeleytip/directions RSVP please. See below. It greatly helps my planning. But, _do_ come if you forgot to RSVP. THE JUNE 5 & 20 ON CAMPUS MEETING LOCATIONS ARE CURRENTLY TO BE DETERMINED. HOPEFULLY KNOW ON FRIDAY JUNE 4. PLEASE VIEW THE BTIP WEBSITE & MAILING LIST FOR THE FINALIZED LOCATION. THANK YOU. ALWAYS BE SURE TO CHECK THE BTIP WEBSITE _&_ MAILING LIST FOR THE LATEST LAST MINUTE DETAILS & CHANGES, BEFORE COMING TO THE MEETING! :) http://sites.google.com/site/berkeleytip http://groups.google.com/group/BerkTIPGlobal DO BRING A VOIP HEADSET, available for $10-30 at most electronics retail stores, & a laptop computer, so you are able to communicate with the global BTIP community via VOIP. It is highly recommended that you have a voip headset, & not rely on a laptop's built in microphone & speakers, because the headphones keep the noise level down. Bringing a headset is not required, but is a great part of the being able to communicate with the global community. :) Clothing: Typically 55-80 degrees F. Weather: http://www.wunderground.com/auto/sfgate/CA/Berkeley.html Other location local meeting possibilities: http://sites.google.com/site/berkeleytip/local-meetings Create a local meeting in your town. ===== 4) HOT TOPICS Oracle owns Sun - Free SW implications? OpenOffice? OpenOffice - Ready for college Fall 2010? MakerBot, RepRap - Personal Making - Like where PCs were in 1975? Android phones - Besting iPhone? worthwhile? How knowable is the hw? - Can BSD be run on Android phones? iPad, iPhone & iPod- rooting & running GNU(Linux) & BSD ===== 5) PLEASE RSVP PROBABILISTICALLY, THANKS :) If you think there is a >70% chance ("likely") you'll come to the in person meeting in Berkeley, please RSVP to me. Thanks. It helps my planning. Please _do_ come even if you haven't RSVP'd, it's not required. Better yet, join the BerkeleyTIP-Global mailing list, send the RSVP there, & tell us what things you're interested in, or what videos you'll try to watch - so we can know what videos are popular, & we might watch them too. :) http://groups.google.com/group/BerkTIPGlobal ===== 6) INSTALLFEST Get help installing & using Free Software, Hardware & Culture. Laptops only, typically. There isn't easy access for physically bringing desktop boxes here. RSVP _HIGHLY RECOMMENDED_ if you want installfest help. Please RSVP to me, Giovanni, at the from address for this announcement, or better, join & send email to the BTIP-Global mailing list telling us what you'd like help with. This way we can be better prepared to help you, & you might get valuable advice from the mailing list members. If you are new to using free software, an excellent system would be the KUbuntu GNU(Linux) software. It is very comprehensive, fairly easy to use (similar to Windows or Mac), & suitable for personal, home, university, or business use. We are also glad to try to help people with software who join via VOIP. Please email the mailing list with requests that you want help with, so we can try to be prepared better to help you. Installfest volunteers/helpers always welcome, in person, or via VOIP. :) ===== SPECIAL - MUSIC IN BERKELEY JUNE 5 SATURDAY ===== Also June 5 Sat in Berkeley, after BTIP: ===== FREE 7th Annual BERKELEY WORLD MUSIC FESTIVAL ===== Telegraph Avenue 12 Noon - 9 pm "Berkeley World Music Fest... has some of our best world musicians who call East Bay home...a wonderful event, and intimate, mix of outdoor performances in cafes and shops(the best music People's Park gets each year along Telegraph Ave. (Larry Kelp, KPFA music host)" Continuous music outdoors & in cafes http://www.berkeleyworldmusic.com/entry.asp?PageID=118 ===== 7) ARRIVING FIRST AT THE MEETING: MAKE A "BerkeleyTIP" SIGN If you get to the meeting & don't see a "BerkeleyTIP" sign up yet, please: 1) Make a BTIP sign on an 8x11 paper & put it at your table, 2) Email the mailing list, or join on IRC, & let us know you are there. Ask someone if you could use their computer for a minute to look something up, or send an email. People are usually very friendly & willing to help. We can also email you a temporary guest AirBears account login. We will have wifi guest accounts available for BTIP attendees. Be sure you have wifi capable equipment. Be Prepared: Bring a multi-outlet extension power cord. ===== 8) IRC: #berkeleytip on irc.freenode.net For help with anything, especially how to get VOIP working, & text communication. ===== 9) VOIP FOR GLOBAL MEETING Speak & listen to everyone globally using VOIP. Get a headset! See some VOIP instructions here: http://sites.google.com/site/berkeleytip/voice-voip-conferencing ===== 10) VOLUNTEERING, TO DOs Enjoy doing or learning something(s)? Help out BTIP in that area. Website development, mailing list management, video locating, VOIP server (FreeSwitch, Asterisk) or client (Ekiga, SFLPhone,...), creating a local meeting. Join the mailing list & let us know. Your offers of free help are always welcome here. :) ===== 11) MAILING LISTS: BerkeleyTIP-Global, LocalBerkeley, Announce Everyone should join the BerkeleyTIP-Global list: http://groups.google.com/group/BerkTIPGlobal Say "hi", tell us your interests, & what videos you'll like to watch. Info on all lists here: http://sites.google.com/site/berkeleytip/mailing-lists ===== 12) ANYTHING I FORGOT TO MENTION? Please join & email the BerkeleyTIP-Global mailing list. ===== 13) FOR FORWARDING You are invited to forward this message anywhere it would be appreciated. Better yet, use it to create a local meeting. Invite & get together with your friends locally, & join in with us all globally. :) Looking forward to meeting with you in person, or online. :) Giovanni From davea at ieee.org Fri Jun 4 13:23:39 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 04 Jun 2010 07:23:39 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: <4C08E23B.7060704@ieee.org> Alan Gauld wrote: > > > flag = True if (smoeValue or another) else False > > is different to > > flag = someValue or another > > Which was why I thought it worth pointing out that the if/else > could be used. > > I'd prefer the form: flag = not not (someValue or another) if I needed real True or False result. DaveA From oberoc at gmail.com Fri Jun 4 14:46:20 2010 From: oberoc at gmail.com (Tino Dai) Date: Fri, 4 Jun 2010 08:46:20 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: <201006041013.28220.steve@pearwood.info> References: <201006041013.28220.steve@pearwood.info> Message-ID: > That is technically correct, you could do that. That's a good example of > the syntax of the `if` expression, but it's a bad example of where to > use it: > > (1) it only works in Python 2.5 or better; and > > (2) experienced Python programmers will laugh at you :) > > with all due respect to Alan who suggested it. It really is an > unnecessarily complicated and verbose way of doing a simple assignment, > nearly as bad as writing this: > > if len(mystring) == 0: > ? ?n = 0 > else: > ? ?n = len(mystring) > > > instead of just > > n = len(mystring) > > Hey Everybody, ??????? Thank you for the rich discussion and making me a better python programmer! Between the new topics that I have learned in Python and Django from documentation, experimentation, and this list, I think my IQ has gone up a couple of points! ??????? I'm at a point where I can do most things in Python (maybe) , now I'm looking to do them succinctly and elegantly. For instance, I had about 10 - 15 lines of code to do this before with a bunch of loops and if blocks, I distilled the product down to this: ?????? answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \ ??????? x.values(),Answer.objects.filter(fk_questionSet=1). \ ??????? filter(fk_question=1).values('widgetAnswer').order_by(). \ ??????? annotate(widgetCount=Count('widgetAnswer'))))) So instead of my python code doing the "leg work", I have the Django ORM and that underlying DB do the work. Also, I leveraged lambda functions and maps to coerce the data in to the right format. Pretty cool IMHO. And I turn it over to the group to see if there is any improvements or gotchas that I missed. Thanks and Thanks in advance, Tino From hugo.yoshi at gmail.com Fri Jun 4 16:31:11 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jun 2010 16:31:11 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: <4C08E23B.7060704@ieee.org> References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> Message-ID: On Fri, Jun 4, 2010 at 1:23 PM, Dave Angel wrote: > > I'd prefer the form: > > ?flag = not not (someValue or another) > That's a construct you might commonly find in languages like C, but I don't think it's very pythonic. If you want to convert your result to a bool, be explicit about it: flag = bool(some_value or another) I'd agree that the if/else construct is redundant if you just want a True/False result, but the double not is a kind of implicit type conversion that is easily avoided. Hugo From hugo.yoshi at gmail.com Fri Jun 4 16:52:03 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jun 2010 16:52:03 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: On Fri, Jun 4, 2010 at 2:46 PM, Tino Dai wrote: > > ??????? I'm at a point where I can do most things in Python (maybe) , > now I'm looking to do them succinctly and elegantly. For instance, I > had about 10 - 15 lines of code to do this before with a bunch of > loops and if blocks, I distilled the product down to this: > > ?????? answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \ > ??????? ? x.values(),Answer.objects.filter(fk_questionSet=1). \ > ??????? ? filter(fk_question=1).values('widgetAnswer').order_by(). \ > ??????? ? annotate(widgetCount=Count('widgetAnswer'))))) > I have a distinct feeling that you would simply love a language like lisp. > So instead of my python code doing the "leg work", I have the Django > ORM and that underlying DB do the work. Also, I leveraged lambda > functions and maps to coerce the data in to the right format. Pretty > cool IMHO. And I turn it over to the group to see if there is any > improvements or gotchas that I missed. > The code is succinct, and it may very well be called elegant in some sense of the word. I might call it "clever," which in the python community is not generally meant as a compliment. Readability counts, you see, and I find that piece of code nigh impossible to read. I would suggest changing the map calls into generator expressions, and using a few temporary variables for clarity. That should keep most of the brevity but increase legibility: answers = Answer.objects.filter(fk_questionSet=1, fk_question=1).values('widgetAnswer') answers = answers.order_by().annotate(widgetCount=Count('widgetAnswer')) values = (x.values() for x in answers) answerDict = dict((str(v[1]), v[0]) for v in values) Disclaimer: i'm not particularly experienced with django, so this piece of code is quite possibly not the most efficient way to do this, and may even be incorrect (e.g. I assumed the filter calls could be collapsed like in sqlAlchemy). However, the rest of my advice should still apply. Hugo From knacktus at googlemail.com Fri Jun 4 17:18:43 2010 From: knacktus at googlemail.com (Jan Jansen) Date: Fri, 04 Jun 2010 17:18:43 +0200 Subject: [Tutor] video watermark In-Reply-To: References: Message-ID: <4C091953.3050300@googlemail.com> Am 04.06.2010 09:21, schrieb Igor Nemilentsev: > Hi everyone. > Can someone suggest a python module so that it would be able to do a video > processing and adding watermark in video? > > Once I had to blur the part of the viewing area of a screencast which showed some confident CAD model. First, I exported the video as sequence of images with virtualdub. The result was something like 3000 *.bmp files on my harddrive. Then I created a little python script using PIL (http://www.pythonware.com/products/pil/). That script processed the files file by file, so no worries about huge movie files and memory. Finally, I've merged the new images with virtual dub. It all worked very well. Otherwise I'm not aware of any video processing library in Python. Also, there're filters for virtualdub to add watermarks to a movie. That might be the easiest way to get your results. Cheers, Jan From oberoc at gmail.com Fri Jun 4 18:26:20 2010 From: oberoc at gmail.com (Tino Dai) Date: Fri, 4 Jun 2010 12:26:20 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: > I have a distinct feeling that you would simply love a language like lisp. LOL, it's actually on the list of things to do. And hear that one will become a better programmer once they learn LISP. > The code is succinct, and it may very well be called elegant in some > sense of the word. I might call it "clever," which in the python > community is not generally meant as a compliment. Readability counts, > you see, and I find that piece of code nigh impossible to read. I > would suggest changing the map calls into generator expressions, and > using a few temporary variables for clarity. That should keep most of > the brevity but increase legibility: > > answers = Answer.objects.filter(fk_questionSet=1, > fk_question=1).values('widgetAnswer') > answers = answers.order_by().annotate(widgetCount=Count('widgetAnswer')) > values = (x.values() for x in answers) > answerDict = dict((str(v[1]), v[0]) for v in values) I am always fighting the battle - more compact vs more readable :) . A couple of questions that I have: Why generators over map? Is it somehow more efficient under the covers or is it for readability purposes? I noticed that you took out the lambda function too (not much good without a map/filter/reduce) to replace with the generator function. Also could you give me some instances where a generator would be used in a real situation? I have already read the stuff on doc.python.org about generators. Thanks, Tino From emile at fenx.com Fri Jun 4 18:57:42 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 04 Jun 2010 09:57:42 -0700 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: On 6/4/2010 5:46 AM Tino Dai said... > I'm at a point where I can do most things in Python (maybe) , > now I'm looking to do them succinctly and elegantly. For instance, I > had about 10 - 15 lines of code to do this before with a bunch of > loops and if blocks, I distilled the product down to this: > > answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \ > x.values(),Answer.objects.filter(fk_questionSet=1). \ > filter(fk_question=1).values('widgetAnswer').order_by(). \ > annotate(widgetCount=Count('widgetAnswer'))))) > The first time there's a suspected problem with this code, you'll probably end up with a similar refactored set of 10-15 lines. I'm sure because I've got code like that scattered throughout my codebase and that's what I end up doing. The difference is that I rattle off the one-liners as part of the original coding effort, and only break it out when there's a need to -- I'm not striving to compact things into one-liners. BTW, doesn't dict(map(lambda x: (str(x[1]),x[0]),map(lambda x:x.values() simply map the values of a dict back into a dict? Emile From jjcrump at uw.edu Fri Jun 4 19:15:26 2010 From: jjcrump at uw.edu (jjcrump at uw.edu) Date: Fri, 4 Jun 2010 10:15:26 -0700 (PDT) Subject: [Tutor] treeTraversal, nested return? Message-ID: All, any observations might be helpful. For the display of database contents I have the following problem: Database querys will return data to me in tuples of the following sort: each tuple has a unique id, a parent id, and a type. a parent id of 0 indicates that the element has no parent. not all data elements have children image elements have no children and must have a parent So the contents of the db is a tree of sorts: (1, 0, work) (555, 1, image) (556, 1, work) (557, 556, image) (558, 556, work) (559, 558, image) (560, 558, work) (561, 556, image) (562, 556, image) (563, 1, work) (564, 563, work) (565, 1, work) I have a function that will traverse this tree, summoning lists of tuples at each leaf. Well and good; it took a lot of trial and error, but it was a fine education in tree traversal. def makeHeirarchy(id): id = parentPath(id)[-1] rootimages = getImages(id[0]) rootworks = getWorks(id[0]) heirarchy = treeTraversal(rootworks, [id, rootimages]) return heirarchy ## which calls this recursive function: def treeTraversal(listIn,result): for x in listIn: if not getWorks(x[0]): result.append(x) result.append(getImages(x[0])) else: result.append(x) result.append(getImages(x[0])) treeTraversal(getWorks(x[0]), result) return result My problem is that this returns the tuples to me in a flat list. I've been trying to work out how I can get it to return some sort of nested structure: nested lists, dictionaries, or html thus:
  • 1,0,data
    • 555, 1, image
    • 556, 1, data
      • 557, 556, image
      • 561, 556, image
      • 562, 556, image
      • 558, 556, data
        • 559, 558, image
        • 560, 558, image
    • 563, 1, data
      • 564, 563, data
    • 565, 1, data
From goodpotatoes at yahoo.com Fri Jun 4 19:51:02 2010 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Fri, 4 Jun 2010 10:51:02 -0700 (PDT) Subject: [Tutor] From SQL Blobs to Python Buffers to Actual Files In-Reply-To: <201006041418.44223.steve@pearwood.info> References: <201006041013.28220.steve@pearwood.info> <210017.22457.qm@web51906.mail.re2.yahoo.com> <201006041418.44223.steve@pearwood.info> Message-ID: <269042.23910.qm@web51904.mail.re2.yahoo.com> When I write the blob/binary data to a file and give it its original file name "customer1.rtf", I am expecting the application to read the binary data into text,excel,word documents, or whatever application created the file originally. Example: when I write blob1 to customer1.rtf, I get "x??VKs?6?93?{????2%??c?lg?d?<&v???\J?" as my first line. To get the blob in Python, I use the following: row=cursor.execute("select top 1 * from FOO..DocUploads").fetchone() #row[2] is the original file name, row[3] is the binary data The blob, when selected in python is a buffer: >>> row[3] When I print row[3] I get data like "x?VKs?6?93?{????2%?" When I print str(row[3]) I get the same data. ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Thu, June 3, 2010 9:18:44 PM Subject: Re: [Tutor] From SQL Blobs to Python Buffers to Actual Files On Fri, 4 Jun 2010 10:57:07 am GoodPotatoes wrote: > I have been given a legacy database, and need to read the binaryfiles > out to a disk. The table has columns "filename" and "binaryFile", > where the binaryFile is a BLOB > > My python script so far is: > > import pyodbc > cnxn=pyodbc.Connection("DSN=sybasedatabase") > cursor=cnxn.cursor() > p=cursor.execute("select top 1 * from FOO..Table").fetchone() > #p contains ('UsersOldFile.rtf', size 1496, offset 0 at 0x010C04E0>) > > #I tried to write this out to the disk as: > myfile=open(p[0],'wb') > myfile.write(p[1]) > myfile.close() > > #but all I get is gibberish. Is there another way to handle the > buffer, or something else I'm missing? What do you mean "gibberish"? I would expect a binary blob to look exactly like random binary characters, in other words, gibberish, so what makes you think this is not working perfectly? What do you get if you print the binary blob, and what do you expect to get? -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From woodm1979 at gmail.com Fri Jun 4 20:08:56 2010 From: woodm1979 at gmail.com (Matthew Wood) Date: Fri, 4 Jun 2010 12:08:56 -0600 Subject: [Tutor] treeTraversal, nested return? In-Reply-To: References: Message-ID: In general, there's 2 solutions to your "unflattening" problem. A) The general solution: Keep track of the depth you're at, and add tabs/spaces ('\t' * depth) as necessary. B) The xml solution: Use (for example) the dom.minidom module, and create a new "ul node" and populate it with children, at each level. Then, have the xml do the printing for you. For what it's worth, I may have a slight nit-pick of your final output. I don't believe you can technically have a
    child of a
      node. I'm not absolutely sure on that, but my quick google searching has appeared to confirm. If that turns out to be true, you'll need to change the structure of your output.
      • 1,0,data
        • 555,1,image
        • ...
      All of that is, of course, null and void if you define your own xml scheme. -- I enjoy haiku but sometimes they don't make sense; refrigerator? On Fri, Jun 4, 2010 at 11:15 AM, wrote: > All, > > any observations might be helpful. For the display of database contents I > have the following problem: > > Database querys will return data to me in tuples of the following sort: > each tuple has a unique id, a parent id, and a type. > > a parent id of 0 indicates that the element has no parent. > not all data elements have children > image elements have no children and must have a parent > > So the contents of the db is a tree of sorts: > > (1, 0, work) > (555, 1, image) > (556, 1, work) > (557, 556, image) > (558, 556, work) > (559, 558, image) > (560, 558, work) > (561, 556, image) > (562, 556, image) > (563, 1, work) > (564, 563, work) > (565, 1, work) > > I have a function that will traverse this tree, summoning lists of tuples > at each leaf. Well and good; it took a lot of trial and error, but it was a > fine education in tree traversal. > > def makeHeirarchy(id): > id = parentPath(id)[-1] > rootimages = getImages(id[0]) > rootworks = getWorks(id[0]) > heirarchy = treeTraversal(rootworks, [id, rootimages]) > return heirarchy > > ## which calls this recursive function: > > def treeTraversal(listIn,result): > for x in listIn: > if not getWorks(x[0]): > result.append(x) > result.append(getImages(x[0])) > else: > result.append(x) > result.append(getImages(x[0])) > treeTraversal(getWorks(x[0]), result) > return result > > My problem is that this returns the tuples to me in a flat list. > I've been trying to work out how I can get it to return some sort of nested > structure: nested lists, dictionaries, or html thus: > >
        >
      • 1,0,data
      • >
          >
        • 555, 1, image
        • >
        • 556, 1, data
        • >
            >
          • 557, 556, image
          • >
          • 561, 556, image
          • >
          • 562, 556, image
          • >
          • 558, 556, data
          • >
              >
            • 559, 558, image
            • >
            • 560, 558, image
            • >
            >
          >
        • 563, 1, data
        • >
            >
          • 564, 563, data
          • >
          >
        • 565, 1, data
        • >
        >
      > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jun 4 20:17:58 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Jun 2010 14:17:58 -0400 Subject: [Tutor] sockets, servers, clients, broadcasts...? In-Reply-To: <20100604104254.33e4a8ef@o> References: <20100604104254.33e4a8ef@o> Message-ID: Thanks for the suggestions, everyone. For now, more as a way to introduce myself to all this, I am going to have my program automatically start a server and pop up that server's ip. Then, if you want, you can type in an ip and connect to the server at that ip (ports are hard-coded at 7777). That way everyone is a server and a client, and either you connect to someone else as a client or they connect to you as a client. It appears, though, that I need a loop to have a server make any sense at all, to handle incoming data and connection requests. Obviously, starting this loop will then put the rest of my program on hold. Am I safe to use basic threading to stick the server's loop into a new thread? That is, will the rest of my program be able to talk to the server / will the server be able to talk to my program from its new home in its separate thread, and might I run into strange problems because of process scheduling and blocking (or not blocking)? On 6/4/10, spir wrote: > On Thu, 3 Jun 2010 18:03:34 -0400 > Alex Hall wrote: > >> Hi all, >> I am a CS major, so I have had the required networking class. I get >> the principles of networking, sockets, and packets, but I have never >> had to actually implement any such principles in any program. Now I >> have this Battleship game (not a school assignment, just a summer >> project) that I am trying to make playable over the internet, since I >> have not written the AI and playing Battleship against oneself is >> rather boring. >> >> Right now I am just trying to figure out how to implement something >> like the following: >> *you start the program and select "online game" >> *you select "server" or "client" (say you choose "server") >> *somehow, your instance of the program starts up a server that >> broadcasts something; your enemy has selected "client", and is now >> (SOMEHOW) listening for the signal your server is broadcasting >> *the signal is picked up, and, SOMEHOW, you and your opponent connect >> and can start sending and receiving data. >> >> First, how does the client know where to look for the server? I am not >> above popping up the server's ip and making the client type it in, but >> a better solution would be great. >> How do I make it so that the client can find the server correctly? The >> above IP is one thing, but are ports important here? Not a big deal if >> they are, but I am not sure. Does someone have an example of this >> process? > > I'm far to be a specialist in this field, so this is just reasoning by > watching your requirements. > > First, such a game seems to match peer-to-peer relation. This would be > different if you implemented complicated game logic, like in the case of an > AI playing. > For peers to connect, a general solution is them to register on a dedicated > public interface (the same can be used to publish a server's IP, indeed). > Then, your app first reads data there to know which (address,port) pair(s) > are available. > But since you seem to be still exploring data exchange issues, you'd better > concentrate on this basic mechanism first, choose and try one of numerous > possible solutions, then only address higher-level problems. In the > meanwhile, just put IPs and ports in a config file or even hardcode them as > constants. > > About client-server, as said above, this model does not really seem to match > your use case, I guess. But this is still an interesting alternative. I > would set my own post as server and players as clients. So, when playing > myself, I would be a local client. This indeed allows two other guys playing > using your post as server (and you maybe watching the game ;-). > But this does not make much sense if the server does not have any relevant > info to deliver (eg playing hints). > > > Denis > ________________________________ > > vit esse estrany ? > > spir.wikidot.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Fri Jun 4 21:02:30 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 4 Jun 2010 19:02:30 +0000 (GMT) Subject: [Tutor] Misc question about scoping In-Reply-To: <4C08E23B.7060704@ieee.org> References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> Message-ID: <762355.65706.qm@web86708.mail.ird.yahoo.com> > > flag = True if (someValue or another) else False > > > I'd prefer the form: > > flag = not not (someValue or another) Eek! no I'd just cast to a bool: flag = bool(someValue or another) but the if/else form has the Pythonic virtue of explicitness. Alan G. From hugo.yoshi at gmail.com Fri Jun 4 21:36:55 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jun 2010 21:36:55 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: <762355.65706.qm@web86708.mail.ird.yahoo.com> References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> <762355.65706.qm@web86708.mail.ird.yahoo.com> Message-ID: <8712109606247301132@unknownmsgid> On 4 jun 2010, at 21:02, ALAN GAULD wrote: Eek! no I'd just cast to a bool: flag = bool(someValue or another) but the if/else form has the Pythonic virtue of explicitness. Are you arguing that the if/else form is better than simply casting to bool because it is more explicit? You could hardly name the cast implicit, it's right there in your face. If anything, I'd say the if/else is a more indirect way of expressing te cast, even more so when you realize bool is called on the expression anyway by the if statement, to determine its truthiness. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 4 22:00:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Jun 2010 21:00:01 +0100 Subject: [Tutor] sockets, servers, clients, broadcasts...? References: <20100604104254.33e4a8ef@o> Message-ID: "Alex Hall" wrote > connect to you as a client. It appears, though, that I need a loop > to > have a server make any sense at all, to handle incoming data and > connection requests. You need to listen then process incoming messages then listen some more, so yes you will need a loop. Probaqbly an infinite one: while True: listen() if someQuitMessage: break process() > rest of my program on hold. Am I safe to use basic threading to > stick > the server's loop into a new thread? For your game you don't need to do that. A single thread should suffice. But usually a server's listen loop is the main thread and the processing goes into the sub threads. > program be able to talk to the server / will the server be able to > talk to my program from its new home in its separate thread, Look at the example in my tutorial. It doesn't use threads but services two separate clients without lockup. (Albeit it doesn't care about context...) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 4 22:02:25 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 4 Jun 2010 13:02:25 -0700 (PDT) Subject: [Tutor] Misc question about scoping In-Reply-To: <8712109606247301132@unknownmsgid> References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> <762355.65706.qm@web86708.mail.ird.yahoo.com> <8712109606247301132@unknownmsgid> Message-ID: <104592.5812.qm@web86703.mail.ird.yahoo.com> > Are you arguing that the if/else form is better than simply casting > to bool because it is more explicit? No, I'm simply offering a reason to use if/else in the general sense. In practice, for this specific case, I'd go with the bool(expr) form. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Jun 4 22:04:15 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jun 2010 22:04:15 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: <104592.5812.qm@web86703.mail.ird.yahoo.com> References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> <762355.65706.qm@web86708.mail.ird.yahoo.com> <8712109606247301132@unknownmsgid> <104592.5812.qm@web86703.mail.ird.yahoo.com> Message-ID: On Fri, Jun 4, 2010 at 10:02 PM, ALAN GAULD wrote: > > No, I'm simply offering a reason to use if/else in the general sense. > > In practice, for this specific case, I'd go with the bool(expr) form. > Ah, then it seems we are in agreement. Sorry for the misunderstanding From davea at ieee.org Fri Jun 4 22:23:26 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 04 Jun 2010 16:23:26 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> <4C08E23B.7060704@ieee.org> Message-ID: <4C0960BE.7000009@ieee.org> Hugo Arts wrote: > On Fri, Jun 4, 2010 at 1:23 PM, Dave Angel wrote: > >> I'd prefer the form: >> >> flag =ot not (someValue or another) >> >> > > That's a construct you might commonly find in languages like C, but I > don't think it's very pythonic. If you want to convert your result to > a bool, be explicit about it: > > flag =ool(some_value or another) > > I'd agree that the if/else construct is redundant if you just want a > True/False result, but the double not is a kind of implicit type > conversion that is easily avoided. > > Hugo > > I'd certainly agree that bool() is better than not not. And I admit a C background. DaveA From hugo.yoshi at gmail.com Fri Jun 4 22:33:19 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jun 2010 22:33:19 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: On Fri, Jun 4, 2010 at 6:26 PM, Tino Dai wrote: > > LOL, it's actually on the list of things to do. And hear that one will become a > better programmer once they learn LISP. > I most certainly did. There are very few languages as conceptually pure as this one. If you ever get it on the top of your list, check out these links. [1] is the venerable book "structure and interpretation of computer programs," commonly regarded as one of the best introductory programming books ever written. It teaches scheme. [2] is a set of excellent lectures of said book, by its writers. They are very good teachers. [1] http://mitpress.mit.edu/sicp/ [2] http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/ > > I am always fighting the battle - more compact vs more readable :) . A couple of > questions that I have: Why generators over map? Is it somehow more efficient > under the covers or is it for readability purposes? I noticed that you > took out the > lambda function too (not much good without a map/filter/reduce) to replace > with the generator function. Also could you give me some instances > where a generator > would be used in a real situation? I have already read the stuff on > doc.python.org about > generators. > generator expressions have essentially the same performance, but are less memory hungry, since the results do not have to be kept into memory. There is a function called imap in the itertools module that has that same benefit though, so it's not inherent to map at all. Think of the list comprehension as a more readable/concise alternative to map and filter, while generator expressions correspond to the imap/ifilter functions. Readability is the key issue here. The generator expression doesn't need a function, so the use of the lambda keyword is avoided, making it a lot shorter and easier on the eyes. It also reads more naturally. generator expressions are basically just a shortcut to generators though, which are even more powerful. Take, for example, a simple generator that yields the fibonacci sequence: def fib(): a = b = 1 while True: yield a a, b = b, a + b >>> fib() >>> it = fib() >>> for i in range(10): print it.next(), 1 1 2 3 5 8 13 21 34 55 >>> It's both more efficient and clearer than a function that simply calculates a list and returns the results. Plus it can actually go on infinitely, and you just take as many results from it as you need (also look at itertools for that, particularly takewhile). In practice it's used mostly for writing __iter__ methods, which is vastly simpler than a separate iterator class with the next method and everything. Just write __iter__ as a generator that yields your sequence, and you're done. Hugo From denis.spir at gmail.com Fri Jun 4 23:08:42 2010 From: denis.spir at gmail.com (spir) Date: Fri, 4 Jun 2010 23:08:42 +0200 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: <20100604230842.79b7b407@o> On Fri, 4 Jun 2010 12:26:20 -0400 Tino Dai wrote: > Also could you give me some instances > where a generator > would be used in a real situation? I have already read the stuff on > doc.python.org about > generators. Sure, generally speaking in the programming world, documentation misses the first and principle step: *purpose* :-) Why is that stuff intended for? My point of view is as follows (I don't mean it's _the_ answer): Generators are useful when not all potential values need be generated (or possibly not all). Meaning you perform some task until a condition is met, so you don't need all possible map values. A mapping or list comprehension instead always creates them all. A particuliar case where a generator is necessary is the one of an "open", unlimited, series, defined by eg a formula, such as cubes. Such a potentially infinite series is only broken by a loop break: def cubes(first): n = first while True: yield n ** 3 n += 1 for cube in cubes(1): if cube > 999: break else: print(cube), Denis ________________________________ vit esse estrany ? spir.wikidot.com From denis.spir at gmail.com Fri Jun 4 23:41:16 2010 From: denis.spir at gmail.com (spir) Date: Fri, 4 Jun 2010 23:41:16 +0200 Subject: [Tutor] treeTraversal, nested return? In-Reply-To: References: Message-ID: <20100604234116.0e04f040@o> On Fri, 4 Jun 2010 10:15:26 -0700 (PDT) jjcrump at uw.edu wrote: > All, > > any observations might be helpful. For the display of database contents I > have the following problem: > > Database querys will return data to me in tuples of the following sort: > each tuple has a unique id, a parent id, and a type. > > a parent id of 0 indicates that the element has no parent. > not all data elements have children > image elements have no children and must have a parent > > So the contents of the db is a tree of sorts: > > (1, 0, work) > (555, 1, image) > (556, 1, work) > (557, 556, image) > (558, 556, work) > (559, 558, image) > (560, 558, work) > (561, 556, image) > (562, 556, image) > (563, 1, work) > (564, 563, work) > (565, 1, work) > > I have a function that will traverse this tree, summoning lists of tuples > at each leaf. Well and good; it took a lot of trial and error, but it was > a fine education in tree traversal. > > def makeHeirarchy(id): > id = parentPath(id)[-1] > rootimages = getImages(id[0]) > rootworks = getWorks(id[0]) > heirarchy = treeTraversal(rootworks, [id, rootimages]) > return heirarchy > > ## which calls this recursive function: > > def treeTraversal(listIn,result): > for x in listIn: > if not getWorks(x[0]): > result.append(x) > result.append(getImages(x[0])) > else: > result.append(x) > result.append(getImages(x[0])) > treeTraversal(getWorks(x[0]), result) > return result > > My problem is that this returns the tuples to me in a flat list. > I've been trying to work out how I can get it to return some sort of > nested structure: nested lists, dictionaries, or html thus: For an indented output, you're simply forgetting to inform the recursive function aobut current indent level. Example (note: a nested sequence is not a tree: it has no root): SPACE , WIDTH, NODE, NL = " " , 4 , "" , '\n' def indentOutput(s, level=0): # fake root if level == 0: text = NODE else: text = "" # children level += 1 offset = level * SPACE * WIDTH for element in s: if isinstance(element, (tuple,list)): text += "%s%s%s%s" %(NL,offset,NODE , indentOutput(element, level)) else: text += "%s%s%s" %(NL,offset,element) return text s = (1,(2,3),4,(5,(6,7),8),9) print indentOutput(s) 1 2 3 4 5 6 7 8 9 Denis ________________________________ vit esse estrany ? spir.wikidot.com From mehgcap at gmail.com Fri Jun 4 23:50:18 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Jun 2010 17:50:18 -0400 Subject: [Tutor] sockets, servers, clients, broadcasts...? In-Reply-To: References: <20100604104254.33e4a8ef@o> Message-ID: On 6/4/10, Alan Gauld wrote: > > "Alex Hall" wrote > >> connect to you as a client. It appears, though, that I need a loop >> to >> have a server make any sense at all, to handle incoming data and >> connection requests. > > You need to listen then process incoming messages then listen some > more, so yes you will need a loop. Probaqbly an infinite one: > > while True: > listen() > if someQuitMessage: > break > process() >> rest of my program on hold. Am I safe to use basic threading to >> stick >> the server's loop into a new thread? > > For your game you don't need to do that. A single thread should > suffice. The idea is to have every instance of the game start up a server (if it is configured to do so by the user). So when a client connects to you, you and the client exchange data (ship positions, board size, and so on), then each move by you sends results to the client and each move by the client sends results to you. For example, the client fires at square A1. As soon as that happens, a toople something like ("shell","a1") is sent to you, the server. You then see if that was a hit or a miss on one of your ships and inform the user accordingly. Currently, the game is based on an accelerator table inside a wx Frame, but I think what I will do is put the calls to server.send() as required in each function called by the accelerator table. I am not sure how I would insert this into the server's loop; as it stands, it seems much more intuitive to have the server spinning its wheels, waiting for things to happen. Again, I am very new to all this, so maybe there is a better way, but I do not know how I would put all the game logic into a huge while loop. Oh, I am using the "toomi" library, which provides basic client and server classes and seems to do what I need, at least for now. > But usually a server's listen loop is the main thread and the > processing > goes into the sub threads. > >> program be able to talk to the server / will the server be able to >> talk to my program from its new home in its separate thread, > > Look at the example in my tutorial. It doesn't use threads but > services two separate clients without lockup. (Albeit it doesn't > care about context...) What is the link for the tutorial? Also, maybe a bit off topic, what is a context? I dealt with them a lot in Android programming last semester, but I still do not get them, and I thought they were just an Android/Java thing. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Jun 5 01:42:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 5 Jun 2010 09:42:00 +1000 Subject: [Tutor] From SQL Blobs to Python Buffers to Actual Files In-Reply-To: <269042.23910.qm@web51904.mail.re2.yahoo.com> References: <201006041418.44223.steve@pearwood.info> <269042.23910.qm@web51904.mail.re2.yahoo.com> Message-ID: <201006050942.01598.steve@pearwood.info> On Sat, 5 Jun 2010 03:51:02 am GoodPotatoes wrote: > When I write the blob/binary data to a file and give it its original > file name "customer1.rtf", I am expecting the application to read the > binary data into text,excel,word documents, or whatever application > created the file originally. > > Example: > when I write blob1 to customer1.rtf, I get > "x??VKs?6?93?{????2%??c?lg?d?<&v???\J?" as my first line. Does that look like Rich Text Format to you? RTF looks like: {\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold} text.\par} It's a database blob. Writing it to a file called "customer1.rtf" won't magically turn it into RTF any more than writing it to a file called "puppy.jpg" will magically turn it into a picture of a puppy. Blobs are database-specific binary data, not RTF. The database could be doing *anything* to it -- it could be compressing it, or encoding it in some way, who knows? You have to convert the data back into RTF before writing it. This almost certainly isn't a Python problem, but a database problem. Consult your database documentation, and good luck. -- Steven D'Aprano From alan.gauld at btinternet.com Sat Jun 5 02:12:09 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 5 Jun 2010 00:12:09 +0000 (GMT) Subject: [Tutor] sockets, servers, clients, broadcasts...? In-Reply-To: References: <20100604104254.33e4a8ef@o> Message-ID: <940983.87056.qm@web86702.mail.ird.yahoo.com> > Look at the example in my tutorial. It doesn't use threads but What is the link for the tutorial? In my sig. Go to the V2 version and look for the Network Programming topic. > what is a context? I dealt with them a lot in Android programming Nothing to do with Android contexts I'm simply using the English meaning. In other words my example processes each request independent of the client, there is no concept of session state. It basically servers up a sequience of numbers on a firs come first served basis, it doesn't remember the last number served per client and give the next number it just serves the next number to whoever asks for one. In your case you only have one client per server - albeit with two servers - so each server only has to deal with a single client's request so again no need to keep session state (the context), you just look at the model and act accordingly. HTH, Alan G http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 5 02:24:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Jun 2010 01:24:56 +0100 Subject: [Tutor] Misc question about scoping References: <201006041013.28220.steve@pearwood.info> Message-ID: "Hugo Arts" wrote > [1] http://mitpress.mit.edu/sicp/ > [2] > http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/ > And I'd add the superb How to Design Programs: http://www.htdp.org/ It teaches Scheme programming using a recipe approach that creates a standard stricture for a function. It then extends that structure as the examples build in complexity but always keeping the basic theme. This book and SICP are two of the best for making you rethink all you thought you knew about program structure and design! If you really want to bend your brain in Lisp (Scheme) try The Little Schemer and its follow up the Seasoned Schemer It took me 3 attempts to really get to grips with the first and I'm on my second attempt at the second! What all these books will do is give you a rational approach to problem solving for programming that will often work when more 'conventional' approaches don't. The performance of the resulting code may not be optimal but it will often give you the key breakthrough that you can then rewrite more conventionally into good and fast code. It also often leads to much more elegant solutions. Good for when you have something that works but looks a mess... rethink it for Lisp and see what's different. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jjcrump at uw.edu Sat Jun 5 03:40:10 2010 From: jjcrump at uw.edu (jjcrump at uw.edu) Date: Fri, 4 Jun 2010 18:40:10 -0700 (PDT) Subject: [Tutor] treeTraversal, nested return? In-Reply-To: References: Message-ID: Matthew, sorry for responding to you instead of the list Thanks for trying to tutor the dunderheaded. It is exactly the general solution I wish to learn. But how, in the context of my treeTraversal function, does one "keep track of the depth you're at"? Tabs are all very well, but what I want is truly a nested structure, and as you point out in that's not what I was showing in my html (though deprecated, browsers still render lists like the one I showed). The simplest and most graphic example would be a nested list of lists, but for the life of me I can't work out how to generate that in this context. Jon On Fri, 4 Jun 2010, Matthew Wood wrote: > In general, there's 2 solutions to your "unflattening" problem. > A) The general solution: Keep track of the depth you're at, and add tabs/spaces ('\t' * depth) as necessary. From denis.spir at gmail.com Sat Jun 5 07:56:03 2010 From: denis.spir at gmail.com (spir) Date: Sat, 5 Jun 2010 07:56:03 +0200 Subject: [Tutor] Lisphon In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: <20100605075603.3748e599@o> On Fri, 4 Jun 2010 22:33:19 +0200 Hugo Arts wrote: > On Fri, Jun 4, 2010 at 6:26 PM, Tino Dai wrote: > > > > LOL, it's actually on the list of things to do. And hear that one will become a > > better programmer once they learn LISP. > > > > I most certainly did. There are very few languages as conceptually > pure as this one. If you ever get it on the top of your list, check > out these links. [1] is the venerable book "structure and > interpretation of computer programs," commonly regarded as one of the > best introductory programming books ever written. It teaches scheme. > [2] is a set of excellent lectures of said book, by its writers. They > are very good teachers. > > [1] http://mitpress.mit.edu/sicp/ > [2] http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/ Thanks for the pointer, Hugo, did not know these lectures. If you do not know lisperati, you *must* follow the pointer, if only for the home page: http://lisperati.com/. Also, history of Lisp: http://www-formal.stanford.edu/jmc/history/lisp/lisp.html Denis ________________________________ vit esse estrany ? spir.wikidot.com From oberoc at gmail.com Sat Jun 5 17:01:25 2010 From: oberoc at gmail.com (Tino Dai) Date: Sat, 5 Jun 2010 11:01:25 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: On Fri, Jun 4, 2010 at 8:24 PM, Alan Gauld wrote: > "Hugo Arts" wrote > > > [1] http://mitpress.mit.edu/sicp/ >> [2] >> http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/ >> >> > And I'd add the superb How to Design Programs: > > http://www.htdp.org/ > > It teaches Scheme programming using a recipe approach > that creates a standard stricture for a function. It then extends > that structure as the examples build in complexity but always > keeping the basic theme. > > This book and SICP are two of the best for making you rethink all > you thought you knew about program structure and design! > How about the ANSI Lisp by Paul Graham. Any options negative or positive? > > If you really want to bend your brain in Lisp (Scheme) try > The Little Schemer and its follow up the Seasoned Schemer > It took me 3 attempts to really get to grips with the first and > I'm on my second attempt at the second! > Is that linked to the Little Lisper somehow? > > What all these books will do is give you a rational approach > to problem solving for programming that will often work when > more 'conventional' approaches don't. The performance of the > resulting code may not be optimal but it will often give you > the key breakthrough that you can then rewrite more > conventionally into good and fast code. It also often leads to > much more elegant solutions. Good for when you have > something that works but looks a mess... rethink it for > Lisp and see what's different. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From woodm1979 at gmail.com Sat Jun 5 18:24:56 2010 From: woodm1979 at gmail.com (Matthew Wood) Date: Sat, 5 Jun 2010 10:24:56 -0600 Subject: [Tutor] treeTraversal, nested return? In-Reply-To: References: Message-ID: On Fri, Jun 4, 2010 at 7:40 PM, wrote: > Matthew, > > sorry for responding to you instead of the list > > > Thanks for trying to tutor the dunderheaded. It is exactly the general > solution I wish to learn. But how, in the context of my treeTraversal > function, does one "keep track of the depth you're at"? Tabs are all very > well, but what I want is truly a nested structure, and as you point out in > that's not what I was showing in my html (though deprecated, > browsers still render lists like the one I showed). > > The simplest and most graphic example would be a nested list of lists, but > for the life of me I can't work out how to generate that in this context. > > Jon > > > > On Fri, 4 Jun 2010, Matthew Wood wrote: > > In general, there's 2 solutions to your "unflattening" problem. >> A) The general solution: Keep track of the depth you're at, and add >> > tabs/spaces ('\t' * depth) as necessary. > > > > Spir's example demonstrates the idiom. Watch the "level" variable. During our function, it gets incremented, and then passed into the next recursive call. Thus, each call to the recursive function is passing along the appropriate tab depth level. Good luck yo. Recursion is one of those concepts that just clicks one day. At least that's how it is for me. I'll attempt to provide a pseudo pseudo code description: def recursive_func(data, indent_level): if is_printable_node(data): print '\t' * indent_level + string_format(data) else: # now we know it's not a node, so it must be a child list. for sub_data in data: recursive_func(sub_data, indent_level + 1) Again, watch the indent_level variable. -- I enjoy haiku but sometimes they don't make sense; refrigerator? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 5 19:41:14 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 5 Jun 2010 17:41:14 +0000 (GMT) Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: <611857.57123.qm@web86708.mail.ird.yahoo.com> > >>>If you really want to bend your brain in Lisp (Scheme) try >>>>The Little Schemer and its follow up the Seasoned Schemer >> > >Is that linked to the Little Lisper somehow? >Yes, its the second edition ported to Scheme. In fact I used the Little Lisper then moved to the Seasoned Schemer. There is a third volume, The Reasoned Schemer, which I also have but I haven't even opened it yet... Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From payal-python at scriptkitchen.com Sun Jun 6 09:32:26 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 6 Jun 2010 00:32:26 -0700 Subject: [Tutor] backreferences - \0 Message-ID: <20100606073226.GA14095@scriptkitchen.com> Hi, A newbie re query. >>> import re >>> s='one' >>> re.sub('(one)','only \\0',s) 'only \x00' >>> re.sub('(one)','only \0',s) 'only \x00' I expected the output to be 'only one' with \0 behaving like "&" in sed. What is wrong with my syntax? With warm regards, -Payal -- From steve at pearwood.info Sun Jun 6 10:26:18 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 Jun 2010 18:26:18 +1000 Subject: [Tutor] backreferences - \0 In-Reply-To: <20100606073226.GA14095@scriptkitchen.com> References: <20100606073226.GA14095@scriptkitchen.com> Message-ID: <201006061826.19720.steve@pearwood.info> On Sun, 6 Jun 2010 05:32:26 pm Payal wrote: > Hi, > A newbie re query. > > >>> import re > >>> s='one' > >>> re.sub('(one)','only \\0',s) > > 'only \x00' > > >>> re.sub('(one)','only \0',s) > > 'only \x00' > > I expected the output to be 'only one' with \0 behaving like "&" in > sed. What is wrong with my syntax? Two things. Firstly, the Python regex engine numbers backreferences from 1, not 0, so you need \1 and not \0. Secondly, you neglected to escape the escape, so Python interpreted the string "only \0" as "only " plus the ASCII null byte, which has no special meaning to the regex engine. Fixing both those problems, you can either escape the escapes, which is tedious for large regexes: >>> re.sub('(one)', 'only \\1', s) 'only one' or better, use the raw string syntax so Python doesn't interpret backslashes specially: >>> re.sub('(one)', r'only \1', s) 'only one' -- Steven D'Aprano From payal-python at scriptkitchen.com Sun Jun 6 11:36:37 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 6 Jun 2010 02:36:37 -0700 Subject: [Tutor] backreferences - \0 In-Reply-To: <201006061826.19720.steve@pearwood.info> References: <20100606073226.GA14095@scriptkitchen.com> <201006061826.19720.steve@pearwood.info> Message-ID: <20100606093637.GA15002@scriptkitchen.com> On Sun, Jun 06, 2010 at 06:26:18PM +1000, Steven D'Aprano wrote: > Two things. Firstly, the Python regex engine numbers backreferences from > 1, not 0, so you need \1 and not \0. Thank for the mail, but i am still not getting it. e.g. >>> import re >>> s = 'one two' >>> re.sub('(one) (two)', r'\1 - \2 \3',s) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 151, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.6/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/usr/lib/python2.6/sre_parse.py", line 795, in expand_template raise error, "invalid group reference" sre_constants.error: invalid group reference >>> re.sub('(one) (two)', r'\1 - \2',s) 'one - two' In first sub I expected, one two - one two I understand that \1 is first (group), \2 the second and etc. But what is the entire regex? With warm regards, -Payal -- From lie.1296 at gmail.com Sun Jun 6 11:52:43 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 06 Jun 2010 19:52:43 +1000 Subject: [Tutor] backreferences - \0 In-Reply-To: <20100606093637.GA15002@scriptkitchen.com> References: <20100606073226.GA14095@scriptkitchen.com> <201006061826.19720.steve@pearwood.info> <20100606093637.GA15002@scriptkitchen.com> Message-ID: On 06/06/10 19:36, Payal wrote: > On Sun, Jun 06, 2010 at 06:26:18PM +1000, Steven D'Aprano wrote: >> Two things. Firstly, the Python regex engine numbers backreferences from >> 1, not 0, so you need \1 and not \0. > > Thank for the mail, but i am still not getting it. e.g. > > In first sub I expected, > one two - one two > > I understand that \1 is first (group), \2 the second and etc. > But what is the entire regex? >>> re.sub('(one) (two)', r'\g<0> - \1 \2',s) the \g is equivalent to \number but is intended to ambiguate cases like "\g<2>0" vs. "\20". It happens that \g<0> refers to the entire group. From lang at tharin.com Sun Jun 6 12:51:16 2010 From: lang at tharin.com (Lang Hurst) Date: Sun, 06 Jun 2010 03:51:16 -0700 Subject: [Tutor] glade gtk radiobutton group Message-ID: <4C0B7DA4.6090500@tharin.com> I'm trying to create an incredibly simple application just to learn gui programming, but I can't see how to work with radio buttons. A sample from my glade looks like: Ch 1 True True False True 1 Ch 2 True True False True radiobutton1 ...and so on. 11 radiobuttons, all belonging to group "radiobutton1" I've tried many different things in my python file, things like radio = [r for r in cbc['radiobutton1'].get_group() if r.get_active()] (Saw that somewhere in my search) So, I have in my Class: dic = { "on_button_quit_clicked" : self.button_quit_clicked, "on_window_destroy" : self.button_quit_clicked, "on_MainWindow_destroy" : gtk.main_quit, "on_button_print_clicked" : self.button_print_clicked, "on_button_edit_clicked" : self.button_edit_clicked } And those all work fine so far. ie: def button_print_clicked(self, widget): print "Print clicked" And when I click the "Print" button, it prints to the terminal. As I said, very basic. Can someone tell me, show me, a very basic way of connecting to my radio buttons. If I could get the thing to just print "Radio button 3 is selected" I'd be ecstatic at this point. I did read through the tutorial, but my old mind isn't flexible enough to go from the hardcoded gtk examples to separate glade + python files. -- There are no stupid questions, just stupid people. From payal-tutor at scriptkitchen.com Sun Jun 6 15:44:06 2010 From: payal-tutor at scriptkitchen.com (Payal) Date: Sun, 6 Jun 2010 06:44:06 -0700 Subject: [Tutor] backreferences - \0 In-Reply-To: References: <20100606073226.GA14095@scriptkitchen.com> <201006061826.19720.steve@pearwood.info> <20100606093637.GA15002@scriptkitchen.com> Message-ID: <20100606134406.GA17243@scriptkitchen.com> On Sun, Jun 06, 2010 at 07:52:43PM +1000, Lie Ryan wrote: > >>> re.sub('(one) (two)', r'\g<0> - \1 \2',s) > > the \g is equivalent to \number but is intended to ambiguate > cases like "\g<2>0" vs. "\20". It happens that \g<0> refers to the > entire group. Thanks a lot. It works as you say. With warm regards, -Payal -- From gvkalra at gmail.com Sun Jun 6 20:29:32 2010 From: gvkalra at gmail.com (Gaurav Kalra) Date: Sun, 6 Jun 2010 23:59:32 +0530 Subject: [Tutor] JS for location detection Message-ID: Hi all, I was trying to get the user location based on 4 levels. 1. Try for Navigator telling the location (W3C recommendations followed) 2. In case the location is not available, fallback on Google Gears 3. Again if not available, fall back on Google Ajax API's (only for US) 4. Again if not available, use IP to location using Max-Mind Database The code that I have written is here: http://github.com/gvkalra/random/blob/master/static/js/map.js The problem I am facing: If the navigator supports location sharing, it will ask the user whether it wants to approve or not (that's okay!). If the user says NO, it is giving me the right result by falling back on 3/4 step. But, in case the user approves, the results are not being populated. Please check the code for more details (commented inline). Any suggestions ? -- With Thanks Gaurav Kalra +91-9717-620-649 gvkalra at googlemail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jun 6 21:43:25 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 06 Jun 2010 15:43:25 -0400 Subject: [Tutor] JS for location detection In-Reply-To: References: Message-ID: <4C0BFA5D.8010206@gmail.com> On 6/6/2010 2:29 PM, Gaurav Kalra wrote: > Hi all, > > I was trying to get the user location based on 4 levels. > 1. Try for Navigator telling the location (W3C recommendations followed) > 2. In case the location is not available, fallback on Google Gears > 3. Again if not available, fall back on Google Ajax API's (only for US) > 4. Again if not available, use IP to location using Max-Mind Database > > The code that I have written is here: > http://github.com/gvkalra/random/blob/master/static/js/map.js > > The problem I am facing: > If the navigator supports location sharing, it will ask the user > whether it wants to approve or not (that's okay!). If the user says > NO, it is giving me the right result by falling back on 3/4 step. But, > in case the user approves, the results are not being populated. > > Please check the code for more details (commented inline). Any > suggestions ? > Your question reached the Python Tutor list. This is not the appropriate place for a JavsScript question. -- Bob Gailer 919-636-4239 Chapel Hill NC From gvkalra at gmail.com Sun Jun 6 21:52:08 2010 From: gvkalra at gmail.com (Gaurav Kalra) Date: Mon, 7 Jun 2010 01:22:08 +0530 Subject: [Tutor] JS for location detection In-Reply-To: <4C0BFA5D.8010206@gmail.com> References: <4C0BFA5D.8010206@gmail.com> Message-ID: On Mon, Jun 7, 2010 at 01:13, bob gailer wrote: > On 6/6/2010 2:29 PM, Gaurav Kalra wrote: > >> Hi all, >> >> I was trying to get the user location based on 4 levels. >> 1. Try for Navigator telling the location (W3C recommendations followed) >> 2. In case the location is not available, fallback on Google Gears >> 3. Again if not available, fall back on Google Ajax API's (only for US) >> 4. Again if not available, use IP to location using Max-Mind Database >> >> The code that I have written is here: >> http://github.com/gvkalra/random/blob/master/static/js/map.js >> >> The problem I am facing: >> If the navigator supports location sharing, it will ask the user whether >> it wants to approve or not (that's okay!). If the user says NO, it is giving >> me the right result by falling back on 3/4 step. But, in case the user >> approves, the results are not being populated. >> >> Please check the code for more details (commented inline). Any suggestions >> ? >> >> Your question reached the Python Tutor list. This is not the appropriate > place for a JavsScript question. > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > The list was suggested to me by a friend and he said that it's for General Programming discussions as well. Am sorry if I broke the laws of the list. But since I have already posted, if anyone up here is with a solution; please PM me. I will be careful next time -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 7 00:59:24 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Jun 2010 23:59:24 +0100 Subject: [Tutor] JS for location detection References: <4C0BFA5D.8010206@gmail.com> Message-ID: "Gaurav Kalra" wrote > The list was suggested to me by a friend and he said that it's for > General > Programming discussions as well. Am sorry if I broke the laws of the > list. > But since I have already posted, if anyone up here is with a > solution; > please PM me. It is for general programming discussions, since those could be applied to Python. So questions about suitable design approaches or algorithms etc would be fine. But it's not really the place for specific questions about code in other languages - unless you want to rewrite them in Python maybe! Alan G. From bgailer at gmail.com Mon Jun 7 02:16:41 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 06 Jun 2010 20:16:41 -0400 Subject: [Tutor] JS for location detection In-Reply-To: References: <4C0BFA5D.8010206@gmail.com> Message-ID: <4C0C3A69.7020108@gmail.com> On 6/6/2010 6:59 PM, Alan Gauld wrote: > > "Gaurav Kalra" wrote > >> The list was suggested to me by a friend and he said that it's for >> General >> Programming discussions as well. Am sorry if I broke the laws of the >> list. >> But since I have already posted, if anyone up here is with a solution; >> please PM me. There are no laws. By "inappropriate" I meant that 1 - you would be less likely to get an answer here. 2 - my preference is that only Python questions be asked, as it takes my time to decipher a question. I examined your code to see if it were Python related. That takes time. -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Mon Jun 7 02:44:48 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 6 Jun 2010 20:44:48 -0400 Subject: [Tutor] while loops causing python.exe to crash on windows Message-ID: -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From bgailer at gmail.com Mon Jun 7 02:55:17 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 06 Jun 2010 20:55:17 -0400 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: Message-ID: <4C0C4375.203@gmail.com> On 6/6/2010 8:44 PM, Alex Hall wrote: > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com;http://www.facebook.com/mehgcap > > What is your question? -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Mon Jun 7 03:08:23 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 6 Jun 2010 21:08:23 -0400 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: <4C0C4375.203@gmail.com> References: <4C0C4375.203@gmail.com> Message-ID: On 6/6/10, bob gailer wrote: > On 6/6/2010 8:44 PM, Alex Hall wrote: >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehgcap at gmail.com;http://www.facebook.com/mehgcap >> >> > What is your question? > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > Why would that code cause Windows to consider the process "not responding", and how can I fix this so I can have a sort of "listener" in place, awaiting a change in the "grid.turnOver" variable inside Player.takeTurn() so that the main while loop can switch to the other player once the one player's turn is over? I thought while loops would do it, but Windows sees them as making python.exe unresponsive. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From lie.1296 at gmail.com Mon Jun 7 03:15:04 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 07 Jun 2010 11:15:04 +1000 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: <4C0C4375.203@gmail.com> Message-ID: On 06/07/10 11:08, Alex Hall wrote: > On 6/6/10, bob gailer wrote: >> On 6/6/2010 8:44 PM, Alex Hall wrote: >>> -- >>> Have a great day, >>> Alex (msg sent from GMail website) >>> mehgcap at gmail.com;http://www.facebook.com/mehgcap >>> >>> >> What is your question? >> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> > Why would that code cause Windows to consider the process "not > responding", and how can I fix this so I can have a sort of "listener" > in place, awaiting a change in the "grid.turnOver" variable inside > Player.takeTurn() so that the main while loop can switch to the other > player once the one player's turn is over? I thought while loops would > do it, but Windows sees them as making python.exe unresponsive. Would you buy me a crystal ball to foresee what you're talking about? From mehgcap at gmail.com Mon Jun 7 03:37:45 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 6 Jun 2010 21:37:45 -0400 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: <4C0C4375.203@gmail.com> Message-ID: On 6/6/10, Lie Ryan wrote: > On 06/07/10 11:08, Alex Hall wrote: >> On 6/6/10, bob gailer wrote: >>> On 6/6/2010 8:44 PM, Alex Hall wrote: >>>> -- >>>> Have a great day, >>>> Alex (msg sent from GMail website) >>>> mehgcap at gmail.com;http://www.facebook.com/mehgcap >>>> >>>> >>> What is your question? >>> >>> >>> -- >>> Bob Gailer >>> 919-636-4239 >>> Chapel Hill NC >>> >>> >> Why would that code cause Windows to consider the process "not >> responding", and how can I fix this so I can have a sort of "listener" >> in place, awaiting a change in the "grid.turnOver" variable inside >> Player.takeTurn() so that the main while loop can switch to the other >> player once the one player's turn is over? I thought while loops would >> do it, but Windows sees them as making python.exe unresponsive. > > Would you buy me a crystal ball to foresee what you're talking about? I am not sure how else to explain it. I want to loop until the value of a variable changes, but while that loop is taking place, the user should be able to perform actions set up in a wx.AcceleratorTable. Looping, though, causes Windows to tell me that python.exe is not responding, so I have to close the entire thing. I guess I am looking for a "listener", which will sit in the background and only perform an action when it detects a certain thing. In this case, a listener to watch for a variable to turn from False to True, then to act when it sees that change. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From bgailer at gmail.com Mon Jun 7 04:15:46 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 06 Jun 2010 22:15:46 -0400 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: <4C0C4375.203@gmail.com> Message-ID: <4C0C5652.6090205@gmail.com> On 6/6/2010 9:37 PM, Alex Hall wrote: > On 6/6/10, Lie Ryan wrote: > >> On 06/07/10 11:08, Alex Hall wrote: >> >>> On 6/6/10, bob gailer wrote: >>> >>>> On 6/6/2010 8:44 PM, Alex Hall wrote: >>>> >>>>> -- >>>>> Have a great day, >>>>> Alex (msg sent from GMail website) >>>>> mehgcap at gmail.com;http://www.facebook.com/mehgcap >>>>> >>>>> >>>>> >>>> What is your question? >>>> >>>> >>>> -- >>>> Bob Gailer >>>> 919-636-4239 >>>> Chapel Hill NC >>>> >>>> >>>> >>> Why would that code What code. I don't see any! >>> cause Windows to consider the process "not >>> responding", and how can I fix this so I can have a sort of "listener" >>> in place, awaiting a change in the "grid.turnOver" variable inside >>> Player.takeTurn() so that the main while loop can switch to the other >>> player once the one player's turn is over? I thought while loops would >>> do it, but Windows sees them as making python.exe unresponsive. >>> >> Would you buy me a crystal ball to foresee what you're talking about? >> > I am not sure how else to explain it. I want to loop until the value > of a variable changes, but while that loop is taking place, the user > should be able to perform actions set up in a wx.AcceleratorTable. > Looping, though, causes Windows to tell me that python.exe is not > responding, so I have to close the entire thing. I guess I am looking > for a "listener", which will sit in the background and only perform an > action when it detects a certain thing. In this case, a listener to > watch for a variable to turn from False to True, then to act when it > sees that change. > We are complaining because you first send a post with no content, then one with a question but no code. -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Mon Jun 7 05:09:37 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 6 Jun 2010 23:09:37 -0400 Subject: [Tutor] while loops / listeners Message-ID: Hi all, First off, I apologize to the list for my previous thread; somehow, despite my having written the post, it ended up blank (????) I have a main loop which will continue for as long as neither player1 nor player2 has won. Inside that loop I have a call to a function which should basically wait until the user completes a turn, then return, exiting this loop and returning to the main loop, the one looping until there is a winner. Once back there, the second player's idling function is called; once that user completes a turn, the main loop switches back to the first user, and so on. Here is the main loop: player1.takeTurn() #someone has to start off the game #now loop until someone wins... while not player1.isWinner and not player2.isWinner: if player1.grid.turnOver: #player1 is done for this turn player1.grid.speak("player 2 is going.") #lock p1 out of the window, unlock p2, and then loop p2 until s/he does something player1.lock(); player2.unlock(); player2.takeTurn() else: #player2 has completed a turn player2.grid.speak("player 1 is going.") #opposite of above - lock p2, unlock p1, loop until p1 is done player2.lock(); player1.unlock(); player1.takeTurn() #end if continue #is this doing anything? time.sleep(.1) #again, is this important? #end while The lock and unlock functions are simply there to disable and enable keyboard/mouse commands, respectively, so lock causes the player's screen to stop responding to input while unlock unfreezes the screen. This way, if you and I are playing a game, I can't keep shooting even if my turn is over. TakeTurn() is that smaller loop I was talking about: def takeTurn(self): while not self.grid.turnOver: #turnOver is true once a turn-ending function is called in grid continue time.sleep(.1) #end while #end def That is inside the Player class. Grid is just another object that is really the most important part of all the game logic; Grid holds the wx frame on which everything is drawn, the boolean to tell if the turn is over, the ships, and more. That is why the function checks self.grid.turnOver, instead of just self.turnOver; turnOver tells if the player has performed a move that ends a turn or not. Firing ends a turn, while just moving around does not. The question, then, is this: when I run the code, Windows says "python.exe has stopped responding". I know that this is because it is getting stuck, probably in the takeTurn() loop. Ordinarily, a situation like this would probably call for: while ok: ok=#program logic The hard part with my program, though, is that all input is set up with a wx.AcceleratorTable object, so I cannot just dump everything into a huge while loop and have it process that way. What I am looking for is some kind of listener object, so that I can just monitor self.grid.turnOver and call a function, or perform a few lines of code, when the listener detects a change in turnOver. On the other hand, there may be something simple that I am missing in my while loop that would cause the problem of python.exe crashing to not happen (well, not crashing, but rather not responding). I hope it is the latter problem, but I am not sure what else I could add to the loop(s) to stop this problem. Thanks, and sorry again for the blank message; still not sure how that happened. Hopefully this one works! -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Mon Jun 7 09:59:17 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Jun 2010 08:59:17 +0100 Subject: [Tutor] while loops causing python.exe to crash on windows References: <4C0C4375.203@gmail.com> Message-ID: "Alex Hall" wrote > I am not sure how else to explain it. I want to loop until the value > of a variable changes, but while that loop is taking place, the user > should be able to perform actions set up in a wx.AcceleratorTable. And here we have the critical clue. You are trying to write this loop in a GUI application. GUIs and long running loops don't mix. GUIs are driven by events and if you write a long loop the GUI cannot receive any events until the loop finishes and so "locks up" In a GUI environment you simulate a long loop with 1) A Timer event that does someting then sets up another timer 2) The null event (if the framework suipports it) whereby when no other events are present the framework calls your code. > for a "listener", which will sit in the background and only perform > an > action when it detects a certain thing. In this case, a listener to > watch for a variable to turn from False to True, then to act when it > sees that change. The listener sits inside a Timer that fires every, say, 1/10 sec. That should leave plenty time to respond to the variable change and give wx time to process any mouse clicks, key presses etc. BTW. If you are doing any significant GUI work in wxPython it will be helpful to buy the wxPython in Action book. It is very clear and includes examples of using Timers etc. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Mon Jun 7 12:01:34 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 7 Jun 2010 11:01:34 +0100 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: <4C0C4375.203@gmail.com> Message-ID: On 7 June 2010 02:37, Alex Hall wrote: > I am not sure how else to explain it. I want to loop until the value > of a variable changes, but while that loop is taking place, the user > should be able to perform actions set up in a wx.AcceleratorTable. > Looping, though, causes Windows to tell me that python.exe is not > responding, so I have to close the entire thing. I guess I am looking > for a "listener", which will sit in the background and only perform an > action when it detects a certain thing. In this case, a listener to > watch for a variable to turn from False to True, then to act when it > sees that change. > Notwithstanding what everyone else have said I'll add the following for what it's worth: You need to do some research into how GUI systems typically work, particularly the message queue and each applications "magic" and hidden message processing loop etc. Basically in a GUI app there's a hidden loop that continually checks for messages (calls) to your application and dispatches those calls to the handlers defined in your application. However, if your handlers do not complete quickly, then while they run, control obviously does not return to this loop again, and consequently no further events can/will be processed by your app. Some OS's flag up applications which do not process their event queues for a while as "not responding" or similar. However, in most windowing systems there's a way to process pending messages that have built up in the queue without actually returning from the handler that you're in. In Delphi the call is "Application.ProcessMessages", in VB it's "DoEvents". In WxPython it's Yield(). (You can google each of those to see the same issue in different languages/platforms if you like, it might be instructive.) So bottom line, in theory you can call Yield() in your loop and you should be OK -- your app should suddenly be responsive again even while in the loop. This type of solution is however the more "cheap and dirty" alternative and can introduce it's own set of problems and downsides. (What if for example another call/message is processed to the same event handler from which you called Yield() alrady? The point is you may open yourself up to re-entrancy issues if you're not careful. Also if the loop is very tight you might end-up consuming a lot of CPU doing nothing, so a sleep() type call might also be advisable in the loop to prevent spending more time calling Yield() than doing anything else. ) Anyway, I've done a quick google and the following page seems to be a good discussion of the above thoughts: http://wiki.wxpython.org/LongRunningTasks HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Mon Jun 7 14:37:30 2010 From: oberoc at gmail.com (Tino Dai) Date: Mon, 7 Jun 2010 08:37:30 -0400 Subject: [Tutor] Misc question about scoping In-Reply-To: References: <201006041013.28220.steve@pearwood.info> Message-ID: > answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \ >> x.values(),Answer.objects.filter(fk_questionSet=1). \ >> filter(fk_question=1).values('widgetAnswer').order_by(). \ >> annotate(widgetCount=Count('widgetAnswer'))))) >> >> > The first time there's a suspected problem with this code, you'll probably > end up with a similar refactored set of 10-15 lines. I'm sure because I've > got code like that scattered throughout my codebase and that's what I end up > doing. The difference is that I rattle off the one-liners as part of the > original coding effort, and only break it out when there's a need to -- I'm > not striving to compact things into one-liners. > Emile, Actually, I have already broken it out into 4 or 5 separate lines. The one-liner is cool for "Hey, look what I can do", but isn't for code maintenance. What I was striving for a happy medium between compactness and readability. > > BTW, doesn't > > > dict(map(lambda x: (str(x[1]),x[0]),map(lambda x:x.values() > > simply map the values of a dict back into a dict? > > I couldn't find a way to reverse the order of the elements to ultimately for a dictionary, so I resorted to this hack instead. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From payal-python at scriptkitchen.com Mon Jun 7 16:01:35 2010 From: payal-python at scriptkitchen.com (Payal) Date: Mon, 7 Jun 2010 07:01:35 -0700 Subject: [Tutor] a class query Message-ID: <20100607140135.GA13869@scriptkitchen.com> Hi all, I know the difference between class Parent : class Parent(object) : But in some softwares i recall seeing, class Parent() : Is this legal syntax? With warm regards, -Payal -- From webtourist at gmail.com Mon Jun 7 16:07:11 2010 From: webtourist at gmail.com (Robert) Date: Mon, 7 Jun 2010 10:07:11 -0400 Subject: [Tutor] a class query In-Reply-To: <20100607140135.GA13869@scriptkitchen.com> References: <20100607140135.GA13869@scriptkitchen.com> Message-ID: lol, for a second I thought this question comes from PayPal On Mon, Jun 7, 2010 at 10:01 AM, Payal wrote: > Hi all, > I know the difference ?between > class Parent : > class Parent(object) : > > But in some softwares i recall seeing, > class Parent() : > > Is this legal syntax? > > With warm regards, > -Payal > -- > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From breamoreboy at yahoo.co.uk Mon Jun 7 16:39:56 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 07 Jun 2010 15:39:56 +0100 Subject: [Tutor] while loops causing python.exe to crash on windows In-Reply-To: References: Message-ID: On 07/06/2010 01:44, Alex Hall wrote: Further to the other comments that you've had, could you please refer to the following, thanks. http://www.catb.org/~esr/faqs/smart-questions.html Kindest regards. Mark Lawrence From bgailer at gmail.com Mon Jun 7 16:49:42 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 07 Jun 2010 10:49:42 -0400 Subject: [Tutor] a class query In-Reply-To: <20100607140135.GA13869@scriptkitchen.com> References: <20100607140135.GA13869@scriptkitchen.com> Message-ID: <4C0D0706.5020505@gmail.com> On 6/7/2010 10:01 AM, Payal wrote: > Hi all, > I know the difference between > class Parent : > class Parent(object) : > > But in some softwares i recall seeing, > class Parent() : > > Is this legal syntax? > Teach: To answer that question, just try it at the interactive prompt. If it is not legal syntax you will get a syntax error! Feed: Yes Originally it was not legal. Then in some version it became legal. -- Bob Gailer 919-636-4239 Chapel Hill NC From python at bdurham.com Mon Jun 7 17:12:28 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 07 Jun 2010 11:12:28 -0400 Subject: [Tutor] a class query In-Reply-To: <4C0D0706.5020505@gmail.com> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com> Message-ID: <1275923548.18844.1378876297@webmail.messagingengine.com> Not the OP, but I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? Thanks, Malcolm From breamoreboy at yahoo.co.uk Mon Jun 7 17:24:44 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 07 Jun 2010 16:24:44 +0100 Subject: [Tutor] a class query In-Reply-To: <1275923548.18844.1378876297@webmail.messagingengine.com> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com> <1275923548.18844.1378876297@webmail.messagingengine.com> Message-ID: On 07/06/2010 16:12, python at bdurham.com wrote: > Not the OP, but I was surprised to see class Name() work (in Python > 2.6.5 at least). > > Is this equivalent to class Name( object ) or does this create an old > style class? > > Going forward into the 2.7/3.x world, is there a preferred style? > > Thanks, > Malcolm > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > RTFM? :) Kindest regards. Mark Lawrence. From python at bdurham.com Mon Jun 7 18:03:18 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 07 Jun 2010 12:03:18 -0400 Subject: [Tutor] a class query In-Reply-To: References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com><1275923548.18844.1378876297@webmail.messagingengine.com> Message-ID: <1275926598.28113.1378884075@webmail.messagingengine.com> Hi Mark, >> I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? > RTFM? :) I am reading TFM :) Here's why I'm confused. The following paragraph from TFM seems to indicate that old style classes are the default: Quote: For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the ?top-level type? object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are ?fixes? that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. http://docs.python.org/reference/datamodel.html#newstyle Yet TFM for 2.6.5 shows all class examples without specifying a parent class. http://docs.python.org/tutorial/classes.html I've been taught that the proper way to create new style classes has been to always specify an explicit "object" parent class when creating a new class not based on other classes. Somewhere along the line I seemed to have missed the fact that it is no longer necessary to define classes with 'object' as a parent in order to get a new style class. In other words, it seems that the following are now equivalent: class Name: -AND- class Name( object ): My impression was the "class Name:" style created an old style class. Thanks for your help! Malcolm From steve at pearwood.info Mon Jun 7 18:11:10 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Jun 2010 02:11:10 +1000 Subject: [Tutor] a class query In-Reply-To: <1275923548.18844.1378876297@webmail.messagingengine.com> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com> <1275923548.18844.1378876297@webmail.messagingengine.com> Message-ID: <201006080211.11779.steve@pearwood.info> On Tue, 8 Jun 2010 01:12:28 am python at bdurham.com wrote: > Not the OP, but I was surprised to see class Name() work (in Python > 2.6.5 at least). > > Is this equivalent to class Name( object ) or does this create an old > style class? In Python 2.x, all classes are old-style unless you directly or indirectly inherit from object. If you inherit from nothing, it is an old-style class regardless of whether you say class Name: pass or class Name(): pass In Python 3.x, there are no old-style classes. > Going forward into the 2.7/3.x world, is there a preferred style? No. -- Steven D'Aprano From steve at pearwood.info Mon Jun 7 18:15:05 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Jun 2010 02:15:05 +1000 Subject: [Tutor] a class query In-Reply-To: <1275926598.28113.1378884075@webmail.messagingengine.com> References: <20100607140135.GA13869@scriptkitchen.com> <1275926598.28113.1378884075@webmail.messagingengine.com> Message-ID: <201006080215.05697.steve@pearwood.info> On Tue, 8 Jun 2010 02:03:18 am python at bdurham.com wrote: > Here's why I'm confused. The following paragraph from TFM seems to > indicate that old style classes are the default: Yes, if you don't inherit from object, or another class that inherits from object (like the built-ins), you get an old-style class. > Yet TFM for 2.6.5 shows all class examples without specifying a > parent class. > http://docs.python.org/tutorial/classes.html As the docs also say, they were mostly written before the existence of new-style classes, and they haven't been updated to show the new syntax. Since Python 3.0 will make such a change obsolete, they will probably never be updated. > I've been taught that the proper way to create new style classes has > been to always specify an explicit "object" parent class when > creating a new class not based on other classes. > > Somewhere along the line I seemed to have missed the fact that it is > no longer necessary to define classes with 'object' as a parent in > order to get a new style class. That only holds for Python 3.x, since old-style classes don't exist any longer. > In other words, it seems that the following are now equivalent: > > class Name: > > -AND- > > class Name( object ): Only in Python 3.x. > My impression was the "class Name:" style created an old style class. Only in Python 2.x (and 1.x, but who still uses that?). -- Steven D'Aprano From breamoreboy at yahoo.co.uk Mon Jun 7 18:24:28 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 07 Jun 2010 17:24:28 +0100 Subject: [Tutor] a class query In-Reply-To: <1275926598.28113.1378884075@webmail.messagingengine.com> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com><1275923548.18844.1378876297@webmail.messagingengine.com> <1275926598.28113.1378884075@webmail.messagingengine.com> Message-ID: On 07/06/2010 17:03, python at bdurham.com wrote: > Hi Mark, > >>> I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? > >> RTFM? :) > > I am reading TFM :) > > Here's why I'm confused. The following paragraph from TFM seems to > indicate that old style classes are the default: > > Quote: For compatibility reasons, classes are still old-style by > default. New-style classes are created by specifying another new-style > class (i.e. a type) as a parent class, or the ?top-level type? object if > no other parent is needed. The behaviour of new-style classes differs > from that of old-style classes in a number of important details in > addition to what type() returns. Some of these changes are fundamental > to the new object model, like the way special methods are invoked. > Others are ?fixes? that could not be implemented before for > compatibility concerns, like the method resolution order in case of > multiple inheritance. > http://docs.python.org/reference/datamodel.html#newstyle > > Yet TFM for 2.6.5 shows all class examples without specifying a parent > class. > http://docs.python.org/tutorial/classes.html > > I've been taught that the proper way to create new style classes has > been to always specify an explicit "object" parent class when creating a > new class not based on other classes. > > Somewhere along the line I seemed to have missed the fact that it is no > longer necessary to define classes with 'object' as a parent in order to > get a new style class. > > In other words, it seems that the following are now equivalent: > > class Name: > > -AND- > > class Name( object ): > > My impression was the "class Name:" style created an old style class. > > Thanks for your help! > > Malcolm > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi Malcolm, I see that Stephen D'Aprano has already replied twice so I won't bother. Apart from that no offence meant, I hope none taken. Kindest regards. Mark Lawrence. From python at bdurham.com Mon Jun 7 18:25:38 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 07 Jun 2010 12:25:38 -0400 Subject: [Tutor] a class query In-Reply-To: <201006080211.11779.steve@pearwood.info> References: <20100607140135.GA13869@scriptkitchen.com><4C0D0706.5020505@gmail.com><1275923548.18844.1378876297@webmail.messagingengine.com> <201006080211.11779.steve@pearwood.info> Message-ID: <1275927938.31616.1378890365@webmail.messagingengine.com> > In Python 2.x, all classes are old-style unless you directly or indirectly inherit from object. If you inherit from nothing, it is an old-style class regardless of whether you say class Name: pass or class Name(): pass. In Python 3.x, there are no old-style classes. Thanks Steven! Malcolm From python at bdurham.com Mon Jun 7 18:27:49 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 07 Jun 2010 12:27:49 -0400 Subject: [Tutor] a class query In-Reply-To: <201006080215.05697.steve@pearwood.info> References: <20100607140135.GA13869@scriptkitchen.com><1275926598.28113.1378884075@webmail.messagingengine.com> <201006080215.05697.steve@pearwood.info> Message-ID: <1275928069.31917.1378890725@webmail.messagingengine.com> Steven, Thanks again for your explanations. I thought I had missed a major change in Python class behavior - relieved to find that I'm up-to-date. Cheers, Malcolm From python at bdurham.com Mon Jun 7 18:30:53 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 07 Jun 2010 12:30:53 -0400 Subject: [Tutor] a class query In-Reply-To: References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com><1275923548.18844.1378876297@webmail.messagingengine.com> <1275926598.28113.1378884075@webmail.messagingengine.com> Message-ID: <1275928253.32451.1378891111@webmail.messagingengine.com> Hi Mark, > I see that Stephen D'Aprano has already replied twice so I won't bother. Apart from that no offence meant, I hope none taken. Your RTFM reply actually gave me a good laugh. No (zero) offence taken. And I appreciate your many helpful posts in these forums. Cheers, Malcolm From adam.jtm30 at gmail.com Mon Jun 7 20:20:22 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 7 Jun 2010 19:20:22 +0100 Subject: [Tutor] Strange range and round behaviour Message-ID: Just out of curiosity does anyone know why you get a deprecation warning if you pass a float to range but if you use round, which returns a float, there is no warning? Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> range(2.0) __main__:1: DeprecationWarning: integer argument expected, got float [0, 1] >>> range(round(2.0)) [0, 1] >>> round(2.0) 2.0 >>> round(2.0, 0) 2.0 >>> round.__doc__ 'round(number[, ndigits]) -> floating point number\n\nRound a number to a given precision in decimal digits (default 0 digits).\nThis always returns a floating point number. Precision may be negative.' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilcomputertrasparente at gmail.com Mon Jun 7 10:08:00 2010 From: ilcomputertrasparente at gmail.com (Francesco Loffredo) Date: Mon, 07 Jun 2010 10:08:00 +0200 Subject: [Tutor] while loops / listeners In-Reply-To: References: Message-ID: <4C0CA8E0.709@libero.it> Hi all, I think that simply erasing those "continue" statements will let Python respond again. Those statements are both useless and damaging, because the following "time.sleep(.1)" statements will NEVER be executed. And this, in turn, is IMHO the reason why Python stops responding: it lacks the time to do so. Hope that helps Francesco Il 07/06/2010 5.09, Alex Hall wrote: > Hi all, > First off, I apologize to the list for my previous thread; somehow, > despite my having written the post, it ended up blank (????) > > I have a main loop which will continue for as long as neither player1 > nor player2 has won. Inside that loop I have a call to a function > which should basically wait until the user completes a turn, then > return, exiting this loop and returning to the main loop, the one > looping until there is a winner. Once back there, the second player's > idling function is called; once that user completes a turn, the main > loop switches back to the first user, and so on. Here is the main > loop: > player1.takeTurn() #someone has to start off the game > > #now loop until someone wins... > while not player1.isWinner and not player2.isWinner: > if player1.grid.turnOver: #player1 is done for this turn > player1.grid.speak("player 2 is going.") > #lock p1 out of the window, unlock p2, and then loop p2 until s/he > does something > player1.lock(); player2.unlock(); player2.takeTurn() > else: #player2 has completed a turn > player2.grid.speak("player 1 is going.") > #opposite of above - lock p2, unlock p1, loop until p1 is done > player2.lock(); player1.unlock(); player1.takeTurn() > #end if > continue #is this doing anything? > time.sleep(.1) #again, is this important? > #end while > > The lock and unlock functions are simply there to disable and enable > keyboard/mouse commands, respectively, so lock causes the player's > screen to stop responding to input while unlock unfreezes the screen. > This way, if you and I are playing a game, I can't keep shooting even > if my turn is over. > TakeTurn() is that smaller loop I was talking about: > def takeTurn(self): > while not self.grid.turnOver: #turnOver is true once a turn-ending > function is called in grid > continue > time.sleep(.1) > #end while > #end def > > That is inside the Player class. Grid is just another object that is > really the most important part of all the game logic; Grid holds the > wx frame on which everything is drawn, the boolean to tell if the turn > is over, the ships, and more. That is why the function checks > self.grid.turnOver, instead of just self.turnOver; turnOver tells if > the player has performed a move that ends a turn or not. Firing ends a > turn, while just moving around does not. > > The question, then, is this: when I run the code, Windows says > "python.exe has stopped responding". I know that this is because it is > getting stuck, probably in the takeTurn() loop. Ordinarily, a > situation like this would probably call for: > while ok: > ok=#program logic > > The hard part with my program, though, is that all input is set up > with a wx.AcceleratorTable object, so I cannot just dump everything > into a huge while loop and have it process that way. What I am looking > for is some kind of listener object, so that I can just monitor > self.grid.turnOver and call a function, or perform a few lines of > code, when the listener detects a change in turnOver. On the other > hand, there may be something simple that I am missing in my while loop > that would cause the problem of python.exe crashing to not happen > (well, not crashing, but rather not responding). I hope it is the > latter problem, but I am not sure what else I could add to the loop(s) > to stop this problem. Thanks, and sorry again for the blank message; > still not sure how that happened. Hopefully this one works! > > > > > > Nessun virus nel messaggio in arrivo. > Controllato da AVG - www.avg.com > Versione: 9.0.829 / Database dei virus: 271.1.1/2921 - Data di rilascio: 06/06/10 08:25:00 > From breamoreboy at yahoo.co.uk Mon Jun 7 22:14:26 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 07 Jun 2010 21:14:26 +0100 Subject: [Tutor] a class query In-Reply-To: <1275928253.32451.1378891111@webmail.messagingengine.com> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com><1275923548.18844.1378876297@webmail.messagingengine.com> <1275926598.28113.1378884075@webmail.messagingengine.com> <1275928253.32451.1378891111@webmail.messagingengine.com> Message-ID: On 07/06/2010 17:30, python at bdurham.com wrote: > Hi Mark, > >> I see that Stephen D'Aprano has already replied twice so I won't bother. Apart from that no offence meant, I hope none taken. > > Your RTFM reply actually gave me a good laugh. No (zero) offence taken. > And I appreciate your many helpful posts in these forums. > > Cheers, > Malcolm > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi Malcolm, Thanks for your kind response. Mind you it will cost you, if you ever get into my neck of the woods it will be at least 2 pints of Ringwood Old Thumper. Cheers. Mark. From missive at hotmail.com Mon Jun 7 22:16:47 2010 From: missive at hotmail.com (Lee Harr) Date: Tue, 8 Jun 2010 00:46:47 +0430 Subject: [Tutor] Strange range and round behaviour Message-ID: > Just out of curiosity does anyone know why you get a deprecation warning if > you pass a float to range but if you use round, which returns a float, there > is no warning? It has nothing to do with the round. It's just that the warning is only shown once: $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 >>> range(2.0) __main__:1: DeprecationWarning: integer argument expected, got float [0, 1] >>> range(2.0) [0, 1] >>> $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> range(round(2.0)) __main__:1: DeprecationWarning: integer argument expected, got float [0, 1] >>> range(round(2.0)) [0, 1] _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. https://signup.live.com/signup.aspx?id=60969 From payal-python at scriptkitchen.com Tue Jun 8 08:08:15 2010 From: payal-python at scriptkitchen.com (Payal) Date: Mon, 7 Jun 2010 23:08:15 -0700 Subject: [Tutor] no. of references Message-ID: <20100608060815.GA23201@scriptkitchen.com> Hi, If I have a list (or a dict), is there any way of knowing how many other variables are referencing the same object? With warm regards, -Payal -- From payal-python at scriptkitchen.com Tue Jun 8 08:10:38 2010 From: payal-python at scriptkitchen.com (Payal) Date: Mon, 7 Jun 2010 23:10:38 -0700 Subject: [Tutor] a class query In-Reply-To: <201006080211.11779.steve@pearwood.info> References: <20100607140135.GA13869@scriptkitchen.com> <4C0D0706.5020505@gmail.com> <1275923548.18844.1378876297@webmail.messagingengine.com> <201006080211.11779.steve@pearwood.info> Message-ID: <20100608061038.GB23201@scriptkitchen.com> On Tue, Jun 08, 2010 at 02:11:10AM +1000, Steven D'Aprano wrote: > In Python 2.x, all classes are old-style unless you directly or > indirectly inherit from object. If you inherit from nothing, it is an > old-style class regardless of whether you say > > class Name: pass > > or > > class Name(): pass > > In Python 3.x, there are no old-style classes. Thanks, that clears my doubt. With warm regards, -Payal -- From k247d0 at gmail.com Tue Jun 8 08:48:31 2010 From: k247d0 at gmail.com (KB SU) Date: Tue, 8 Jun 2010 12:33:31 +0545 Subject: [Tutor] accented characters to unaccented Message-ID: Hi, I have open url and read like following: $import urllib $txt = urllib.urlopen("http://www.terme-catez.si").read() $txt Gives output like below: ----other parts are skipped --- r\n 2010\r\n Terme \xc4\x8cate\xc5\xbe\r\n Slovenija\r\n
      \r\n Spletne re\ xc5\xa1itve\r\n © 1996-\r\n 2010\r\n (T)media

      \r\n \r\n\r\n
      \r\n
      \r\n \r\n \r\n \r\n \r\n
      \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n' If you see above, in junk of HTLM, there is text like 'Terme \xc4\x8cate\xc5\xbe' (original is 'Terme ?ate?'). Now, I want to convert code like '\xc4\x8c' or '\xc5\xbe' to unaccented chars so that 'Terme \xc4\x8cate\xc5\xbe' become 'Terme Catez'. Is there any way convert from whole HTML. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jun 8 09:59:31 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jun 2010 09:59:31 +0200 Subject: [Tutor] accented characters to unaccented References: Message-ID: KB SU wrote: > Hi, > > I have open url and read like following: > > $import urllib > $txt = urllib.urlopen("http://www.terme-catez.si").read() > $txt > If you see above, in junk of HTLM, there is text like 'Terme > \xc4\x8cate\xc5\xbe' (original is 'Terme ?ate?'). Now, I want to convert > code like '\xc4\x8c' or '\xc5\xbe' to unaccented chars so that 'Terme > \xc4\x8cate\xc5\xbe' become 'Terme Catez'. Is there any way convert from > whole HTML. First convert to unicode with txt = txt.decode("utf-8") and then follow http://effbot.org/zone/unicode-convert.htm Peter From steve at pearwood.info Tue Jun 8 12:07:28 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Jun 2010 20:07:28 +1000 Subject: [Tutor] no. of references In-Reply-To: <20100608060815.GA23201@scriptkitchen.com> References: <20100608060815.GA23201@scriptkitchen.com> Message-ID: <201006082007.29671.steve@pearwood.info> On Tue, 8 Jun 2010 04:08:15 pm Payal wrote: > Hi, > If I have a list (or a dict), is there any way of knowing how many > other variables are referencing the same object? Sort of. The question is simple, but the answer isn't. It depends what you mean by "variables", and it requires a good understanding of Python's programming model. Python doesn't have "variables" like C or Pascal, it has names and objects. Objects can be bound to no names at all: len([1,2,4]) or to a single name: x = [1,2,4] len(x) or to multiple names: x = y = z = [1,2,4] w = y len(w) Objects can also be referenced by other objects, which in turn could have zero, one or more names. Consider this example: >>> a = [1,2,4] >>> b = a >>> c = {None: ('xyz', b)} >>> class K: ... pass ... >>> d = K() >>> d.attr = [c] Given your question, how many "variables" refer to the list [1,2,4]?, what answer would you expect? Depending on how I count them, I get either 4, 5 or 6: 4: "variables" (names) a, b, c and d 5: the dict globals() has two references to the list, using keys 'a' and 'b'; the tuple ('xyz', b); the dict with key None and value the above tuple; the list [c]; the instance d has a dict __dict__ with key 'attr' 6: same as five, but counting globals() twice Interestingly, Python has a standard tool for tracking referrers, the gc (garbage collector) module, and it disagrees with all of those counts: >>> import gc >>> len(gc.get_referrers(a)) 2 >>> print gc.get_referrers(a) [('xyz', [1, 2, 4]), {'a': [1, 2, 4], 'c': {None: ('xyz', [1, 2, 4])}, 'b': [1, 2, 4], 'd': <__main__.C instance at 0xb7f6008c>, 'gc': , '__builtins__': , 'C': , '__name__': '__main__', '__doc__': None}] So gc says two objects *directly* refer to the list: the tuple, and globals(). But of course there are multiple *indirect* references to the list as well. So the answer you get depends on the way you ask it. -- Steven D'Aprano From davea at ieee.org Tue Jun 8 14:48:48 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 08 Jun 2010 08:48:48 -0400 Subject: [Tutor] no. of references In-Reply-To: <20100608060815.GA23201@scriptkitchen.com> References: <20100608060815.GA23201@scriptkitchen.com> Message-ID: <4C0E3C30.2080405@ieee.org> Payal wrote: > Hi, > If I have a list (or a dict), is there any way of knowing how many other > variables are referencing the same object? > > With warm regards, > -Payal > Depends on what you mean by variables. Try sys.getrefcount(mylist) Naturally, the count will be one higher than you expect. And you should only use this for debugging purposes. DaveA From hugo.yoshi at gmail.com Tue Jun 8 15:03:19 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 8 Jun 2010 15:03:19 +0200 Subject: [Tutor] no. of references In-Reply-To: <20100608060815.GA23201@scriptkitchen.com> References: <20100608060815.GA23201@scriptkitchen.com> Message-ID: <3718990424089414980@unknownmsgid> On 8 jun 2010, at 08:08, Payal wrote: > Hi, > If I have a list (or a dict), is there any way of knowing how many > other > variables are referencing the same object? > In short, not in any compatible way. If you have a bounded list of names, you can check them with the is operator. But the question "are there any names anywhere in my program that refer to this object?" is generally not answerable. The more relevant question is: why would you want to know this? Hugo From payal-python at scriptkitchen.com Tue Jun 8 16:25:13 2010 From: payal-python at scriptkitchen.com (Payal) Date: Tue, 8 Jun 2010 07:25:13 -0700 Subject: [Tutor] no. of references In-Reply-To: <201006082007.29671.steve@pearwood.info> References: <20100608060815.GA23201@scriptkitchen.com> <201006082007.29671.steve@pearwood.info> Message-ID: <20100608142513.GA28368@scriptkitchen.com> Hi all, Excuse for TOFU. Thanks a lot Steven, Dave and Hugo. Steven the explanation was really great. Thanks a lot for it. Hugo, I was just curious, have no real need. Thanks. With warm regards, -Payal -- On Tue, Jun 08, 2010 at 08:07:28PM +1000, Steven D'Aprano wrote: > On Tue, 8 Jun 2010 04:08:15 pm Payal wrote: > > Hi, > > If I have a list (or a dict), is there any way of knowing how many > > other variables are referencing the same object? > > Sort of. The question is simple, but the answer isn't. It depends what > you mean by "variables", and it requires a good understanding of > Python's programming model. > > Python doesn't have "variables" like C or Pascal, it has names and > objects. Objects can be bound to no names at all: > > len([1,2,4]) > > or to a single name: > > x = [1,2,4] > len(x) > > or to multiple names: > > x = y = z = [1,2,4] > w = y > len(w) > > > Objects can also be referenced by other objects, which in turn could > have zero, one or more names. Consider this example: > > >>> a = [1,2,4] > >>> b = a > >>> c = {None: ('xyz', b)} > >>> class K: > ... pass > ... > >>> d = K() > >>> d.attr = [c] > > > Given your question, how many "variables" refer to the list [1,2,4]?, > what answer would you expect? Depending on how I count them, I get > either 4, 5 or 6: > > 4: > "variables" (names) a, b, c and d > > 5: > the dict globals() has two references to the list, using keys 'a' > and 'b'; > the tuple ('xyz', b); > the dict with key None and value the above tuple; > the list [c]; > the instance d has a dict __dict__ with key 'attr' > > 6: > same as five, but counting globals() twice > > > Interestingly, Python has a standard tool for tracking referrers, the gc > (garbage collector) module, and it disagrees with all of those counts: > > >>> import gc > >>> len(gc.get_referrers(a)) > 2 > >>> print gc.get_referrers(a) > [('xyz', [1, 2, 4]), {'a': [1, 2, 4], 'c': {None: ('xyz', [1, 2, > 4])}, 'b': [1, 2, 4], 'd': <__main__.C instance at 0xb7f6008c>, 'gc': > , '__builtins__': (built-in)>, 'C': 0xb7d0602c>, '__name__': '__main__', '__doc__': None}] > > So gc says two objects *directly* refer to the list: the tuple, and > globals(). But of course there are multiple *indirect* references to > the list as well. So the answer you get depends on the way you ask it. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jf_byrnes at comcast.net Tue Jun 8 18:38:28 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 08 Jun 2010 11:38:28 -0500 Subject: [Tutor] Tkinter - master attribute Message-ID: <4C0E7204.6080908@comcast.net> When reading code examples I see things like theframe.master.title('spam) or def __init__(self, master): frame = Frame(master) When I encounter these I tend to get bogged down trying to decide if "master" has special meaning or is just a name the author has chosen. For example is it similar to Buttton(text='spam) where text in this case has special meaning. I've goolged and found references to "widgets master attributes" but nothing to really explain it. Could someone point me to a good reference so that I could better understand it use. Thanks, Jim From steve at pearwood.info Tue Jun 8 18:52:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 9 Jun 2010 02:52:08 +1000 Subject: [Tutor] Tkinter - master attribute In-Reply-To: <4C0E7204.6080908@comcast.net> References: <4C0E7204.6080908@comcast.net> Message-ID: <201006090252.09077.steve@pearwood.info> On Wed, 9 Jun 2010 02:38:28 am Jim Byrnes wrote: > When reading code examples I see things like > theframe.master.title('spam) or > def __init__(self, master): > frame = Frame(master) > > When I encounter these I tend to get bogged down trying to decide if > "master" has special meaning or is just a name the author has chosen. > For example is it similar to Buttton(text='spam) where text in this > case has special meaning. To understand Tkinter effectively, you have to know it is an interface to the Tk language (hence the name TK INTERface). Googling on "tk master widget" brings me to this: http://www.tkdocs.com/tutorial/concepts.html which includes this: Geometry management in Tk relies on the concept of master and slave widgets. A master is a widget, typically a toplevel window or a frame, which will contain other widgets, which are called slaves. You can think of a geometry manager as taking control of the master widget, and deciding what will be displayed within. I suppose you could say that master and slave widgets could be named parent and child widgets instead. -- Steven D'Aprano From alan.gauld at btinternet.com Wed Jun 9 00:52:34 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Jun 2010 23:52:34 +0100 Subject: [Tutor] Tkinter - master attribute References: <4C0E7204.6080908@comcast.net> Message-ID: "Jim Byrnes" wrote in > When reading code examples I see things like > theframe.master.title('spam) > def __init__(self, master): > frame = Frame(master) > When I encounter these I tend to get bogged down trying to decide if > "master" has special meaning or is just a name the author has > chosen. In the first case master is an attribute of the frame and as such is defined by the frame definition. In the second case master is just an arbitrary name for a parameter like any other. Because it is being used to correspond to the master attribute of the Framer(as seen in the call to Frame() ) the author has used the name master too. But other common names for the same attribute are parent, root, top, etc > For example is it similar to Buttton(text='spam) where text in this > case has special meaning. In the first example yes, in the second no. Although 'text' is even more special because it is actually defined in the underlying Tk code rather than in Tkinter Python code. > I've goolged and found references to "widgets master attributes" but > nothing to really explain it. Could someone point me to a good > reference so that I could better understand it use. Because Tkinter is a thin wrapper around the underlying Tk tookit many atttributes of widgets are actually defined in the Tk code and simply mirrored by Tkinter. In that sense the widget attributes tend to have fixed names. But in Tkinter code the naming is essentially arbitrary and follows the usual Python naming conventions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ibhatm at gmail.com Wed Jun 9 02:44:16 2010 From: ibhatm at gmail.com (Manju) Date: Wed, 9 Jun 2010 10:44:16 +1000 Subject: [Tutor] Extract from file Message-ID: <004001cb076c$e601a140$b204e3c0$@com> Hi, I need help with extracting information from file. I have a file which is a comma delimited text file containing separate line for each booking. Each line is composed of date, room number, course number and course day. I need to extract only the room number which is entered at the prompt and display course number, date and room number. I have so far managed accept the entry from the prompt, to open the file and display all the text Please help. Regards, Manju -------------- next part -------------- An HTML attachment was scrubbed... URL: From memilanuk at gmail.com Wed Jun 9 05:19:32 2010 From: memilanuk at gmail.com (Monte Milanuk) Date: Tue, 08 Jun 2010 20:19:32 -0700 Subject: [Tutor] Extract from file In-Reply-To: <004001cb076c$e601a140$b204e3c0$@com> References: <004001cb076c$e601a140$b204e3c0$@com> Message-ID: On 6/8/10 5:44 PM, Manju wrote: > Hi, > > I need help with extracting information from file. > > I have a file which is a comma delimited text file containing separate > line for each booking. Each line is composed of date, room number, > course number and course day. Course day??? Not sure what you meant by that, on top of the already mentioned 'date'...? > > I need to extract only the room number which is entered at the prompt > and display course number, date and room number. > > I have so far managed accept the entry from the prompt, to open the file > and display all the text > This may be a case of the blind leading the blind, but here goes: Given this data file (comments not included in actual file): # # example.txt # # date, room, course 2010-06-08,123,246 2009-06-08,234,468 2008-06-08,345,680 # # example.py # room = raw_input("Enter the room #: ") file = open("example.txt", "r") for line in file: line = line.strip() line = line.split(',') if line[1] == room: print "Date: " + line[0] print "Room: " + line[1] print "Course: " + line[2] file.close() >>> Enter the room #: 234 Date: 2009-06-08 Room: 234 Course: 468 >>> HTH, Monte From lang at tharin.com Wed Jun 9 06:11:44 2010 From: lang at tharin.com (Lang Hurst) Date: Tue, 08 Jun 2010 21:11:44 -0700 Subject: [Tutor] Regular expression grouping insert thingy Message-ID: <4C0F1480.6010204@tharin.com> This is so trivial (or should be), but I can't figure it out. I'm trying to do what in vim is :s/\([0-9]\)x/\1*x/ That is, "find a number followed by an x and put a "*" in between the number and the x" So, if the string is "6443x - 3", I'll get back "6443*x - 3" I won't write down all the things I've tried, but suffice it to say, nothing has done it. I just found myself figuring out how to call sed and realized that this should be a one-liner in python too. Any ideas? I've read a lot of documentation, but I just can't figure it out. Thanks. -- There are no stupid questions, just stupid people. From woodm1979 at gmail.com Wed Jun 9 06:17:59 2010 From: woodm1979 at gmail.com (Matthew Wood) Date: Tue, 8 Jun 2010 22:17:59 -0600 Subject: [Tutor] Regular expression grouping insert thingy In-Reply-To: <4C0F1480.6010204@tharin.com> References: <4C0F1480.6010204@tharin.com> Message-ID: re.sub(r'(\d+)x', r'\1*x', input_text) -- I enjoy haiku but sometimes they don't make sense; refrigerator? On Tue, Jun 8, 2010 at 10:11 PM, Lang Hurst wrote: > This is so trivial (or should be), but I can't figure it out. > > I'm trying to do what in vim is > > :s/\([0-9]\)x/\1*x/ > > That is, "find a number followed by an x and put a "*" in between the > number and the x" > > So, if the string is "6443x - 3", I'll get back "6443*x - 3" > > I won't write down all the things I've tried, but suffice it to say, > nothing has done it. I just found myself figuring out how to call sed and > realized that this should be a one-liner in python too. Any ideas? I've > read a lot of documentation, but I just can't figure it out. Thanks. > > -- > There are no stupid questions, just stupid people. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lang at tharin.com Wed Jun 9 06:27:55 2010 From: lang at tharin.com (Lang Hurst) Date: Tue, 08 Jun 2010 21:27:55 -0700 Subject: [Tutor] Regular expression grouping insert thingy In-Reply-To: References: <4C0F1480.6010204@tharin.com> Message-ID: <4C0F184B.5070006@tharin.com> Oh. Crap, I knew it would be something simple, but honestly, I don't think that I would have gotten there. Thank you so much. Seriously saved me more grey hair. Matthew Wood wrote: > re.sub(r'(\d+)x', r'\1*x', input_text) > > -- > > I enjoy haiku > but sometimes they don't make sense; > refrigerator? > > > On Tue, Jun 8, 2010 at 10:11 PM, Lang Hurst > wrote: > > This is so trivial (or should be), but I can't figure it out. > > I'm trying to do what in vim is > > :s/\([0-9]\)x/\1*x/ > > That is, "find a number followed by an x and put a "*" in between > the number and the x" > > So, if the string is "6443x - 3", I'll get back "6443*x - 3" > > I won't write down all the things I've tried, but suffice it to > say, nothing has done it. I just found myself figuring out how to > call sed and realized that this should be a one-liner in python > too. Any ideas? I've read a lot of documentation, but I just > can't figure it out. Thanks. > > -- > There are no stupid questions, just stupid people. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- There are no stupid questions, just stupid people. From eddie9139 at gmail.com Wed Jun 9 13:52:52 2010 From: eddie9139 at gmail.com (Eddie) Date: Wed, 9 Jun 2010 21:52:52 +1000 Subject: [Tutor] Removing an archived message Message-ID: To an admin of this group: Is it possible to get an archived email on the web of mien from thsi group containing personal info about me removed? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at uw.edu Wed Jun 9 20:40:29 2010 From: jjcrump at uw.edu (jjcrump at uw.edu) Date: Wed, 9 Jun 2010 11:40:29 -0700 (PDT) Subject: [Tutor] treeTraversal, nested return? In-Reply-To: References: Message-ID: Thanks to Matthew and Denis for trying to enlighten me. Thanks to your clues I've made some progress; however, I can't seem to get the hang of the usual recursion trick of keeping track of the level one is on. It doesn't work, I suppose, because the data structure I'm traversing isn't actually nested, its a flat series of lists of tuples. I did finally get a function to traverse the "tree-like" data coming from the db getRecord() returns a tuple of record-type, record-id, parent-id, and title, thus: ('work', 47302, 47301, 'record title') getImages(id) returns a list of 'image' tuples whose parent-id is id getWorks(id) returns a list of 'work' tuples whose parent-id is id works can be nodes, images can't so: def makeDecendentList(id, result): result.append(getRecord(id)) if getImages(id): for x in getImages(id): result.append(x) if not getWorks(id): return else: for y in getWorks(id): makeDecendentList(y[1],result) return result called with the empty list as the second argument. Well and good. This walks the 'tree' (following the parent-ids) and returns me a list of all the decendents of id. But what I wanted was a nested data structure. In the fashion of an ape given a typewriter and sufficient time, I trial and errored my way to this: def makeNestedLists(id): result = [] result.append(getRecord(id)) result.extend(getImages(id)) if not getWorks(id): return result else: result.extend([makeNestedLists(x[1]) for x in getWorks(id)]) return result To my surprise, this gets me exactly what I wanted, eg: [ ('work', 47301, 47254, 'a title'), ('image', 36871, 47301, 'a title'), ('image', 36872, 47301, 'a title'), [ ('work', 47302, 47301, 'a title'), ('image', 10706, 47302, 'a title'), ('image', 10725, 47302, 'a title') ] ] To my surprise, I say, because it looks like it shouldn't work at all with the result being set to the empty list with each recursion; moreover, if I spell out the loop in the list comp like this: def makeNestedLists(id): result = [] result.append(getRecord(id)) result.extend(getImages(id)) if not getWorks(id): return result else: for x in getWorks(id): result.extend(makeNestedLists(x[1])) return result I once again get a flat list of all the decendents of id. I know it's sad, but can any wise tutor explain to me what's going on in the code that I myself wrote? Thanks, Jon From woodm1979 at gmail.com Wed Jun 9 22:31:25 2010 From: woodm1979 at gmail.com (Matthew Wood) Date: Wed, 9 Jun 2010 14:31:25 -0600 Subject: [Tutor] Fwd: treeTraversal, nested return? In-Reply-To: References: Message-ID: Gah, hit the reply button instead of reply-all. :-( -- I enjoy haiku but sometimes they don't make sense; refrigerator? ---------- Forwarded message ---------- From: Matthew Wood Date: Wed, Jun 9, 2010 at 2:30 PM Subject: Re: [Tutor] treeTraversal, nested return? To: jjcrump at uw.edu Well, I've taken a look at your code. In your last example, the appending last line here: > else: > for x in getWorks(id): > result.extend(makeNestedLists(x[1])) uses, a list.extend call. If you switch that to append, you SHOULD see the result you're looking for. ...at least as best I can guess without replicating the code and having some good test cases. Here's some of your other questions: >To my surprise, I say, because it looks like it shouldn't work at all >with the result being set to the empty list with each recursion; Each time you call the function 'makeNestedLists' a new copy of all the local variables is created. Thus, you aren't blanking the 'result' list each time; instead you're creating a new list each time. Then, when you return the list, you then shove it into the parent-function-instance list. Just take care to understand the difference between: [1, 2, 3].append([4, 5, 6]) -> [1, 2, 3, [4, 5, 6]] [1, 2, 3].extend([4, 5, 6]) -> [1, 2, 3, 4, 5, 6] Your list comprehension example above adds an extra list wrapper around things, which is why the extend worked. -- I enjoy haiku but sometimes they don't make sense; refrigerator? On Wed, Jun 9, 2010 at 12:40 PM, wrote: > Thanks to Matthew and Denis for trying to enlighten me. Thanks to your > clues I've made some progress; however, I can't seem to get the hang of the > usual recursion trick of keeping track of the level one is on. It doesn't > work, I suppose, because the data structure I'm traversing isn't actually > nested, its a flat series of lists of tuples. > > I did finally get a function to traverse the "tree-like" data coming from > the db > > getRecord() returns a tuple of record-type, record-id, parent-id, and > title, thus: > ('work', 47302, 47301, 'record title') > > getImages(id) returns a list of 'image' tuples whose parent-id is id > getWorks(id) returns a list of 'work' tuples whose parent-id is id > > works can be nodes, images can't > > so: > > def makeDecendentList(id, result): > result.append(getRecord(id)) > if getImages(id): > for x in getImages(id): > result.append(x) > if not getWorks(id): > return > else: > for y in getWorks(id): > makeDecendentList(y[1],result) > return result > > called with the empty list as the second argument. > > Well and good. This walks the 'tree' (following the parent-ids) and returns > me a list of all the decendents of id. But what I wanted was a nested data > structure. > > In the fashion of an ape given a typewriter and sufficient time, I trial > and errored my way to this: > > def makeNestedLists(id): > result = [] > result.append(getRecord(id)) > result.extend(getImages(id)) > if not getWorks(id): > return result > else: > result.extend([makeNestedLists(x[1]) for x in getWorks(id)]) > return result > > To my surprise, this gets me exactly what I wanted, eg: > > [ ('work', 47301, 47254, 'a title'), > ('image', 36871, 47301, 'a title'), > ('image', 36872, 47301, 'a title'), > [ ('work', 47302, 47301, 'a title'), > ('image', 10706, 47302, 'a title'), > ('image', 10725, 47302, 'a title') > ] > ] > > To my surprise, I say, because it looks like it shouldn't work at all with > the result being set to the empty list with each recursion; moreover, if I > spell out the loop in the list comp like this: > > def makeNestedLists(id): > result = [] > result.append(getRecord(id)) > result.extend(getImages(id)) > if not getWorks(id): > return result > else: > for x in getWorks(id): > result.extend(makeNestedLists(x[1])) > return result > > I once again get a flat list of all the decendents of id. > > I know it's sad, but can any wise tutor explain to me what's going on in > the code that I myself wrote? > > Thanks, > Jon > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zubin.mithra at gmail.com Wed Jun 9 11:06:55 2010 From: zubin.mithra at gmail.com (Zubin Mithra) Date: Wed, 9 Jun 2010 14:36:55 +0530 Subject: [Tutor] 2to3 conversion Message-ID: Hey everyone, I was running 2to3 on a particular file and I got the following traceback( http://paste.pocoo.org/show/223468/). The file which I was attempting to convert can be viewed here( http://paste.pocoo.org/show/223469/). Any pointers on what needs to be done? Thanks in advance, Zubin -------------- next part -------------- An HTML attachment was scrubbed... URL: From dkuhlman at rexx.com Wed Jun 9 23:37:34 2010 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 9 Jun 2010 14:37:34 -0700 Subject: [Tutor] Extract from file In-Reply-To: References: <004001cb076c$e601a140$b204e3c0$@com> Message-ID: <20100609213734.GA24324@cutter.rexx.com> On Tue, Jun 08, 2010 at 08:19:32PM -0700, Monte Milanuk wrote: > > On 6/8/10 5:44 PM, Manju wrote: > >Hi, > > > >I need help with extracting information from file. > > > >I have a file which is a comma delimited text file containing separate > >line for each booking. Each line is composed of date, room number, > >course number and course day. > > Course day??? Not sure what you meant by that, on top of the already > mentioned 'date'...? > > > > >I need to extract only the room number which is entered at the prompt > >and display course number, date and room number. > > > >I have so far managed accept the entry from the prompt, to open the file > >and display all the text > > > Monte gave you a good suggestion *if* you are sure that there is no quoting and, especially, if you are sure that there are no commas inside of quotes in your input data. However, it seems that you are dealing with a CSV (comma separated values) file. Python has a module for that. See: http://docs.python.org/library/csv.html That module might help you write safer code. -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Thu Jun 10 00:34:12 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Jun 2010 23:34:12 +0100 Subject: [Tutor] Removing an archived message References: Message-ID: I tried to send a reply to you directly but my mail server errors on your gmail account. Can you please reply to me directly (preferably from another account!) and I'll see what can be done. Alan G. List Moderator "Eddie" wrote in message news:AANLkTilszAzlhRymMaUI3P1QjuzvufCYO085RBIP6Hgp at mail.gmail.com... > To an admin of this group: Is it possible to get an archived email > on the > web of mien from thsi group containing personal info about me > removed? > > Thanks > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From vceder at canterburyschool.org Thu Jun 10 01:54:28 2010 From: vceder at canterburyschool.org (Vern Ceder) Date: Wed, 09 Jun 2010 19:54:28 -0400 Subject: [Tutor] 2to3 conversion In-Reply-To: References: Message-ID: <4C1029B4.6070505@canterburyschool.org> Zubin Mithra wrote: > Hey everyone, > > I was running 2to3 on a particular file and I got the following > traceback(http://paste.pocoo.org/show/223468/). > > The file which I was attempting to convert can be viewed > here(http://paste.pocoo.org/show/223469/). > > Any pointers on what needs to be done? The traceback indicates that the utf-8 codec doesn't know how to decode the values at bytes 232-234, yet when I saved the file just now, 2to3 ran without giving that error. In fact it only flagged the exception handling as needing mofications. I wonder if the version served by the pastebin is *exactly* the same as the one you are using on your machine? Cheers, Vern > > Thanks in advance, > Zubin > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW From memilanuk at gmail.com Thu Jun 10 04:02:21 2010 From: memilanuk at gmail.com (Monte Milanuk) Date: Thu, 10 Jun 2010 02:02:21 +0000 (UTC) Subject: [Tutor] Extract from file References: <004001cb076c$e601a140$b204e3c0$@com> <20100609213734.GA24324@cutter.rexx.com> Message-ID: Dave Kuhlman rexx.com> writes: > > Monte gave you a good suggestion *if* you are sure that there is no > quoting and, especially, if you are sure that there are no commas > inside of quotes in your input data. > > However, it seems that you are dealing with a CSV (comma separated > values) file. Python has a module for that. See: > > http://docs.python.org/library/csv.html > > That module might help you write safer code. > Well, like I said... 'blind leading the blind'. I was piecing it together from what I've been exposed to. I had a feeling there was a csv function out there but not having any experience with it I stuck with what I had seen. Reading up on the csv file reading function, it does appear to be a *much* better solution for reading the file and processing the contents! Monte From prasadaraon50 at gmail.com Thu Jun 10 17:14:56 2010 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 10 Jun 2010 20:44:56 +0530 Subject: [Tutor] Doubts galore. Message-ID: Hi def cript(doc=None,data =None): if doc==None and data==None:doc=sys.agv1 elif doc: data=open(doc,'r').read() data_c= binascii.hexlify(data) else:data_c= binascii.hexlify(data) if doc: q=tempfile.TemporaryFile() q.write(data_c) os.rename(q,doc) return return data_c cript(doc='./language.txt') Traceback (most recent call last): File "", line 1, in File "", line 10, in cript TypeError: coercing to Unicode: need string or buffer, file found 1)Why I got the above error message with the above function?How to correct it? 2)Is it reasonable to have 2 if blocks in a function as above? 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my file as I expect it to do) Please someone enlighten me. Prasad From steve at alchemy.com Thu Jun 10 17:26:28 2010 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 10 Jun 2010 08:26:28 -0700 Subject: [Tutor] Doubts galore. In-Reply-To: References: Message-ID: <20100610152628.GA1715@dragon.alchemy.com> On Thu, Jun 10, 2010 at 08:44:56PM +0530, prasad rao wrote: > Hi > > def cript(doc=None,data =None): > if doc==None and data==None:doc=sys.agv1 Never NEVER compare for equality with None. What you want is: if doc is None and data is None: Also, what is "sys.agv1"? Did you mean sys.argv[1]? > elif doc: > data=open(doc,'r').read() > data_c= binascii.hexlify(data) > else:data_c= binascii.hexlify(data) > if doc: > q=tempfile.TemporaryFile() > q.write(data_c) > os.rename(q,doc) > return > return data_c It would probably be cleaner to use one-line conditional statements (sparingly) where they make sense on their own, but not to mix multi-line and single line styles in the same if-else structure. I'm not sure the logical flow through there does what you think it does, though. > cript(doc='./language.txt') > Traceback (most recent call last): > File "", line 1, in > File "", line 10, in cript > TypeError: coercing to Unicode: need string or buffer, file found > Is this the actual code or did you retype it? It has some typos which makes me wonder. If you copy/paste the actual code that can remove any confusion introduced by simple typing mistakes, so we are sure we're all looking at the same thing here. > 1)Why I got the above error message with the above function?How to correct it? The binascii.hexlify() function converts a binary data string into hexadecimal digits. You didn't give it a data string to work from, you gave it an open file object. You'll need to actually read the data from the file and give that to the function. > 2)Is it reasonable to have 2 if blocks in a function as above? Sure > 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my > file as I expect it to do) It creates a TEMPORARY file. That means you can expect it to exist on disk until you close it, and then if at all possible, it will automatically be destroyed for you. Hence "temporary". Depending on your platform, while there will be a physical disk file, it might not even show up in a directory or be openable by other applications. If you want a file to not be temporary, use open() to create it. > > Please someone enlighten me. > > Prasad > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From lie.1296 at gmail.com Thu Jun 10 17:41:11 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Jun 2010 01:41:11 +1000 Subject: [Tutor] Doubts galore. In-Reply-To: References: Message-ID: On 06/11/10 01:14, prasad rao wrote: > Hi > > def cript(doc=None,data =None): > if doc==None and data==None:doc=sys.agv1 > elif doc: > data=open(doc,'r').read() > data_c= binascii.hexlify(data) > else:data_c= binascii.hexlify(data) > if doc: > q=tempfile.TemporaryFile() > q.write(data_c) > os.rename(q,doc) > return > return data_c > > > cript(doc='./language.txt') > Traceback (most recent call last): > File "", line 1, in > File "", line 10, in cript > TypeError: coercing to Unicode: need string or buffer, file found > > 1)Why I got the above error message with the above function?How to correct it? The error message points out here: # line 10 os.rename(q,doc) ^^^ scanning a few lines earlier, we saw: q=tempfile.TemporaryFile() os.rename() doesn't rename a file object; os.rename() takes two string arguments. > 2)Is it reasonable to have 2 if blocks in a function as above? This is where boolean algebra can help. An elif-block will only be run when all the if-elif blocks before it evaluates to false. IOW, your code is equivalent to this: if doc==None and data==None: doc=sys.agv1 if not (doc==None and data==None) and doc: data=open(doc,'r').read() data_c= binascii.hexlify(data) except that "doc==None and data==None" is only evaluated once. So, using boolean algebra (assuming a reasonable definition of == and !=): not (doc==None and data==None) and doc (doc!=None or data!=None) and doc now depending on the intent of "doc" and "doc != None"; it may be possible to simplify that to only: data != None. Note that this is all assuming a reasonable definition of ==, !=, not, etc and assuming no side effects and assuming that the checks are equally lightweight. > 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my > file as I expect it to do) AFAIK, tempfile creates a file in harddisk, but I've never used tempfile, so don't quote me on that. From prasadaraon50 at gmail.com Thu Jun 10 18:13:34 2010 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 10 Jun 2010 21:43:34 +0530 Subject: [Tutor] Doubts galore. In-Reply-To: <20100610152628.GA1715@dragon.alchemy.com> References: <20100610152628.GA1715@dragon.alchemy.com> Message-ID: > Never NEVER compare for equality with None. > > What you want is: > if doc is None and data is None: > > Also, what is "sys.agv1"? Did you mean sys.argv[1]? yes > > elif doc: > > data=open(doc,'r').read() > > data_c= binascii.hexlify(data) > > else:data_c= binascii.hexlify(data) > > if doc: > > q=tempfile.TemporaryFile() > > q.write(data_c) > > os.rename(q,doc) > > return > > return data_c > It would probably be cleaner to use one-line > conditional statements (sparingly) where they make > sense on their own, but not to mix multi-line and > single line styles in the same if-else structure. I am a newbie.I couldn't understand that comment. > I'm not sure the logical flow through there > does what you think it does, though. > > cript(doc='./language.txt') > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 10, in cript > > TypeError: coercing to Unicode: need string or buffer, file found > Is this the actual code or did you retype it? I just copied from .py file and pasted. > It has some typos which makes me wonder. If you copy/paste > the actual code that can remove any confusion introduced > by simple typing mistakes, so we are sure we're all looking > at the same thing here. > > > > 1)Why I got the above error message with the above function?How to correct it? > > > The binascii.hexlify() function converts a binary data string into > hexadecimal digits. You didn't give it a data string to work from, > you gave it an open file object. You'll need to actually read the > data from the file and give that to the function. > > > > 2)Is it reasonable to have 2 if blocks in a function as above? > > > Sure > > > > 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my > > file as I expect it to do) > > > It creates a TEMPORARY file. That means you can expect it to > exist on disk until you close it, and then if at all possible, > it will automatically be destroyed for you. Hence "temporary". > Depending on your platform, while there will be a physical disk > file, it might not even show up in a directory or be openable by > other applications. > > If you want a file to not be temporary, use open() to create it. > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. Thanks for the reply..Now I will try to correct my code. From steve at alchemy.com Thu Jun 10 19:11:10 2010 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 10 Jun 2010 10:11:10 -0700 Subject: [Tutor] Doubts galore. In-Reply-To: References: <20100610152628.GA1715@dragon.alchemy.com> Message-ID: <20100610171110.GB1715@dragon.alchemy.com> On Thu, Jun 10, 2010 at 09:43:34PM +0530, prasad rao wrote: > > It would probably be cleaner to use one-line > > conditional statements (sparingly) where they make > > sense on their own, but not to mix multi-line and > > single line styles in the same if-else structure. > > I am a newbie.I couldn't understand that comment. So occasionally it's cleaner and clearer to put the condition and statement on one line like if x>0: print x But often you need more than one line, so you make a block structure: if x>0: do_stuff() do_more_stuff() If you have multiple blocks in an if-elif-elif-...-else structure, don't go back and forth between one-line and multi-line blocks, be consistent, so instead of something like if x>0: do_one_thing() elif x<0: do_something_else(-x) something_entirely_different(x**2) elif x==0 and y>0: do_something_else(y) yet_another_function(y**3) else: raise ValueError('values for x and y not in allowed range') you should be consistent and write this as: if x>0: do_one_thing() elif x<0: do_something_else(-x) something_entirely_different(x**2) elif x==0 and y>0: do_something_else(y) yet_another_function(y**3) else: raise ValueError('values for x and y not in allowed range') -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From beachkid at insightbb.com Fri Jun 11 15:57:34 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 09:57:34 -0400 Subject: [Tutor] Looking for duplicates within a list Message-ID: <4C1240CE.7050807@insightbb.com> I have been working on this problem for several days and I am not making any progress. I have a group of 18 number, in ascending order, within a list. They ranged from 1 to 39. Some numbers are duplicated as much as three times or as few as none. I started with one list containing the numbers. For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: for j in range (0, 5): x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. TIA, Ken From mehgcap at gmail.com Fri Jun 11 16:20:20 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 11 Jun 2010 10:20:20 -0400 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: On 6/11/10, Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress. I have a group of 18 number, in ascending order, within a > list. They ranged from 1 to 39. Some numbers are duplicated as much as > three times or as few as none. FYI, Python's "set" data type will let you have a list and never have a repeat. I know that is not your goal now, but if you want to remove duplicates, it seems like a good choice. > > I started with one list containing the numbers. For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > > for j in range (0, 5): > x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? A couple points here. First, you will want to make life easier by saying range(0, len(a)) so that the loop will work no matter the size of a. Second, for comparing a list to itself, here is a rather inefficient, though simple, way: for i in range(0, len(a)): x=a[i] for j in range(0, len(a)): y=a[j] if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the same index of a > > In any event, if a number is listed more than once, I would like to know > how many times, such as 2 or 3 times. For example, '3' is listed twice > within a list. Do not quote me here, but I think sets may be able to tell you that as well. > > TIA, > > Ken > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From beachkid at insightbb.com Fri Jun 11 16:31:58 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 10:31:58 -0400 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <630560.5642.qm@web95316.mail.in2.yahoo.com> References: <630560.5642.qm@web95316.mail.in2.yahoo.com> Message-ID: <4C1248DE.6090508@insightbb.com> vijay wrote: > Check out this code > l= [1, 2, 3, 3, 4] > d={} > for item in l: > d.setdefaut(item,0) > d[item] +=1 > print d > {1: 1, 2: 1, 3: 2, 4: 1} > > > with regard's > vijay > > Thanks. Very interesting concept. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Fri Jun 11 16:40:58 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 10:40:58 -0400 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: References: <4C1240CE.7050807@insightbb.com> Message-ID: <4C124AFA.7030007@insightbb.com> Alex Hall wrote: > On 6/11/10, Ken G. wrote: > >> I have been working on this problem for several days and I am not making >> any progress. I have a group of 18 number, in ascending order, within a >> list. They ranged from 1 to 39. Some numbers are duplicated as much as >> three times or as few as none. >> > FYI, Python's "set" data type will let you have a list and never have > a repeat. I know that is not your goal now, but if you want to remove > duplicates, it seems like a good choice. > >> I started with one list containing the numbers. For example, they are >> listed as like below: >> >> a = [1, 2, 3, 3, 4] >> >> I started off with using a loop: >> >> for j in range (0, 5): >> x = a[0] # for example, 1 >> >> How would I compare '1' with 2, 3, 3, 4? >> >> Do I need another duplicated list such as b = a and compare a[0] with >> either b[0], b[1], b[2], b[3], b[4]? >> >> Or do I compare a[0] with a[1], a[2], a[3], a[4]? >> > A couple points here. First, you will want to make life easier by > saying range(0, len(a)) so that the loop will work no matter the size > of a. > Second, for comparing a list to itself, here is a rather inefficient, > though simple, way: > > for i in range(0, len(a)): > x=a[i] > for j in range(0, len(a)): > y=a[j] > if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the > same index of a > >> In any event, if a number is listed more than once, I would like to know >> how many times, such as 2 or 3 times. For example, '3' is listed twice >> within a list. >> > Do not quote me here, but I think sets may be able to tell you that as well. > >> TIA, >> >> Ken >> Thank you for your contribution. As seen here, I have much to learn. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jun 11 16:46:25 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 11 Jun 2010 16:46:25 +0200 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: On 11 June 2010 15:57, Ken G. wrote: > In any event, if a number is listed more than once, I would like to know how > many times, such as 2 or 3 times. ?For example, '3' is listed twice within a > list. If you do not have top keep the order of the number this will work. >>> a = [1, 2, 3, 3, 4] >>> counted = {} >>> for n in a: if not n in counted: counted[n] = 1 else: counted[n] += 1 >>> counted {1: 1, 2: 1, 3: 2, 4: 1} >>> for x, y in counted.items(): if y > 1: print "Number %s was found %s times" % (x, y) else: print "Number %s was found %s time" % (x, y) Number 1 was found 1 time Number 2 was found 1 time Number 3 was found 2 times Number 4 was found 1 time Greets Sander From ljmamoreira at gmail.com Fri Jun 11 16:49:22 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 11 Jun 2010 15:49:22 +0100 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: <201006111549.22751.ljmamoreira@gmail.com> On Friday, June 11, 2010 02:57:34 pm Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress. I have a group of 18 number, in ascending order, within a > list. They ranged from 1 to 39. Some numbers are duplicated as much as > three times or as few as none. > > I started with one list containing the numbers. For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > > for j in range (0, 5): > x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? > > In any event, if a number is listed more than once, I would like to know > how many times, such as 2 or 3 times. For example, '3' is listed twice > within a list. > > TIA, > I would do it with a dictionary: def reps(lst): dict = {} for item in lst: if item in dict: dict[item] += 1 else: dict[item] = 1 return dict This function returns a dictionary with of the number of times each value in the list is repeated. Even shorter using dict.setdefault: def reps(lst): dict={} for item in lst: dict[item] = dict.setdefault(item,0) + 1 return dict For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns {1: 1, 2: 3, 4: 2, 5: 1} Using the fact that the list is ordered, one can design a more efficient solution (go through the list; if this item is equal to the previous, then it is repeated, else, it is a new value). But you list is short enough for this direct approach to work. Hope this helps. Cheers, Jose From alan.gauld at btinternet.com Fri Jun 11 16:58:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Jun 2010 15:58:19 +0100 Subject: [Tutor] Looking for duplicates within a list References: <4C1240CE.7050807@insightbb.com> Message-ID: "Ken G." wrote > In any event, if a number is listed more than once, I would like to > know how many times, such as 2 or 3 times. For example, '3' is > listed twice within a list. Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) > 1) Seems to work... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From beachkid at insightbb.com Fri Jun 11 17:16:38 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 11:16:38 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: References: <4C1240CE.7050807@insightbb.com> Message-ID: <4C125356.5030708@insightbb.com> Sander Sweers wrote: > On 11 June 2010 15:57, Ken G. wrote: > >> In any event, if a number is listed more than once, I would like to know how >> many times, such as 2 or 3 times. For example, '3' is listed twice within a >> list. >> > > If you do not have top keep the order of the number this will work. > > >>>> a = [1, 2, 3, 3, 4] >>>> counted = {} >>>> for n in a: >>>> > if not n in counted: > counted[n] = 1 > else: > counted[n] += 1 > > >>>> counted >>>> > {1: 1, 2: 1, 3: 2, 4: 1} > > >>>> for x, y in counted.items(): >>>> > if y > 1: > print "Number %s was found %s times" % (x, y) > else: > print "Number %s was found %s time" % (x, y) > > Number 1 was found 1 time > Number 2 was found 1 time > Number 3 was found 2 times > Number 4 was found 1 time > > Greets > Sander > That works great! Thanks! Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Fri Jun 11 17:17:57 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 11:17:57 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: <201006111549.22751.ljmamoreira@gmail.com> References: <4C1240CE.7050807@insightbb.com> <201006111549.22751.ljmamoreira@gmail.com> Message-ID: <4C1253A5.7000304@insightbb.com> Jose Amoreira wrote: > On Friday, June 11, 2010 02:57:34 pm Ken G. wrote: > >> I have been working on this problem for several days and I am not making >> any progress. I have a group of 18 number, in ascending order, within a >> list. They ranged from 1 to 39. Some numbers are duplicated as much as >> three times or as few as none. >> >> I started with one list containing the numbers. For example, they are >> listed as like below: >> >> a = [1, 2, 3, 3, 4] >> >> I started off with using a loop: >> >> for j in range (0, 5): >> x = a[0] # for example, 1 >> >> How would I compare '1' with 2, 3, 3, 4? >> >> Do I need another duplicated list such as b = a and compare a[0] with >> either b[0], b[1], b[2], b[3], b[4]? >> >> Or do I compare a[0] with a[1], a[2], a[3], a[4]? >> >> In any event, if a number is listed more than once, I would like to know >> how many times, such as 2 or 3 times. For example, '3' is listed twice >> within a list. >> >> TIA, >> >> > > I would do it with a dictionary: > def reps(lst): > dict = {} > for item in lst: > if item in dict: > dict[item] += 1 > else: > dict[item] = 1 > return dict > > This function returns a dictionary with of the number of times each value in > the list is repeated. Even shorter using dict.setdefault: > > def reps(lst): > dict={} > for item in lst: > dict[item] = dict.setdefault(item,0) + 1 > return dict > > For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns > {1: 1, 2: 3, 4: 2, 5: 1} > > Using the fact that the list is ordered, one can design a more efficient > solution (go through the list; if this item is equal to the previous, then it > is repeated, else, it is a new value). But you list is short enough for this > direct approach to work. > Hope this helps. Cheers, > Jose > > Thanks. I will be studying your approach. Thanks all. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Fri Jun 11 17:19:17 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 11:19:17 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: References: <4C1240CE.7050807@insightbb.com> Message-ID: <4C1253F5.2090300@insightbb.com> Alan Gauld wrote: > > "Ken G." wrote > >> In any event, if a number is listed more than once, I would like to >> know how many times, such as 2 or 3 times. For example, '3' is >> listed twice within a list. > > Have you looked at the count method of lists? > > Something like: > > counts = set(( item, mylist.count(item)) for item in mylist if > mylist.count(item) > 1) > > Seems to work... > > HTH, > > Whee, this is great! I learned a lot today. Back to playing and studying. Ken From davea at ieee.org Fri Jun 11 17:37:31 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 11 Jun 2010 11:37:31 -0400 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: <4C12583B.5050707@ieee.org> Ken G. wrote: > I have been working on this problem for several days and I am not > making any progress. I have a group of 18 number, in ascending order, > within a list. They ranged from 1 to 39. Some numbers are duplicated > as much as three times or as few as none. > > I started with one list containing the numbers. For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > > for j in range (0, 5): > x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? > > In any event, if a number is listed more than once, I would like to > know how many times, such as 2 or 3 times. For example, '3' is listed > twice within a list. > > TIA, > > Ken > I'm a bit surprised nobody has mentioned the obvious solution -- another list of size 40, each of which represents the number of times a particular number has appeared. (Untested) a = [1, 2, 3, 3, 4] counts = [0] * 40 for item in a: counts[item] += 1 Now, if you want to know how many times 3 appears, simply print counts[3] The only downside to this is if the range of possible values is large, or non-numeric. In either of those cases, go back to the default dictionary. DaveA From steve at pearwood.info Fri Jun 11 17:49:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jun 2010 01:49:54 +1000 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: References: <4C1240CE.7050807@insightbb.com> Message-ID: <201006120149.55173.steve@pearwood.info> On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: > Have you looked at the count method of lists? > > Something like: > > counts = set(( item, mylist.count(item)) for item in mylist if > mylist.count(item) > 1) That's a Shlemiel the Painter algorithm. http://www.joelonsoftware.com/articles/fog0000000319.html > Seems to work... You say that now, but one day you will use it on a list of 100,000 items, and you'll wonder why it takes 45 minutes to finish, and curse Python for being slow. -- Steven D'Aprano From beachkid at insightbb.com Fri Jun 11 18:08:02 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 12:08:02 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: <4C12583B.5050707@ieee.org> References: <4C1240CE.7050807@insightbb.com> <4C12583B.5050707@ieee.org> Message-ID: <4C125F62.50706@insightbb.com> Dave Angel wrote: > Ken G. wrote: >> I have been working on this problem for several days and I am not >> making any progress. I have a group of 18 number, in ascending >> order, within a list. They ranged from 1 to 39. Some numbers are >> duplicated as much as three times or as few as none. >> >> I started with one list containing the numbers. For example, they >> are listed as like below: >> >> a = [1, 2, 3, 3, 4] >> >> I started off with using a loop: >> >> for j in range (0, 5): >> x = a[0] # for example, 1 >> >> How would I compare '1' with 2, 3, 3, 4? >> Do I need another duplicated list such as b = a and compare a[0] with >> either b[0], b[1], b[2], b[3], b[4]? >> >> Or do I compare a[0] with a[1], a[2], a[3], a[4]? >> >> In any event, if a number is listed more than once, I would like to >> know how many times, such as 2 or 3 times. For example, '3' is >> listed twice within a list. >> >> TIA, >> >> Ken >> > I'm a bit surprised nobody has mentioned the obvious solution -- > another list of size 40, each of which represents the number of times > a particular number has appeared. > > (Untested) > > > a = [1, 2, 3, 3, 4] > counts = [0] * 40 > for item in a: > counts[item] += 1 > > Now, if you want to know how many times 3 appears, simply > print counts[3] > > The only downside to this is if the range of possible values is large, > or non-numeric. In either of those cases, go back to the default > dictionary. > > DaveA > > > This will be look into. Mucho thanks. Ken From beachkid at insightbb.com Fri Jun 11 18:09:09 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 12:09:09 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: <201006120149.55173.steve@pearwood.info> References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> Message-ID: <4C125FA5.8000403@insightbb.com> Steven D'Aprano wrote: > On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: > > >> Have you looked at the count method of lists? >> >> Something like: >> >> counts = set(( item, mylist.count(item)) for item in mylist if >> mylist.count(item) > 1) >> > > That's a Shlemiel the Painter algorithm. > > http://www.joelonsoftware.com/articles/fog0000000319.html > > > >> Seems to work... >> > > You say that now, but one day you will use it on a list of 100,000 > items, and you'll wonder why it takes 45 minutes to finish, and curse > Python for being slow. > Hee, hee. Will investigate further. Thanks. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Jun 11 18:18:52 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 11 Jun 2010 18:18:52 +0200 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <201006120149.55173.steve@pearwood.info> References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> Message-ID: <2114901386686547039@unknownmsgid> On 11 jun 2010, at 17:49, Steven D'Aprano wrote: > On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: > >> Have you looked at the count method of lists? >> >> Something like: >> >> counts = set(( item, mylist.count(item)) for item in mylist if >> mylist.count(item) > 1) > > That's a Shlemiel the Painter algorithm. > > http://www.joelonsoftware.com/articles/fog0000000319.html > It is, but it's also very elegant and simple to understand. And it works fine on small inputs. Everything is fast for small n. > >> Seems to work... > > You say that now, but one day you will use it on a list of 100,000 > items, and you'll wonder why it takes 45 minutes to finish, and curse > Python for being slow. > Actually, now that you know it is a shlemiel the painter's algorithm, you won't have to wonder anymore. And you'll just say: "well, this piece of code might need to handle huge lists someday, I'll use a dictionary." I guess what I'm trying to say is: using code that performs bad in situations that won't be encountered anyway is not inherently bad. Otherwise, we'd all still be writing everything in C. The corrolary, of course, is that you should always know what the performance characteristics of your code are, and what kind of data it will handle. Hugo From davidheiserca at gmail.com Fri Jun 11 18:22:55 2010 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Fri, 11 Jun 2010 09:22:55 -0700 Subject: [Tutor] Looking for duplicates within a list [SOLVED] References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> <4C125FA5.8000403@insightbb.com> Message-ID: How about this? List = [1, 2, 3, 3, 3, 4, 5, 5] for Item in list(set(List)): print Item, List.count(Item) ----- Original Message ----- From: Ken G. To: Steven D'Aprano Cc: tutor at python.org Sent: Friday, June 11, 2010 9:09 AM Subject: Re: [Tutor] Looking for duplicates within a list [SOLVED] Steven D'Aprano wrote: On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) > 1) That's a Shlemiel the Painter algorithm. http://www.joelonsoftware.com/articles/fog0000000319.html Seems to work... You say that now, but one day you will use it on a list of 100,000 items, and you'll wonder why it takes 45 minutes to finish, and curse Python for being slow. Hee, hee. Will investigate further. Thanks. Ken ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 11 19:28:30 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jun 2010 03:28:30 +1000 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <2114901386686547039@unknownmsgid> References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> <2114901386686547039@unknownmsgid> Message-ID: <201006120328.31344.steve@pearwood.info> On Sat, 12 Jun 2010 02:18:52 am Hugo Arts wrote: > On 11 jun 2010, at 17:49, Steven D'Aprano wrote: > > On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: > >> Have you looked at the count method of lists? > >> > >> Something like: > >> > >> counts = set(( item, mylist.count(item)) for item in mylist if > >> mylist.count(item) > 1) > > > > That's a Shlemiel the Painter algorithm. > > > > http://www.joelonsoftware.com/articles/fog0000000319.html > > It is, but it's also very elegant and simple to understand. Your idea of elegant and simple is not the same as mine. To me, I see unnecessary work and unneeded complexity. A generator expression for a beginner having trouble with the basics? Calling mylist.count(item) *twice* for every item?! How is that possibly elegant? > And it > works fine on small inputs. Everything is fast for small n. [pedantic] Not everything. Some things are inherently slow, for example: http://en.wikipedia.org/wiki/Busy_beaver A five-state Busy Beaver machine takes 47,176,870 steps to return, and a six-state Busy Beaver takes 10**21132 steps to return. A slightly less extreme example is Ackermann's Function: http://en.wikipedia.org/wiki/Ackermann's_function where (for example) A(4,2) has over 19,000 digits. Calculating the number of recursive steps needed to calculate that value is left as an exercise. [/pedantic] These are extreme examples, but the point is that there are tasks which are hard even for small N. "Find N needles in a haystack" remains hard even for N=1. (And before you suggest using a magnet, it's a *plastic* needle.) [...] > I guess what I'm trying to say is: using code that performs bad in > situations that won't be encountered anyway is not inherently bad. The problem is that situations that won't be encountered often *are* encountered, long after the coder who introduced the poorly-performing algorithm has moved on. Here's a real-life example, from Python itself: last September, on the Python-Dev mailing list, Chris Withers reported a problem downloading a file using Python's httplib module. For a file that took wget or Internet Explorer approximately 2 seconds to download, it took Python up to thirty MINUTES -- that's nearly a thousand times slower. Eventually Chris, with the help of others on the list, debugged the problem down to a Shlemiel algorithm in the httplib code. Somebody found a comment in the _read_chunked method that said: ? # XXX This accumulates chunks by repeated string concatenation, ? # which is not efficient as the number or size of chunks gets big. So somebody used an algorithm which they KNEW was inefficient and slow, it had been there for years, affecting who knows how many people, until eventually somebody was annoyed sufficiently to do something about it. And the sad thing is that avoiding repeated string concatenation is easy and there was no need for it in the first place. > Otherwise, we'd all still be writing everything in C. You've missed the point. It's not the language, you can write poorly performing code in any language, and an O(N) algorithm in a slow language will probably out-perform an O(N**2) or O(2**N) algorithm in a fast language. -- Steven D'Aprano From steve at pearwood.info Fri Jun 11 19:37:05 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jun 2010 03:37:05 +1000 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: <201006120337.05963.steve@pearwood.info> On Fri, 11 Jun 2010 11:57:34 pm Ken G. wrote: > I have been working on this problem for several days and I am not > making any progress. I have a group of 18 number, in ascending > order, within a list. They ranged from 1 to 39. Some numbers are > duplicated as much as three times or as few as none. To find out how many times each number is in the list: counts = {} for i in mylist: # Don't do the work if you've already done it. if i not in counts: counts[i] = mylist.count(i) Can we do better? For very small lists, probably not, because the count() method is implemented in fast C, and anything we write will be in slow-ish Python. But for larger lists, count() is wasteful, because every time you call it, it walks the entire length of the string from start to finish. Since we know the list is sorted, that's a rubbish strategy. Let's write a quick helper function: # Untested def count_equals(alist, start): """Count the number of consecutive items of alist equal to the item at start. Returns the count and the next place to start.""" item = alist[start] count = 1 for i in xrange(start+1, len(alist)): x = alist[i] if x == item: count += 1 else: return (count, i) return (count, len(alist)) Now, with this we can avoid wastefully starting from the beginning of the list each time. (But remember, this will only be worthwhile for sufficiently large lists. My guess, and this is only a guess, is that it won't be worthwhile for lists smaller than perhaps 1,000 items.) counts = {} i = 0 while i < len(mylist): count, i = count_equals(mylist, i) counts[i] = count > I started with one list containing the numbers. For example, they > are listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > > for j in range (0, 5): > x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? # Untested counts = {} for j in range(len(a)): x = a[j] count = 1 for k in range(j+1, len(a)): if x == a[k]: count += 1 else: counts[x] = count break > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? b = a doesn't create a duplicated list, it gives the same list a second name. Watch this: >>> a = [1, 2, 3] >>> b = a >>> b.append("Surprise!") >>> a [1, 2, 3, 'Surprise!'] b and a both refer to the same object, the list [1,2,3,'Surprise!']. To make a copy of the list, you need: b = a[:] But why bother, if all you're doing is comparisons and not modifying it? -- Steven D'Aprano From alan.gauld at btinternet.com Fri Jun 11 19:48:29 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 11 Jun 2010 10:48:29 -0700 (PDT) Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: <4C1253F5.2090300@insightbb.com> References: <4C1240CE.7050807@insightbb.com> <4C1253F5.2090300@insightbb.com> Message-ID: <463.83642.qm@web86706.mail.ird.yahoo.com> > > counts = > > set(( item, mylist.count(item)) for item in mylist if mylist.count(item) > > Whee, this is great! I learned a lot today. I should have added that although thats a one liner in code terms it does involve iterating over the list twice - in count() - for each element. So it might not be very fast for big lists, certainly there are more efficient solutions if you don't mind writing more code. But for most lists you will likely find it is fast enough, certainly for 18 items! Alan G. From beachkid at insightbb.com Fri Jun 11 19:52:16 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 13:52:16 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: <2114901386686547039@unknownmsgid> References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> <2114901386686547039@unknownmsgid> Message-ID: <4C1277D0.3000906@insightbb.com> Hugo Arts wrote: > On 11 jun 2010, at 17:49, Steven D'Aprano wrote: > > >> On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: >> >> >>> Have you looked at the count method of lists? >>> >>> Something like: >>> >>> counts = set(( item, mylist.count(item)) for item in mylist if >>> mylist.count(item) > 1) >>> >> That's a Shlemiel the Painter algorithm. >> >> http://www.joelonsoftware.com/articles/fog0000000319.html >> >> > > It is, but it's also very elegant and simple to understand. And it > works fine on small inputs. Everything is fast for small n. > > >>> Seems to work... >>> >> You say that now, but one day you will use it on a list of 100,000 >> items, and you'll wonder why it takes 45 minutes to finish, and curse >> Python for being slow. >> >> > > Actually, now that you know it is a shlemiel the painter's algorithm, > you won't have to wonder anymore. And you'll just say: "well, this > piece of code might need to handle huge lists someday, I'll use a > dictionary." > > I guess what I'm trying to say is: using code that performs bad in > situations that won't be encountered anyway is not inherently bad. > Otherwise, we'd all still be writing everything in C. > > The corrolary, of course, is that you should always know what the > performance characteristics of your code are, and what kind of data it > will handle. > > Hugo > > I appreciate your input. Thanks! Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Fri Jun 11 19:53:54 2010 From: beachkid at insightbb.com (Ken G.) Date: Fri, 11 Jun 2010 13:53:54 -0400 Subject: [Tutor] Looking for duplicates within a list [SOLVED] In-Reply-To: References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> <4C125FA5.8000403@insightbb.com> Message-ID: <4C127832.1010705@insightbb.com> davidheiserca at gmail.com wrote: > How about this? > > List = [1, 2, 3, 3, 3, 4, 5, 5] > for Item in list(set(List)): > print Item, List.count(Item) > > > > ----- Original Message ----- > *From:* Ken G. > *To:* Steven D'Aprano > *Cc:* tutor at python.org > *Sent:* Friday, June 11, 2010 9:09 AM > *Subject:* Re: [Tutor] Looking for duplicates within a list [SOLVED] > > > Steven D'Aprano wrote: >> On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: >> >> >>> Have you looked at the count method of lists? >>> >>> Something like: >>> >>> counts = set(( item, mylist.count(item)) for item in mylist if >>> mylist.count(item) > 1) >>> >> >> That's a Shlemiel the Painter algorithm. >> >> http://www.joelonsoftware.com/articles/fog0000000319.html >> >> >> >>> Seems to work... >>> >> >> You say that now, but one day you will use it on a list of 100,000 >> items, and you'll wonder why it takes 45 minutes to finish, and curse >> Python for being slow. >> > Hee, hee. Will investigate further. Thanks. > > Ken > > > ------------------------------------------------------------------------ > ___ > Oh, a nice one. Many thanks. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 11 20:19:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Jun 2010 19:19:52 +0100 Subject: [Tutor] Looking for duplicates within a list [SOLVED] References: <4C1240CE.7050807@insightbb.com><201006120149.55173.steve@pearwood.info><4C125FA5.8000403@insightbb.com> Message-ID: wrote > How about this? > > List = [1, 2, 3, 3, 3, 4, 5, 5] > for Item in list(set(List)): > print Item, List.count(Item) Not bad and you don't need the convert back to list() But it doesn't filter out those items which are unique which the OP asked for. So I guess it becomes for item in set(List): n = List.count(item) if n > 1: print item, n which is still pretty clear. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From knacktus at googlemail.com Fri Jun 11 21:42:35 2010 From: knacktus at googlemail.com (Knacktus) Date: Fri, 11 Jun 2010 21:42:35 +0200 Subject: [Tutor] What's the catch with ZopeDB? Message-ID: <4C1291AB.40804@googlemail.com> Hey everyone, I'm planning to create small application which manages product data e.g. parts of cars. There are quite some relations, e.g. - a car consists of certain assemblies, - an assembly consists of certatin parts, - a part has serveral documents which describe the part, e.g. a CAD document or material data. So, one could think of storing the data in a relational database. But now I start to think ... ;-): - I would just need some predefined queries which would be performed by Python code, of course. Maybe using an ORM. - Therefore, I don't think I need all the power and flexibility of SQL. - I will work with Python objects. Why should I translate to an relational schema "just" for persistence? - Performancewise, caching is probably much more sensitive than pure database performance. (That my guess...) To me, ZopeDB (a object database for Python) looks like an awesomely easy solution. I could save some brain power for the innovative part or drink more beer watching the soccer world cup. At the same moment, I wonder why anyone in the python world would go through the hassle of using relational databases unless forced. So, has anyone experience with ZopeDB? Are there some drawbacks I should be aware of before getting a book and dive in? (It sounds too good ;-)) Cheers, Jan From hugo.yoshi at gmail.com Fri Jun 11 21:59:45 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 11 Jun 2010 21:59:45 +0200 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <201006120328.31344.steve@pearwood.info> References: <4C1240CE.7050807@insightbb.com> <201006120149.55173.steve@pearwood.info> <2114901386686547039@unknownmsgid> <201006120328.31344.steve@pearwood.info> Message-ID: I really shouldn't, but I'll bite just this once. On Fri, Jun 11, 2010 at 7:28 PM, Steven D'Aprano wrote: > > Your idea of elegant and simple is not the same as mine. To me, I see > unnecessary work and unneeded complexity. A generator expression for a > beginner having trouble with the basics? Calling mylist.count(item) > *twice* for every item?! How is that possibly elegant? > What I mean by simple is that that line of code is the most obvious and direct translation of "a list of every item and how often it appears, for every item that appears more than once." I call it elegant because the code is even shorter than that English description while remaining readable, possibly even to someone with little programming experience. I'm making a judgement based on readability, not performance. Code that goes for performance in lieu of readability I'd call "clever," and that's not a compliment. Yes, it's an opinion. You disagree. That's fine. > [pedantic] > Not everything. Some things are inherently slow, for example: > > http://en.wikipedia.org/wiki/Busy_beaver > > A five-state Busy Beaver machine takes 47,176,870 steps to return, and a > six-state Busy Beaver takes 10**21132 steps to return. > > A slightly less extreme example is Ackermann's Function: > > http://en.wikipedia.org/wiki/Ackermann's_function > > where (for example) A(4,2) has over 19,000 digits. Calculating the > number of recursive steps needed to calculate that value is left as an > exercise. > [/pedantic] > > These are extreme examples, but the point is that there are tasks which > are hard even for small N. "Find N needles in a haystack" remains hard > even for N=1. > Now you're just arguing for the sake of being right (points for marking it [pedantic], I suppose). The busy beaver and Ackermann function have no bearing on this discussion whatsoever. If we're going to argue pedantically, the 1-state busy beaver (n=1) finishes in one step, and A(1,0) = A(0, 1) = 2. Even those are fast for small n, they just grow ridiculously quickly. Also, (pedantically), the problem "find needles in a haystack" grows in the size of the haystack, not the amount of needles. So the more appropriate n=1 version would be a haystack of size 1 with a needle in it. Which is quite easy. > (And before you suggest using a magnet, it's a *plastic* needle.) That solution is not in the spirit of the problem, and since I know that, I wouldn't bring it up. > > The problem is that situations that won't be encountered often *are* > encountered, long after the coder who introduced the poorly-performing > algorithm has moved on. > > Here's a real-life example, from Python itself: last September, on the > Python-Dev mailing list, Chris Withers reported a problem downloading a > file using Python's httplib module. For a file that took wget or > Internet Explorer approximately 2 seconds to download, it took Python > up to thirty MINUTES -- that's nearly a thousand times slower. > > Eventually Chris, with the help of others on the list, debugged the > problem down to a Shlemiel algorithm in the httplib code. Somebody > found a comment in the _read_chunked method that said: > > ? # XXX This accumulates chunks by repeated string concatenation, > ? # which is not efficient as the number or size of chunks gets big. > > So somebody used an algorithm which they KNEW was inefficient and slow, > it had been there for years, affecting who knows how many people, until > eventually somebody was annoyed sufficiently to do something about it. > And the sad thing is that avoiding repeated string concatenation is > easy and there was no need for it in the first place. > Estimating the size of your input is sometimes hard. That's a valid point. OTOH, that line of code takes maybe 10 seconds to write, and after profiling reveals it to be slow (you *are* profiling your code, right?) you can easily replace it with something more appropriate. Or your successor can, since he'll have no problem figuring out what it does. > > You've missed the point. It's not the language, you can write poorly > performing code in any language, and an O(N) algorithm in a slow > language will probably out-perform an O(N**2) or O(2**N) algorithm in a > fast language. > That wasn't the point I was trying to make. My point was that speed is not always the primary concern, and if it is, you shouldn't be writing code in python anyway, since it is always possible to write a program in C that performs better. Alan's code makes a trade-off between performance and readability. I'd call it the easiest to read solution so far. That's a trade-off that may or may not be appropriate. My point is that you shouldn't dismiss the code just because the algorithm sucks. You should only dismiss it because the algorithm sucks *and* your code will have to handle large inputs. Hugo From emile at fenx.com Fri Jun 11 22:07:47 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 11 Jun 2010 13:07:47 -0700 Subject: [Tutor] What's the catch with ZopeDB? In-Reply-To: <4C1291AB.40804@googlemail.com> References: <4C1291AB.40804@googlemail.com> Message-ID: On 6/11/2010 12:42 PM Knacktus said... > So, has anyone experience with ZopeDB? Are there some drawbacks I should > be aware of before getting a book and dive in? (It sounds too good ;-)) > I've been using it as part of a couple applications I wrote 10 years ago that use zope. I'm not sure how my comments relate to non-zope usage or the recent versions so YMMV. The two things that bother me most are that without packing the database, it grows -- apparently without bound. It'll pack a 1Gb source DB down to 32Mb. Also, I once experienced corruption and found it impossible to recover the lost data, and I've a fair amount of experience recovering lost data even from unmountable partitions and drives that don't power up. I'm not opposed to the idea so I think I'd try it out, but those are issues I'd watch for. Emile From dkuhlman at rexx.com Sat Jun 12 00:10:43 2010 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 11 Jun 2010 15:10:43 -0700 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: <4C1240CE.7050807@insightbb.com> References: <4C1240CE.7050807@insightbb.com> Message-ID: <20100611221043.GA56775@cutter.rexx.com> On Fri, Jun 11, 2010 at 09:57:34AM -0400, Ken G. wrote: > > > for j in range (0, 5): > x = a[0] # for example, 1 One picky, little point. I've seen several solutions in this thread that included something like the following: for i in range(len(mylist)): val = mylist[i] mylist[i] = f(val) o o o That works fine, but ... You can do this a bit more easily by using the "enumerate" built-in function. It provides that index. Example: for i, val in enumerate(mylist): mylist[i] = f(val) o o o See http://docs.python.org/library/functions.html#enumerate - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Sat Jun 12 00:27:44 2010 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 11 Jun 2010 15:27:44 -0700 Subject: [Tutor] What's the catch with ZopeDB? In-Reply-To: <4C1291AB.40804@googlemail.com> References: <4C1291AB.40804@googlemail.com> Message-ID: <20100611222744.GB56775@cutter.rexx.com> On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote: > > To me, ZopeDB (a object database for Python) looks like an awesomely > easy solution. I could save some brain power for the innovative part or > drink more beer watching the soccer world cup. At the same moment, I > wonder why anyone in the python world would go through the hassle of > using relational databases unless forced. > > So, has anyone experience with ZopeDB? Are there some drawbacks I should > be aware of before getting a book and dive in? (It sounds too good ;-)) > Jan - If you are evaluating alternative solutions, you might also look into Django models. There have been some very positive comments about Django on this list. And, Django models can be used outside of the Django Web applications. Also, Django models are reasonably object oriented. A Django model/DB can sit on top of several different relational database engines, for example, PostgreSQL, MySQL, sqlite3, etc. See: http://docs.djangoproject.com/en/1.2/#the-model-layer http://www.djangobook.com/en/2.0/chapter05/ - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From eldonjr at hotmail.com Sat Jun 12 03:13:31 2010 From: eldonjr at hotmail.com (Eldon Londe Mello Junior) Date: Fri, 11 Jun 2010 22:13:31 -0300 Subject: [Tutor] Python a substitute/alternative for PhP? In-Reply-To: <20100611222744.GB56775@cutter.rexx.com> References: <4C1291AB.40804@googlemail.com>, <20100611222744.GB56775@cutter.rexx.com> Message-ID: Hi there, If you care to listen to my story and fully help me out, just keep on reading }else{ move to the final question :) I'm just finishing an introductory course on PhP and MySQL (HTML, CSS and Javascript basics included). That's a typical first step to novice programmers in Brazil. However, I've been reading a lot about programming languages and stuff in order to make the best choice as I don't want to spend much time learning unnecessary things I won't need in the future. Thus, I decided I want to be a contributor for the GNU/LINUX community and, of course, become sort of an opensource-solutions professional programmer. And if I got it right, python would the most adequate language for me to reach my goals. Only a few programmers in Brazil are familiar with python though. As I said before, most beginners start with PhP and stick with it or go for JAVA or MS proprietary languages. Actually, you can only learn python on your own around here as no college or private institutes offer python courses. As you may see it coming, the big question for me is: should I stick with PHP as most people here (those fond of free software) or Python is or would be a better choice for me? FINAL QUESTION> Is Python a substitute for PHP? I mean, can I start learning python by trying to do the things I've learned with PHP? Are they different anyhow or they actually compete against each other? Thanks in advance, advice on which steps to take to reach my career goals would be very appreciated as well! Eldon. > Date: Fri, 11 Jun 2010 15:27:44 -0700 > From: dkuhlman at rexx.com > To: Tutor at python.org > Subject: Re: [Tutor] What's the catch with ZopeDB? > > On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote: > > > > > To me, ZopeDB (a object database for Python) looks like an awesomely > > easy solution. I could save some brain power for the innovative part or > > drink more beer watching the soccer world cup. At the same moment, I > > wonder why anyone in the python world would go through the hassle of > > using relational databases unless forced. > > > > So, has anyone experience with ZopeDB? Are there some drawbacks I should > > be aware of before getting a book and dive in? (It sounds too good ;-)) > > > > Jan - > > If you are evaluating alternative solutions, you might also look > into Django models. There have been some very positive comments > about Django on this list. And, Django models can be used outside > of the Django Web applications. Also, Django models are reasonably > object oriented. A Django model/DB can sit on top of several > different relational database engines, for example, PostgreSQL, MySQL, > sqlite3, etc. > > See: > > http://docs.djangoproject.com/en/1.2/#the-model-layer > http://www.djangobook.com/en/2.0/chapter05/ > > - Dave > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Jun 12 03:33:46 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 11 Jun 2010 21:33:46 -0400 Subject: [Tutor] Python a substitute/alternative for PhP? In-Reply-To: References: <4C1291AB.40804@googlemail.com> <20100611222744.GB56775@cutter.rexx.com> Message-ID: Personally, I would learn Python. My college does not offer Python either, so I had to learn what I know on my own(of course, by that I mean constantly pestering this and other of the amazing Python email lists). PHP is fine in itself, but, after using it, Java, and intros to a few other languages, nothing has been able to beat Python's ease of use, massive extensibility (there is a package to let you do just about anything you want), and support community. It is a great language and, especially if you plan to stick with desktop applications, I think it is much easier than a language like C++ or Java. Your life will be even easier than mine since you are going to be on Linux; I believe most Linux distros come with Python, while Windows does not, so what you make can be distributed as scripts while I have to use a program like py2exe and package the entire Python interpreter. Anyway, just my thoughts. Note that I am still in college for my computer science degree and am in no way a professional programmer, just someone who has waded in several languages and found Python to be the only one worth diving into all the way. On 6/11/10, Eldon Londe Mello Junior wrote: > > Hi there, > > If you care to listen to my story and fully help me out, just keep on > reading }else{ move to the final question :) > > I'm just finishing an introductory course on PhP and MySQL (HTML, CSS and > Javascript basics included). That's a typical first step to novice > programmers in Brazil. > > However, I've been reading a lot about programming languages and stuff in > order to make the best choice as I don't want to spend much time learning > unnecessary things I won't need in the future. > > Thus, I decided I want to be a contributor for the GNU/LINUX community and, > of course, become sort of an opensource-solutions professional programmer. > And if I got it right, python would the most adequate language for me to > reach my goals. > > Only a few programmers in Brazil are familiar with python though. As I said > before, most beginners start with PhP and stick with it or go for JAVA or MS > proprietary languages. Actually, you can only learn python on your own > around here as no college or private institutes offer python courses. > > As you may see it coming, the big question for me is: should I stick with > PHP as most people here (those fond of free software) or Python is or would > be a better choice for me? > > FINAL QUESTION> Is Python a substitute for PHP? I mean, can I start learning > python by trying to do the things I've learned with PHP? Are they different > anyhow or they actually compete against each other? > > Thanks in advance, advice on which steps to take to reach my career goals > would be very appreciated as well! > > Eldon. > > > > > >> Date: Fri, 11 Jun 2010 15:27:44 -0700 >> From: dkuhlman at rexx.com >> To: Tutor at python.org >> Subject: Re: [Tutor] What's the catch with ZopeDB? >> >> On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote: >> >> > >> > To me, ZopeDB (a object database for Python) looks like an awesomely >> > easy solution. I could save some brain power for the innovative part or >> > drink more beer watching the soccer world cup. At the same moment, I >> > wonder why anyone in the python world would go through the hassle of >> > using relational databases unless forced. >> > >> > So, has anyone experience with ZopeDB? Are there some drawbacks I should >> > >> > be aware of before getting a book and dive in? (It sounds too good ;-)) >> > >> >> Jan - >> >> If you are evaluating alternative solutions, you might also look >> into Django models. There have been some very positive comments >> about Django on this list. And, Django models can be used outside >> of the Django Web applications. Also, Django models are reasonably >> object oriented. A Django model/DB can sit on top of several >> different relational database engines, for example, PostgreSQL, MySQL, >> sqlite3, etc. >> >> See: >> >> http://docs.djangoproject.com/en/1.2/#the-model-layer >> http://www.djangobook.com/en/2.0/chapter05/ >> >> - Dave >> >> -- >> Dave Kuhlman >> http://www.rexx.com/~dkuhlman >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _________________________________________________________________ > Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. > https://signup.live.com/signup.aspx?id=60969 -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Jun 12 04:38:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jun 2010 12:38:54 +1000 Subject: [Tutor] Looking for duplicates within a list In-Reply-To: References: <4C1240CE.7050807@insightbb.com> <201006120328.31344.steve@pearwood.info> Message-ID: <201006121238.55555.steve@pearwood.info> On Sat, 12 Jun 2010 05:59:45 am Hugo Arts wrote: [...] Putting aside all the theoretical arguments, and getting to an actual, real-life example: > > So somebody used an algorithm which they KNEW was inefficient and > > slow, it had been there for years, affecting who knows how many > > people, until eventually somebody was annoyed sufficiently to do > > something about it. And the sad thing is that avoiding repeated > > string concatenation is easy and there was no need for it in the > > first place. > > Estimating the size of your input is sometimes hard. That's a valid > point. OTOH, that line of code takes maybe 10 seconds to write, and > after profiling reveals it to be slow (you *are* profiling your code, > right?) you can easily replace it with something more appropriate. Or > your successor can, since he'll have no problem figuring out what it > does. I beg to differ. The incident with httplib is actual, real-life evidence that your caviler attitude towards poor algorithms is bad advice. You wave your hands and say "Oh well, it doesn't matter, because somebody will find the slowdown and easily fix it". But in real life, it isn't that simple, not even in Open Source software let alone proprietary software where you might not have access to the source and the vendor might not care. (Has Microsoft yet fixed the ridiculously slow behaviour of the Trash Can when it has thousands of items in it?) I was mistaken when I said Chris Withers reported this performance bug in September. He actually first raised it with the Python-Dev team in early August: http://mail.python.org/pipermail/python-dev/2009-August/thread.html#91125 http://mail.python.org/pipermail/python-dev/2009-September/thread.html#91584 So this took AT LEAST a month elapsed time, with multiple people contributing, at least two different bug reports involved (and possibly five), and who knows how many hours debugging to solve this. Once the issue was identified, the solution was trivial: http://svn.python.org/view/python/trunk/Lib/httplib.py?r1=74523&r2=74655 but it took a lot of effort to identify the issue. As Guido van Rossum himself said, this was an embarrassment. The fix was entirely trivial, and there was no good reason to write the Shlemiel algorithm in the first place, especially since the author apparently knew it was a Shlemiel algorithm. Perhaps he too thought it was "more elegant" and that somebody else would "easily" deal with the problems that it caused. The poorly-performing httplib code has been in at least three major releases of CPython (2.4 to 2.6) and possibly more, but apparently due to differences in realloc it only affected Windows users. So once you've run into the bug, your *second* problem is that other people say "It works for me, it must be your network". It is not true that "he'll have no problem figuring out what it does". In code of any complexity, you can run into multiple problems and wild-goose-chases. This is a good example. Read the thread and see how many different ideas people had: they blamed the proxy, they blamed a pre-existing bug in sockets, they blamed buffer sizes. Nobody publicly blamed "third-party drivers", but I bet you somebody was thinking it. I think you have a very rosy view of how easy it is to debug performance issues. Debugging is hard. Debugging performance problems is ten times harder. Avoiding bad algorithms isn't premature optimization, it is thinking ahead. There's a fine line between them, I agree, but with the risks of hard-to-debug performance degradation caused by O(N**2) algorithms you should have a *seriously* compelling reason for using one, and not just because it's "good enough for small N" or "its a one-liner". On modern desktop or laptop hardware, I would expect small N to mean multiple hundreds or even thousands, not a dozen or two. This isn't 1985 when desktop computers couldn't count past 32768 and 1000 items was a lot. Today, large N is tens of millions. Huge is hundreds of millions, at which point I start worrying about paging into virtual memory more than the algorithm, because memory paging is an O(N**2) (or worse!) algorithm too. [...] > That wasn't the point I was trying to make. My point was that speed > is not always the primary concern, and if it is, you shouldn't be > writing code in python anyway, since it is always possible to write a > program in C that performs better. It is noteworthy the PyPy people use JIT compilation of Python code to beat the pants off CPython speed, and their audacious aim is to be *faster* than C, at least for some things. It is possible to write Python programs that run faster than the equivalent program written in optimized C. http://news.ycombinator.com/item?id=1379382 > Alan's code makes a trade-off between performance and readability. > I'd call it the easiest to read solution so far. Really? I think its readability is pretty poor, and nowhere near as clear as an explicit loop. Especially for a beginner who might not even know what a generator expression is. There's too much stuff in one line, making it hard to read. It does the same work multiple times instead of once. Instead of the one-liner: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) > 1) I think a two-liner is *far* clearer: counts = ((item, mylist.count(item)) for item in set(mylist)) counts = [t for t in counts if t[1] > 1] It's still has the awful O(N**2) performance, but it is nearly 25% faster (for N=18) by my tests, and is easier to read. And by some happy accident, it keeps the order of the original sorted list: >>> mylist = [1, 2, 2, 3, 3, 5, 6, 19, 21, 21, 23, ... 25, 25, 25, 26, 26, 31, 39] >>> counts = ((item, mylist.count(item)) for item in set(mylist)) >>> counts = [t for t in counts if t[1] > 1] >>> counts [(2, 2), (3, 2), (21, 2), (25, 3), (26, 2)] -- Steven D'Aprano From amartin7211 at gmail.com Sat Jun 12 06:50:26 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Sat, 12 Jun 2010 00:50:26 -0400 Subject: [Tutor] Problems with Importing into the Python Shell Message-ID: Hey, everyone, I am new to programming and just downloaded Python 2.6 onto my windows vista laptop. I am attempting to follow 4.11 of the tutorial called "How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation" ( http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I am having some trouble. First off, I do not understand how to import things into the python shell. I have a script I saved as chap03.py, but when I try to import it into the python shell i get an error like this: >>> from chap03 import * Traceback (most recent call last): File "", line 1, in from chap03 import * File "C:/Python26\chap03.py", line 2 print param param ^ SyntaxError: invalid syntax >>> The chap03.py file is a simple one that looks like this: def print_twice(param): print param param My second problem is that I need to install and import GASP in order to follow the tutorial. When I tried to do import it, I ran into an error like this: >>> from gasp import * Traceback (most recent call last): File "", line 1, in from gasp import * File "C:\Python26\lib\site-packages\gasp\__init__.py", line 1, in from api import * File "C:\Python26\lib\site-packages\gasp\api.py", line 1, in import backend File "C:\Python26\lib\site-packages\gasp\backend.py", line 7, in except ImportError: raise 'Pygame is not installed. Please install it.' TypeError: exceptions must be old-style classes or derived from BaseException, not str >>> Can anybody help me with this? Thanks a lot P.S. SORRY FOR THE LONG EMAIL -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Jun 12 09:39:09 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Jun 2010 08:39:09 +0100 Subject: [Tutor] Problems with Importing into the Python Shell In-Reply-To: References: Message-ID: On 12/06/2010 05:50, Andrew Martin wrote: > Hey, everyone, I am new to programming and just downloaded Python 2.6 onto > my windows vista laptop. I am attempting to follow 4.11 of the tutorial > called "How to Think Like a Computer Scientist: Learning with Python v2nd > Edition documentation" ( > http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I > am having some trouble. First off, I do not understand how to import things > into the python shell. I have a script I saved as chap03.py, but when I try > to import it into the python shell i get an error like this: > >>>> from chap03 import * This is generally considered bad practice, I'll let you do some research to find out why. :) > > Traceback (most recent call last): > File "", line 1, in > from chap03 import * > File "C:/Python26\chap03.py", line 2 > print param param > ^ > SyntaxError: invalid syntax >>>> > > The chap03.py file is a simple one that looks like this: > def print_twice(param): > print param param One of the great advantages of Python is trying things from an interactive prompt, so let's go. c:\Users\Mark\python>python Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def print_twice(param): ... print param param File "", line 2 print param param ^ SyntaxError: invalid syntax So it is! What's print_twice trying to do, let's guess? >>> def print_twice(param): ... print param, param ... >>> print_twice('Hi Andrew') Hi Andrew Hi Andrew >>> Better! See how I slotted that comma into the function print_twice, just hope my guess is right. So run up some editor/IDE and slap that comma in there, it should at least keep you going. > > My second problem is that I need to install and import GASP in order to > follow the tutorial. When I tried to do import it, I ran into an error like > this: >>>> from gasp import * > > Traceback (most recent call last): The line above basically says "start reading from the bottom up" > File "", line 1, in > from gasp import * > File "C:\Python26\lib\site-packages\gasp\__init__.py", line 1, in > from api import * > File "C:\Python26\lib\site-packages\gasp\api.py", line 1, in > import backend > File "C:\Python26\lib\site-packages\gasp\backend.py", line 7, in > except ImportError: raise 'Pygame is not installed. Please install it.' > TypeError: exceptions must be old-style classes or derived from > BaseException, not str The TypeError means exactly what it says. The ImportError is trying to raise an exception, but what follows is a string type, not an exception type. Just install Pygame to get yourself going, at some point in the tutorial you're bound to run into exception handling. >>>> > > Can anybody help me with this? > > Thanks a lot > > P.S. SORRY FOR THE LONG EMAIL By some standards this doesn't even qualify as short, it's just a snippet. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor HTH, and keep asking as Python lists are renowned for their friendlyness. Mark Lawrence. From steve at pearwood.info Sat Jun 12 10:33:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jun 2010 18:33:23 +1000 Subject: [Tutor] Problems with Importing into the Python Shell In-Reply-To: References: Message-ID: <201006121833.24205.steve@pearwood.info> On Sat, 12 Jun 2010 02:50:26 pm Andrew Martin wrote: > >>> from chap03 import * > > Traceback (most recent call last): > File "", line 1, in > from chap03 import * > File "C:/Python26\chap03.py", line 2 > print param param > ^ > SyntaxError: invalid syntax This tells you exactly what the error is: a syntax error in your module chap03, which prevents Python from importing it. `print a b` is not valid Python syntax. Python can't correct the error, because it doesn't know if you mean print param+param, or param,param or "param param" or something else, and it refuses to guess. > The chap03.py file is a simple one that looks like this: > def print_twice(param): > print param param The print statement takes a comma-separated list of things to print: print param, param > My second problem is that I need to install and import GASP in order > to follow the tutorial. When I tried to do import it, I ran into an > error like > > this: > >>> from gasp import * > > Traceback (most recent call last): > File "", line 1, in > from gasp import * > File "C:\Python26\lib\site-packages\gasp\__init__.py", line 1, in > from api import * > File "C:\Python26\lib\site-packages\gasp\api.py", line 1, in > import backend > File "C:\Python26\lib\site-packages\gasp\backend.py", line 7, in > except ImportError: raise 'Pygame is not installed. Please > install it.' TypeError: exceptions must be old-style classes or > derived from BaseException, not str Here you have two problems. The first problem is that you need to have Pygame installed, and you don't, or it is installed in such a place that Python 2.6 can't see it. The second is that the version of gasp you are using has a bug in it, possibly because you're using an old version. In the very early days of Python, it used string exceptions: to raise an error message, you would say: raise "this is an error message" For various reasons, this was not very satisfactory, and over the years these string exceptions were discouraged, then flagged as officially deprecated, then Python would print an warning message when you used them, and finally in Python 2.6 they because prohibited: >>> raise "this is an error" Traceback (most recent call last): File "", line 1, in TypeError: exceptions must be classes or instances, not str So the version of gasp you are using pre-dates Python 2.6, and contains obsolete code that does not run correctly. Your work-arounds, in order of best-to-worst ideas: (1) Install an updated version of gasp that works with Python 2.6; (2) Install Python 2.5 and use that; or (3) Hack your copy of gasp to fix the bug. Of course, since you're a beginner, option 3 (not very desirable at the best of times!) is virtually impossible. Good luck! However, there is one little ray of sunshine. If you install Pygame, gasp should successfully import it and therefore not try to raise a string exception, and the second error will disappear all on its own. (But who knows how many more little landmines are waiting...) -- Steven D'Aprano From advertising at robbstucky.net Fri Jun 11 23:12:27 2010 From: advertising at robbstucky.net (Advertising Department) Date: Fri, 11 Jun 2010 17:12:27 -0400 Subject: [Tutor] (no subject) Message-ID: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw """still thinking in imperative" """ ## obviously this is a bad construct. ## Can someone suggest a pythonesque way of doing this? def getid(): response = raw_input('prompt') if response not in [ "", "y", "Y", "yes"] : getid() # ouch print "continue working" # do more stuff # do more stuff getid() dosomething() getid() dosomethingelse() ## obviously this is a bad construct. ## Can someone give me a pythonesque way of doing this? From zubin.mithra at gmail.com Fri Jun 11 21:27:39 2010 From: zubin.mithra at gmail.com (Zubin Mithra) Date: Sat, 12 Jun 2010 00:57:39 +0530 Subject: [Tutor] lib2to3 fixers Message-ID: Hey everyone, I just discovered that the following construct does not work in Py3k. >>> string.maketrans('-', '_') However, the following works, >>> str.maketrans('-', '_') When i try to convert a python module containing the above construct, it does not get modified in a way such that it could run on Python 3.0 I`m trying to automate the conversion of making the module Py3k compatible and so I guess i`m left with two options. 1. replace string.maketrans() with a function which is compatible in both Python 2.x and 3.0 ; as of now I`m unaware of such a construct. 2. write a fixer for doing this which I could use. I could`nt find any good tutorials out there on writing fixers, i`d be grateful if you could point me to any. Thankx in advance, cheers zubin From rdmoores at gmail.com Sat Jun 12 10:50:21 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 12 Jun 2010 01:50:21 -0700 Subject: [Tutor] winsound.Beep(500,500) "Failed to beep" Message-ID: >>> import winsound >>> winsound.Beep(500,500) Traceback (most recent call last): File "", line 1, in RuntimeError: Failed to beep >>> Vista, Python 3.1 Any ideas? Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Sat Jun 12 11:20:01 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Sat, 12 Jun 2010 10:20:01 +0100 Subject: [Tutor] (no subject) In-Reply-To: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> Message-ID: <201006121020.01253.ljmamoreira@gmail.com> On Friday, June 11, 2010 10:12:27 pm Advertising Department wrote: > #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw > """still thinking in imperative" > """ > > ## obviously this is a bad construct. > ## Can someone suggest a pythonesque way of doing this? > > > def getid(): > response = raw_input('prompt') > if response not in [ "", "y", "Y", "yes"] : > getid() # ouch > print "continue working" > # do more stuff > # do more stuff > > > getid() > dosomething() > getid() > dosomethingelse() > > > ## obviously this is a bad construct. > ## Can someone give me a pythonesque way of doing this? > Using recursion for validation, that doesn't sound right. I would rather do it with a simple while cycle: response="any invalid string" while response not in ["","y","Y","yes"]: response = raw_input("prompt") Hope this helps Jos? From kaushalshriyan at gmail.com Sat Jun 12 11:37:12 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Sat, 12 Jun 2010 15:07:12 +0530 Subject: [Tutor] New to Programming Message-ID: Hi, I am absolutely new to programming language. Dont have any programming experience. Can some one guide me please. is python a good start for novice. Thanks, Kaushal From davea at ieee.org Sat Jun 12 12:34:31 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 12 Jun 2010 06:34:31 -0400 Subject: [Tutor] New to Programming In-Reply-To: References: Message-ID: <4C1362B7.6070702@ieee.org> Kaushal Shriyan wrote: > Hi, > > I am absolutely new to programming language. Dont have any programming > experience. Can some one guide me please. is python a good start for > novice. > > Thanks, > > Kaushal > > Like nearly all questions, the answer is "it depends." Mainly, it depends on what your goal is. In my case, I made my living with programming, for many years. And in the process, learned and used about 35 languages, plus a few more for fun. I wish I had discovered Python much earlier, though it couldn't have been my first, since it wasn't around. But it'd have been much better than Fortran was, for learning. So tell us about your goals. Abstract knowledge, console utilities, gui development, games, web development, networking communication, ... Next, you might want to evaluate what you already know. There are a lot of non-programming things that a programmer needs to understand. If you already know many of them, that's a big head start. If you already know how to administer a Linux system, you're already a programmer and didn't know it. If you write complex formulas for Excel, you're a programmer. If you already know modus ponens, and understand what a contrapositive is, you've got a head start towards logic (neither is a programming subject, just a start towards logical thinking). If you've worked on a large document, and kept backups of incremental versions, so you could rework the current version based on earlier ones, that's a plus. If you know why a file's timestamp might change when you copy it from hard disk to a USB drive and back again, you've got a head start. If you know why it might have a different timestamp when you look at it six months from now without changing it, you've got a head start. If you're using Windows and never used a command prompt, you have a ways to go. If you don't know what a file really is, or how directories are organized, you have a ways to go. And if you think a computer is intelligent, you have a long way to go. Python is a powerful tool. But if you're totally new to programming, it can also be daunting. And most people have no idea how easy some programs are, nor how hard some other programs are, to build. In any case, some of the things recommending Python as a first language are: 1) an interactive interpreter - you can experiment, trivially 2) very fast turnaround, from the time you make a change, till you can see how it works. This can be true even for large programs 3) this mailing list DaveA From sudipb at sudipb.com Sat Jun 12 12:34:44 2010 From: sudipb at sudipb.com (Sudip Bhattacharya) Date: Sat, 12 Jun 2010 16:04:44 +0530 Subject: [Tutor] Adding line numbers to a Python Script Message-ID: I quote this example (and the problem that I am facing trying to understand) from the book "Beginning Python - From Novice to Professional" by Magnus Lie Hetland Page 227 # numberlines.py import fileinput........................(1) for line in fileinput.input(inplace = true)............(2) line = line.rstrip()........................................(3) num=fileinput.lineno()..................................(4) print '%-40s #%2i' %(line,num).....................(5) Question: Please help me understand: Line (3) - Are we stripping the entire line of code first, inserting the code at the end (line (5)) and then placing it back at the same place ? Line (5) - What does the individual characters in the expression "Print '%-40s #%2i' %(line,num)" mean ? - '-40s' : is this the space [what does "-40s" mean] that we are creating post - which the line nos is inserted "#%2i" ? - What does '%2" mean ? - Is that 2 cursor spaces of width ? Much thanks in advance... -- Thanks and regards, Sudip Bhattacharya Mobile: +91 9999 100 706 Home Land line: +91 11 22237561 Office Land line: +91 0124 4321078 eMail ID: sudipb at sudipb.com; sudipb at gmail.com Please visit my website at: www.sudipb.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Jun 12 13:19:37 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jun 2010 13:19:37 +0200 Subject: [Tutor] Looking for duplicates within a list References: <4C1240CE.7050807@insightbb.com> Message-ID: Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress. I have a group of 18 number, in ascending order, within a > list. They ranged from 1 to 39. Some numbers are duplicated as much as > three times or as few as none. > > I started with one list containing the numbers. For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > > for j in range (0, 5): > x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? > > In any event, if a number is listed more than once, I would like to know > how many times, such as 2 or 3 times. For example, '3' is listed twice > within a list. I haven't seen a solution that takes advantage of the fact that the numbers are sorted, so here's one: >>> items = [1, 2, 3, 3, 4] >>> value = items[0] >>> n = 0 >>> result = [] >>> for item in items: ... if value != item: ... print value, "-->", n ... value = item ... n = 1 ... else: ... n += 1 ... 1 --> 1 2 --> 1 3 --> 2 >>> print value, "-->", n 4 --> 1 Python has a cool feature called generator that allows you to encapsulate the above nicely: >>> def count_runs(items): ... it = iter(items) ... value = next(it) ... n = 1 # next consumes one item ... for item in it: # the for loop starts with the second item ... if value != item: ... yield value, n ... value = item ... n = 1 ... else: ... n += 1 ... yield value, n ... >>> for v, n in count_runs([1, 1, 1, 2, 2, 3, 4, 4, 4, 4]): ... print v, "-->", n ... 1 --> 3 2 --> 2 3 --> 1 4 --> 4 Finally, there is itertools.groupby() which allows you to simplify the implementation count_runs(): >>> from itertools import groupby >>> def count_runs2(items): ... for key, group in groupby(items): ... yield key, sum(1 for _ in group) ... >>> for v, n in count_runs2([1, 1, 1, 2, 2, 3, 4, 4, 4, 4]): ... print v, "-->", n ... 1 --> 3 2 --> 2 3 --> 1 4 --> 4 Peter From mehgcap at gmail.com Sat Jun 12 14:13:18 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 12 Jun 2010 08:13:18 -0400 Subject: [Tutor] winsound.Beep(500,500) "Failed to beep" In-Reply-To: References: Message-ID: Not that it helps much, but using win7x64 and Python 2.6 it works as expected. Possibly your sound card? Update drivers? On 6/12/10, Richard D. Moores wrote: >>>> import winsound >>>> winsound.Beep(500,500) > Traceback (most recent call last): > File "", line 1, in > RuntimeError: Failed to beep >>>> > > Vista, Python 3.1 > > Any ideas? > > Dick Moores > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From bgailer at gmail.com Sat Jun 12 17:05:52 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 Jun 2010 11:05:52 -0400 Subject: [Tutor] Better construct? (was no subject) In-Reply-To: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> Message-ID: <4C13A250.5020405@gmail.com> On 6/11/2010 5:12 PM, Advertising Department wrote: Please supply a meaningful subject. > #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw > """still thinking in imperative" > """ > > ## obviously this is a bad construct. Why is it "obvious"? What is "this"? Are you referring to the function, to the mainline program, or what? > ## Can someone suggest a pythonesque way of doing this? > > > def getid(): > response = raw_input('prompt') > if response not in [ "", "y", "Y", "yes"] : > getid() # ouch > print "continue working" > # do more stuff > # do more stuff > > > getid() > dosomething() > getid() > dosomethingelse() > > > ## obviously this is a bad construct. > ## Can someone give me a pythonesque way of doing this? One improvement - response.lower().startswith("yes") will cover all your cases. You can collect functions in a sequence, then iterate over it. This allows for easy expansion (when you decide to add another function). funcs = (dosomething(), dosomethingelse()) for func in funcs: getid() func() -- Bob Gailer 919-636-4239 Chapel Hill NC From jdeltoro1973 at gmail.com Sat Jun 12 19:24:37 2010 From: jdeltoro1973 at gmail.com (Juan Jose Del Toro) Date: Sat, 12 Jun 2010 12:24:37 -0500 Subject: [Tutor] Python a substitute/alternative for PhP? In-Reply-To: References: <4C1291AB.40804@googlemail.com> <20100611222744.GB56775@cutter.rexx.com> Message-ID: 2010/6/11 Alex Hall > Personally, I would learn Python. My college does not offer Python > either, so I had to learn what I know on my own(of course, by that I > mean constantly pestering this and other of the amazing Python email > lists). PHP is fine in itself, but, after using it, Java, and intros > to a few other languages, nothing has been able to beat Python's ease > of use, massive extensibility (there is a package to let you do just > about anything you want), and support community. It is a great > language and, especially if you plan to stick with desktop > applications, I think it is much easier than a language like C++ or > Java. Your life will be even easier than mine since you are going to > be on Linux; I believe most Linux distros come with Python, while > Windows does not, so what you make can be distributed as scripts while > I have to use a program like py2exe and package the entire Python > interpreter. > Anyway, just my thoughts. Note that I am still in college for my > computer science degree and am in no way a professional programmer, > just someone who has waded in several languages and found Python to be > the only one worth diving into all the way. > > On 6/11/10, Eldon Londe Mello Junior wrote: > > > > Hi there, > > > > If you care to listen to my story and fully help me out, just keep on > > reading }else{ move to the final question :) > > > > I'm just finishing an introductory course on PhP and MySQL (HTML, CSS and > > Javascript basics included). That's a typical first step to novice > > programmers in Brazil. > > > > However, I've been reading a lot about programming languages and stuff in > > order to make the best choice as I don't want to spend much time learning > > unnecessary things I won't need in the future. > > > > Thus, I decided I want to be a contributor for the GNU/LINUX community > and, > > of course, become sort of an opensource-solutions professional > programmer. > > And if I got it right, python would the most adequate language for me to > > reach my goals. > > > > Only a few programmers in Brazil are familiar with python though. As I > said > > before, most beginners start with PhP and stick with it or go for JAVA or > MS > > proprietary languages. Actually, you can only learn python on your own > > around here as no college or private institutes offer python courses. > > > > As you may see it coming, the big question for me is: should I stick with > > PHP as most people here (those fond of free software) or Python is or > would > > be a better choice for me? > > > > FINAL QUESTION> Is Python a substitute for PHP? I mean, can I start > learning > > python by trying to do the things I've learned with PHP? Are they > different > > anyhow or they actually compete against each other? > > > > Thanks in advance, advice on which steps to take to reach my career goals > > would be very appreciated as well! > > > > Eldon. > > > > > > > > > > > >> Date: Fri, 11 Jun 2010 15:27:44 -0700 > >> From: dkuhlman at rexx.com > >> To: Tutor at python.org > >> Subject: Re: [Tutor] What's the catch with ZopeDB? > >> > >> On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote: > >> > >> > > >> > To me, ZopeDB (a object database for Python) looks like an awesomely > >> > easy solution. I could save some brain power for the innovative part > or > >> > drink more beer watching the soccer world cup. At the same moment, I > >> > wonder why anyone in the python world would go through the hassle of > >> > using relational databases unless forced. > >> > > >> > So, has anyone experience with ZopeDB? Are there some drawbacks I > should > >> > > >> > be aware of before getting a book and dive in? (It sounds too good > ;-)) > >> > > >> > >> Jan - > >> > >> If you are evaluating alternative solutions, you might also look > >> into Django models. There have been some very positive comments > >> about Django on this list. And, Django models can be used outside > >> of the Django Web applications. Also, Django models are reasonably > >> object oriented. A Django model/DB can sit on top of several > >> different relational database engines, for example, PostgreSQL, MySQL, > >> sqlite3, etc. > >> > >> See: > >> > >> http://docs.djangoproject.com/en/1.2/#the-model-layer > >> http://www.djangobook.com/en/2.0/chapter05/ > >> > >> - Dave > >> > >> -- > >> Dave Kuhlman > >> http://www.rexx.com/~dkuhlman > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > > > > _________________________________________________________________ > > Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. > > https://signup.live.com/signup.aspx?id=60969 > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Eldon; Same here in Mexico, in my hometown Guadalajara I couldn't find any Python course everything is either PHP, Delphi, Visual Basic or Java; I chose Java as a way of learning Python, sounds odd but since I don't have any programming background I was lacking the basics concepts and my self-teaching techniques were not doing a very good job; Java is HARD is confusing and most of my effort has gone into trying to memorize the steps in order to run a simple program; my idea is after this course I will re-take Python and understand it much better and of course as a Ihave already realized and actually miss its simplicity and beauty; so I guess it's true to say that "The more I learn Java the more I Love Python". -- ?Saludos! / Greetings! Juan Jos? Del Toro M. jdeltoro1973 at gmail.com Guadalajara, Jalisco MEXICO -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Jun 12 20:22:03 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 12 Jun 2010 13:22:03 -0500 Subject: [Tutor] Linux webcam libraries? Message-ID: Hi, I want to do something like this: http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-driveway-activity/ I want to be able to grab a webcam image via python. So I'm curious if anyone has had any experience/luck in this particular area and/or knows of any libraries I should take a look at. I know my webcam definitely works under linux because I can use the cheese program and see the image... Anyway, any information will be very welcome! Thanks, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From imsam100 at yahoo.co.in Sat Jun 12 20:29:19 2010 From: imsam100 at yahoo.co.in (saurabh agrawal) Date: Sat, 12 Jun 2010 23:59:19 +0530 (IST) Subject: [Tutor] Tutor Digest, Vol 76, Issue 31 In-Reply-To: Message-ID: <290351.88493.qm@web94616.mail.in2.yahoo.com> Hi, You can use method name count in list also for getting the repeats. #!/usr/bin/python li=[1,2,3,1,4,5,7,3,4,1] for i in range(len(li)): ??? print li[i], li.count(li[i]) cheers, Saurabh --- On Fri, 11/6/10, tutor-request at python.org wrote: From: tutor-request at python.org Subject: Tutor Digest, Vol 76, Issue 31 To: tutor at python.org Date: Friday, 11 June, 2010, 8:19 PM 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. Looking for duplicates within a list (Ken G.) ???2. Re: Looking for duplicates within a list (Alex Hall) ???3. Re: Looking for duplicates within a list (Ken G.) ???4. Re: Looking for duplicates within a list (Ken G.) ???5. Re: Looking for duplicates within a list (Sander Sweers) ???6. Re: Looking for duplicates within a list (Jose Amoreira) ---------------------------------------------------------------------- Message: 1 Date: Fri, 11 Jun 2010 09:57:34 -0400 From: "Ken G." To: tutor at python.org Subject: [Tutor] Looking for duplicates within a list Message-ID: <4C1240CE.7050807 at insightbb.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed I have been working on this problem for several days and I am not making any progress.? I have a group of 18 number, in ascending order, within a list.? They ranged from 1 to 39.? Some numbers are duplicated as much as three times or as few as none. I started with one list containing the numbers.? For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: ? ? for j in range (0, 5): ? ? x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times.? For example, '3' is listed twice within a list. TIA, Ken ------------------------------ Message: 2 Date: Fri, 11 Jun 2010 10:20:20 -0400 From: Alex Hall To: "Ken G." Cc: tutor at python.org Subject: Re: [Tutor] Looking for duplicates within a list Message-ID: ??? Content-Type: text/plain; charset=ISO-8859-1 On 6/11/10, Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress.? I have a group of 18 number, in ascending order, within a > list.? They ranged from 1 to 39.? Some numbers are duplicated as much as > three times or as few as none. FYI, Python's "set" data type will let you have a list and never have a repeat. I know that is not your goal now, but if you want to remove duplicates, it seems like a good choice. > > I started with one list containing the numbers.? For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > >? ???for j in range (0, 5): >? ???x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? A couple points here. First, you will want to make life easier by saying range(0, len(a)) so that the loop will work no matter the size of a. Second, for comparing a list to itself, here is a rather inefficient, though simple, way: for i in range(0, len(a)): x=a[i] for j in range(0, len(a)): ? y=a[j] ? if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the same index of a > > In any event, if a number is listed more than once, I would like to know > how many times, such as 2 or 3 times.? For example, '3' is listed twice > within a list. Do not quote me here, but I think sets may be able to tell you that as well. > > TIA, > > Ken > > > > > > > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap ------------------------------ Message: 3 Date: Fri, 11 Jun 2010 10:31:58 -0400 From: "Ken G." To: vnbang2003 at yahoo.com, tutor at python.org Subject: Re: [Tutor] Looking for duplicates within a list Message-ID: <4C1248DE.6090508 at insightbb.com> Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" vijay wrote: > Check out this code >? l= [1, 2, 3, 3, 4] >? d={} >? for item in l: >? ? ? d.setdefaut(item,0) >? ? ? d[item] +=1 > print d > {1: 1, 2: 1, 3: 2, 4: 1} > > > with regard's > vijay > > Thanks.? Very interesting concept. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Fri, 11 Jun 2010 10:40:58 -0400 From: "Ken G." To: Alex Hall Cc: tutor at python.org Subject: Re: [Tutor] Looking for duplicates within a list Message-ID: <4C124AFA.7030007 at insightbb.com> Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" Alex Hall wrote: > On 6/11/10, Ken G. wrote: >??? >> I have been working on this problem for several days and I am not making >> any progress.? I have a group of 18 number, in ascending order, within a >> list.? They ranged from 1 to 39.? Some numbers are duplicated as much as >> three times or as few as none. >>? ??? > FYI, Python's "set" data type will let you have a list and never have > a repeat. I know that is not your goal now, but if you want to remove > duplicates, it seems like a good choice. >??? >> I started with one list containing the numbers.? For example, they are >> listed as like below: >> >> a = [1, 2, 3, 3, 4] >> >> I started off with using a loop: >> >>? ???for j in range (0, 5): >>? ???x = a[0] # for example, 1 >> >> How would I compare '1' with 2, 3, 3, 4? >> >> Do I need another duplicated list such as b = a and compare a[0] with >> either b[0], b[1], b[2], b[3], b[4]? >> >> Or do I compare a[0] with a[1], a[2], a[3], a[4]? >>? ??? > A couple points here. First, you will want to make life easier by > saying range(0, len(a)) so that the loop will work no matter the size > of a. > Second, for comparing a list to itself, here is a rather inefficient, > though simple, way: > > for i in range(0, len(a)): >? x=a[i] >? for j in range(0, len(a)): >???y=a[j] >???if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the > same index of a >??? >> In any event, if a number is listed more than once, I would like to know >> how many times, such as 2 or 3 times.? For example, '3' is listed twice >> within a list. >>? ??? > Do not quote me here, but I think sets may be able to tell you that as well. >??? >> TIA, >> >> Ken >>? ??? Thank you for your contribution.? As seen here, I have much to learn. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Fri, 11 Jun 2010 16:46:25 +0200 From: Sander Sweers To: "Ken G." Cc: tutor at python.org Subject: Re: [Tutor] Looking for duplicates within a list Message-ID: ??? Content-Type: text/plain; charset=UTF-8 On 11 June 2010 15:57, Ken G. wrote: > In any event, if a number is listed more than once, I would like to know how > many times, such as 2 or 3 times. ?For example, '3' is listed twice within a > list. If you do not have top keep the order of the number this will work. >>> a = [1, 2, 3, 3, 4] >>> counted = {} >>> for n in a: ??? if not n in counted: ??? ??? counted[n] = 1 ??? else: ??? ??? counted[n] += 1 >>> counted {1: 1, 2: 1, 3: 2, 4: 1} >>> for x, y in counted.items(): ??? if y > 1: ??? ??? print "Number %s was found %s times" % (x, y) ??? else: ??? ??? print "Number %s was found %s time" % (x, y) Number 1 was found 1 time Number 2 was found 1 time Number 3 was found 2 times Number 4 was found 1 time Greets Sander ------------------------------ Message: 6 Date: Fri, 11 Jun 2010 15:49:22 +0100 From: Jose Amoreira To: tutor at python.org Subject: Re: [Tutor] Looking for duplicates within a list Message-ID: <201006111549.22751.ljmamoreira at gmail.com> Content-Type: Text/Plain;? charset="iso-8859-1" On Friday, June 11, 2010 02:57:34 pm Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress.? I have a group of 18 number, in ascending order, within a > list.? They ranged from 1 to 39.? Some numbers are duplicated as much as > three times or as few as none. > > I started with one list containing the numbers.? For example, they are > listed as like below: > > a = [1, 2, 3, 3, 4] > > I started off with using a loop: > >? ???for j in range (0, 5): >? ???x = a[0] # for example, 1 > > How would I compare '1' with 2, 3, 3, 4? > > Do I need another duplicated list such as b = a and compare a[0] with > either b[0], b[1], b[2], b[3], b[4]? > > Or do I compare a[0] with a[1], a[2], a[3], a[4]? > > In any event, if a number is listed more than once, I would like to know > how many times, such as 2 or 3 times.? For example, '3' is listed twice > within a list. > > TIA, > I would do it with a dictionary: def reps(lst): ??? dict = {} ??? for item in lst: ??? ??? if item in dict: ??? ??? ??? dict[item] += 1 ??? ??? else: ??? ??? ??? dict[item] = 1 ??? return dict This function returns a dictionary with of the number of times each value in the list is repeated. Even shorter using dict.setdefault: def reps(lst): ??? dict={} ??? for item in lst: ??? ??? dict[item] = dict.setdefault(item,0) + 1 ??? return dict For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns {1: 1, 2: 3, 4: 2, 5: 1} Using the fact that the list is ordered, one can design a more efficient solution (go through the list; if this item is equal to the previous, then it is repeated, else, it is a new value). But you list is short enough for this direct approach to work. Hope this helps. Cheers, Jose ------------------------------ _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 76, Issue 31 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 12 21:56:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 20:56:21 +0100 Subject: [Tutor] Python a substitute/alternative for PhP? References: <4C1291AB.40804@googlemail.com>, <20100611222744.GB56775@cutter.rexx.com> Message-ID: "Eldon Londe Mello Junior" wrote First, please don't hijack an existing thread, this message appears under a thread about Zope DB! Always post a new message to start a new thread. It will get more readers and not confuse readers using threaded mail/newsreaders. > However, I've been reading a lot about programming > languages and stuff in order to make the best choice > as I don't want to spend much time learning unnecessary > things I won't need in the future. I'm not sure what you think the "unnecessary things" are but programming languages come and go and as a professional programmers you can expect to have to learn at least a dozen before you are done, probably more like two dozen. So don't think you will pick a single language and never have to learn another. As a minimum you will probably need to know: a) A general purpose language - Java, python, C++, Visual Basic, etc... b) SQL c) Javascript d) An OS shell language(DOS batch/WSH or a Linux shell(bash/csh or Korn) Very few modern applications have less than those 4 language groups embedded within them somewhere. The minimum I've ever seen in a professional project is 3. The maximum was 12 - but it was a big project. > opensource-solutions professional programmer. Caveat: There is not a lot of money in that market. People use Opensource because they expect it to be cheap. That means they won't pay the programmer as much either... At lerast thats my experience. There is much more money to be had programming Oracle or DB2 apps than creating MySql apps... > beginners start with PhP and stick with it or go for JAVA > or MS proprietary languages. Actually, you can only > learn python on your own around here as no college > or private institutes offer python courses. Pyton didn't even exist when I started, but neither did Java or C++ or VB... And in twenty years time possibly none of these languages will be in vogue and we will all be using periwinkle gizzard or whatever the latest craze is called... > FINAL QUESTION> Is Python a substitute for PHP? It can do similar things but it does it differently, especially for the web. Although you can write standalone PHP programs it is usually used on the Web. Most serious webv developers combine Python with a web framework like Django or Pylons or whatever. Arguably Python + Framework is superior to PHP - but less widely supported on ISP servers. > I mean, can I start learning python by trying to do the > things I've learned with PHP? You can, but the web elements will be very different. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 12 22:03:23 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 21:03:23 +0100 Subject: [Tutor] New to Programming References: Message-ID: "Kaushal Shriyan" wrote > I am absolutely new to programming language. Dont have any > programming > experience. Can some one guide me please. is python a good start for > novice. Yes, it is one of the best languages for an absolute beginner. It may be all the language you ever need but even if you branch out to others the principles you learn in Python will translate easily. There are a bunch of tutorials for absiolute beginners listed on the Python web site (including mine) Try here (or follow my .sig): http://wiki.python.org/moin/BeginnersGuide/NonProgrammers -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 12 21:59:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 20:59:52 +0100 Subject: [Tutor] Better construct? (was no subject) References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> <4C13A250.5020405@gmail.com> Message-ID: "bob gailer" wrote > You can collect functions in a sequence, then iterate over it. This > allows for easy expansion (when you decide to add another function). > > funcs = (dosomething(), dosomethingelse()) I suspect Bob meant to leave off the (). You would normally just use the function name. (Unless these are factory functions returning another function but I don't think that was the intent! :-) funcs = (doSomething, doSomethingElse) > for func in funcs: > getid() > func() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 12 22:10:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 21:10:20 +0100 Subject: [Tutor] Adding line numbers to a Python Script References: Message-ID: "Sudip Bhattacharya" wrote > for line in fileinput.input(inplace = true)............(2) > line = line.rstrip()........................................(3) > num=fileinput.lineno()..................................(4) > print '%-40s #%2i' %(line,num).....................(5) > > Line (3) - Are we stripping the entire line of code first, inserting > the > code at the end (line (5)) and then placing it back at the same > place ? Fire up the python interpreter and type: >>> help("".strip) See if you understand what it says. If not come back here and ask again. Python's help fuinction is very powerful, learn to use it for fast answers. > Line (5) - What does the individual characters in the expression > "Print > '%-40s #%2i' %(line,num)" mean ? These are formatting characters. If you read the Simple Sequences topic in my tutor you will get some easier examples to try. Then read the Python documentation - search for format string... > - '-40s' : is this the space [what does "-40s" mean] that we are > creating post - which the line nos is inserted "#%2i" ? Again fitre up the Python interpreter and try it out. >>> "%-40s" % "Some string here" Now try again with a different number, Try missing out the minus sign. Can you see what the different bits do? Now go read the documentation again. Try some different data types. Experiment. Its the best way to really understand. > - What does '%2" mean ? - Is that 2 cursor spaces of width ? Close but again Read the docs, try it, experiment. See for yourself. >>> "%2i" % 7 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 12 22:12:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 21:12:48 +0100 Subject: [Tutor] Tutor Digest, Vol 76, Issue 31 References: <290351.88493.qm@web94616.mail.in2.yahoo.com> Message-ID: Please do not send the entire digest when replying rto a single email. Use your editor to remove the redundant material. -------------------- "saurabh agrawal" wrote You can use method name count in list also for getting the repeats. #!/usr/bin/python li=[1,2,3,1,4,5,7,3,4,1] for i in range(len(li)): print li[i], li.count(li[i]) cheers, Saurabh --- On Fri, 11/6/10, tutor-request at python.org wrote: From: tutor-request at python.org Subject: Tutor Digest, Vol 76, Issue 31 To: tutor at python.org Date: Friday, 11 June, 2010, 8:19 PM ... From alan.gauld at btinternet.com Sat Jun 12 22:17:37 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jun 2010 21:17:37 +0100 Subject: [Tutor] Problems with Importing into the Python Shell References: Message-ID: "Andrew Martin" wrote > am having some trouble. First off, I do not understand how to import > things > into the python shell. I have a script I saved as chap03.py, but > when I try > to import it into the python shell i get an error like this: > >>>> from chap03 import * > > Traceback (most recent call last): > File "", line 1, in > from chap03 import * > File "C:/Python26\chap03.py", line 2 > print param param > ^ > SyntaxError: invalid syntax OK, First things first. You have imported the file correctly. Thats why you are getting the error. Now read the error. It says there is a syntax error, which there is. Can you see what you have done wrong in the print statement. The little caret symbol is giving you a big clue... Finally, its considered bad style to use from foo import * It can lerad to difficult to debug problems where two files have things with the same name. It is better to use import foo and then use foo.name to access things. It is more typing but much safer and more reliable. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sun Jun 13 00:10:58 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 Jun 2010 18:10:58 -0400 Subject: [Tutor] Better construct? (was no subject) In-Reply-To: References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> <4C13A250.5020405@gmail.com> Message-ID: <4C1405F2.5060506@gmail.com> On 6/12/2010 3:59 PM, Alan Gauld wrote: > > "bob gailer" wrote > >> You can collect functions in a sequence, then iterate over it. This >> allows for easy expansion (when you decide to add another function). >> >> funcs = (dosomething(), dosomethingelse()) > > I suspect Bob meant to leave off the (). Yep. Thank you for the correction. -- Bob Gailer 919-636-4239 Chapel Hill NC From eike.welk at gmx.net Sun Jun 13 01:27:42 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 13 Jun 2010 01:27:42 +0200 Subject: [Tutor] OT: Great find! In-Reply-To: References: Message-ID: <201006130127.42852.eike.welk@gmx.net> On Saturday June 12 2010 20:22:03 Wayne Werner wrote: > I want to do something like this: > http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-dri > veway-activity/ Great find! That's a very nice idea! Eike. From eldonjr at hotmail.com Sun Jun 13 02:58:17 2010 From: eldonjr at hotmail.com (Eldon Londe Mello Junior) Date: Sat, 12 Jun 2010 21:58:17 -0300 Subject: [Tutor] Python a substitute/alternative for PhP? In-Reply-To: References: <4C1291AB.40804@googlemail.com>, , <20100611222744.GB56775@cutter.rexx.com>, , Message-ID: Hi there, Just would like to thanks all of those who provided me with some insight about which ways to go about programming. I'll consider every single piece of advice. I would also like to apologize for I didn't mean to hijack no thread, that was just so stupid of me. As I'm finishing my PhP course by Monday now I feel comfortable enough to delve into Python which means you'll probably be hearing from me soon, Cheers for the English speakers and saludos a Jos? Del Toro! Eldon. _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Jun 13 04:57:30 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 12 Jun 2010 21:57:30 -0500 Subject: [Tutor] Better construct? (was no subject) In-Reply-To: <4C13A250.5020405@gmail.com> References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> <4C13A250.5020405@gmail.com> Message-ID: > >> ## Can someone suggest a pythonesque way of doing this? >> >> >> def getid(): >> ? ?response ?= raw_input('prompt') >> ? ?if response not in [ "", "y", "Y", "yes"] : >> ? ? ? ?getid() ? ?# ouch >> ? ?print "continue working" >> ? ?# do more stuff >> ? ?# do more stuff >> This seems like really strange behavior. If the response is wrong, you will then have another instance of getid, then if they get the response correct, you will execute your code twice! Was that really your intent? I think what you really want is: def getid(): valid = False while not valid: response = raw_input('prompt') valid = response.strip().lower() in ["", "y", "yes"] >One improvement - response.lower().startswith("yes") will cover all your cases. Am I misunderstanding? They appear to have different behaviors. >>> x = "" >>> y = ["", "y", "Y", "yes"] >>> x not in y False >>> x.lower().startswith('yes') False >>> x = "yes" >>> x not in y False >>> x.lower().startswith('yes') True From steve at pearwood.info Sun Jun 13 05:03:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 Jun 2010 13:03:32 +1000 Subject: [Tutor] lib2to3 fixers In-Reply-To: References: Message-ID: <201006131303.33042.steve@pearwood.info> On Sat, 12 Jun 2010 05:27:39 am Zubin Mithra wrote: > Hey everyone, > > I just discovered that the following construct does not work in Py3k. > > >>> string.maketrans('-', '_') Like the error message says, you have to use bytes, which I grant is counter-intuitive, but it does work: >>> table = string.maketrans(b'-', b'_') >>> 'abc-def'.translate(table) 'abc_def' (Perhaps it shouldn't though... it seems to be an undocumented feature.) > However, the following works, > > >>> str.maketrans('-', '_') > > When i try to convert a python module containing the above construct, > it does not get modified in a way such that it could run on Python > 3.0 I think this should be reported as a bug/feature request on the bug tracker. Having 2to3 be as extensive as possible is a high priority to the Python development team. http://bugs.python.org/ > 1. replace string.maketrans() with a function which is compatible in > both Python 2.x and 3.0 ; as of now I`m unaware of such a construct. That at least is easy. def maketrans(a, b): try: return string.translate(a, b) except TypeError: return str.translate(a, b) > 2. write a fixer for doing this which I could use. I could`nt find > any good tutorials out there on writing fixers, i`d be grateful if > you could point me to any. For that you probably need to ask on the main Python mailing list or newsgroup: comp.lang.python http://mail.python.org/mailman/listinfo/python-list -- Steven D'Aprano From lie.1296 at gmail.com Sun Jun 13 10:08:29 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Jun 2010 18:08:29 +1000 Subject: [Tutor] Linux webcam libraries? In-Reply-To: References: Message-ID: On 06/13/10 04:22, Wayne Werner wrote: > Hi, > > I want to do something like this: > http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-driveway-activity/ > > I want to be able to grab a webcam image via python. So I'm curious if > anyone has had any experience/luck in this particular area and/or knows of > any libraries I should take a look at. I know my webcam definitely works > under linux because I can use the cheese program and see the image... > I think the upcoming pygame2 will have a camera module, though I've never personally used it. From sander.sweers at gmail.com Sun Jun 13 11:35:02 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 13 Jun 2010 11:35:02 +0200 Subject: [Tutor] Linux webcam libraries? In-Reply-To: References: Message-ID: On 12 June 2010 20:22, Wayne Werner wrote: > I want to be able to grab a webcam image via python. So I'm curious if > anyone has had any experience/luck in this particular area and/or knows of > any libraries I should take a look at. I know my webcam definitely works > under linux because I can use the cheese program and see the image... Everything that captures video under linux is managed by video4linux [1]. You will have to figure out how to use it with python. A quick google search led me to v4l2capture [2]. Greets Sander [1] http://www.linuxtv.org/wiki/index.php/Main_Page [2] http://pypi.python.org/pypi/v4l2capture/1.2 From steve at pearwood.info Sun Jun 13 12:55:58 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 Jun 2010 20:55:58 +1000 Subject: [Tutor] (no subject) In-Reply-To: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> References: <6F3DC60E-3EE2-48B8-9C90-403BEC5FD784@robbstucky.net> Message-ID: <201006132055.59040.steve@pearwood.info> On Sat, 12 Jun 2010 07:12:27 am Advertising Department wrote: > #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw > """still thinking in imperative" > """ There is absolutely nothing wrong with writing imperative code. Python makes it easy to mix imperative, functional and object-oriented code in the same application, and in truth you'll soon find that they blend into each other so easily that sometimes it's hard to tell the difference. > ## obviously this is a bad construct. > ## Can someone suggest a pythonesque way of doing this? You have to explain what you are aiming to do. > def getid(): > response = raw_input('prompt') > if response not in [ "", "y", "Y", "yes"] : > getid() # ouch > print "continue working" > # do more stuff > # do more stuff You have comments "do more stuff" (repeated twice, so I suppose that means there is a LOT of more stuff) in a function called "getid". *That* is a bad programming construct, and not just in Python, and not because it is imperative. It is because the getid() function should do ONE THING -- get the id, and nothing else. You should separate the *user interface* from the *backend* (the engine). So you should have two functions: def getid(): """Return the id.""" return 123456789 # FIXME everybody has the same id... def ask_id(prompt): prompt = prompt + ' (Y/n) ' done = False while not done: response = raw_input(prompt) done = response.lower() in ["", "y", "yes", "n", "no"] return response.lower() in ["", "y", "yes"] And then put them together in your main program like this: def main(): if ask_id('Would you like an ID?'): x = getid() do_something_with_id(x) print "Continue working"... do_some_work() do_some_more_work() while ask_id('Would you like another ID?'): x = getid() do_something_else_with_id(x) print "Done now!" main() Hope this helps. -- Steven D'Aprano From kaushalshriyan at gmail.com Sun Jun 13 17:38:27 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Sun, 13 Jun 2010 21:08:27 +0530 Subject: [Tutor] New to Programming In-Reply-To: <4C1362B7.6070702@ieee.org> References: <4C1362B7.6070702@ieee.org> Message-ID: On Sat, Jun 12, 2010 at 4:04 PM, Dave Angel wrote: > Kaushal Shriyan wrote: >> >> Hi, >> >> I am absolutely new to programming language. Dont have any programming >> experience. Can some one guide me please. is python a good start for >> novice. >> >> Thanks, >> >> Kaushal >> >> > > Like nearly all questions, the answer is "it depends." > > Mainly, it depends on what your goal is. ?In my case, I made my living with > programming, for many years. ?And in the process, learned and used about 35 > languages, plus a few more for fun. ?I wish I had discovered Python much > earlier, though it couldn't have been my first, since it wasn't around. ?But > it'd have been much better than Fortran was, for learning. > > So tell us about your goals. ?Abstract knowledge, console utilities, gui > development, games, web development, networking communication, ... > > Next, you might want to evaluate what you already know. ?There are a lot of > non-programming things that a programmer needs to understand. ?If you > already know many of them, that's a big head start. ?If you already know how > to administer a Linux system, you're already a programmer and didn't know > it. ?If you write complex formulas for Excel, you're a programmer. ?If you > already know modus ponens, and understand what a contrapositive is, you've > got a head start towards logic (neither is a programming subject, just a > start towards logical thinking). ?If you've worked on a large document, and > kept backups of ?incremental versions, so you could rework the current > version based on earlier ones, that's a plus. ?If you know why a file's > timestamp might change when you copy it from hard disk to a USB drive and > back again, you've got a head start. ?If you know why it might have a > different timestamp when you look at it six months from now without changing > it, you've got a head start. > > If you're using Windows and never used a command prompt, you have a ways to > go. ?If you don't know what a file really is, or how directories are > organized, you have a ways to go. ?And if you think a computer is > intelligent, you have a long way to go. > > Python is a powerful tool. ?But if you're totally new to programming, it can > also be daunting. ?And most people have no idea how easy some programs are, > nor how hard some other programs are, to build. > > In any case, some of the things recommending Python as a first language are: > ?1) an interactive interpreter - you can experiment, trivially > ?2) very fast turnaround, from the time you make a change, till you can see > how it works. ?This can be true even for large programs > ?3) this mailing list > > DaveA > > Thanks Dave. You saved my day and really motivated me Kaushal From kaushalshriyan at gmail.com Sun Jun 13 17:38:38 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Sun, 13 Jun 2010 21:08:38 +0530 Subject: [Tutor] New to Programming In-Reply-To: References: Message-ID: On Sun, Jun 13, 2010 at 1:33 AM, Alan Gauld wrote: > > "Kaushal Shriyan" wrote > >> I am absolutely new to programming language. Dont have any programming >> experience. Can some one guide me please. is python a good start for >> novice. > > Yes, it is one of the best languages for an absolute beginner. > It may be all the language you ever need but even if you branch > out to others the principles you learn in Python will translate easily. > > There are a bunch of tutorials for absiolute beginners listed > on the Python web site (including mine) > > Try here (or follow my .sig): > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > Thanks Alan for the motivation. Kaushal From ilhs_hs at yahoo.com Sun Jun 13 23:45:45 2010 From: ilhs_hs at yahoo.com (Hs Hs) Date: Sun, 13 Jun 2010 14:45:45 -0700 (PDT) Subject: [Tutor] large file Message-ID: <461181.1334.qm@web111209.mail.gq1.yahoo.com> hi: I have a very large file 15Gb. Starting from 15th line this file shows the following lines: HWUSI-EAS1211_0001:1:1:977:20764#0 HWUSI-EAS1211_0001:1:1:977:20764#0 HWUSI-EAS1521_0001:1:1:978:13435#0 HWUSI-EAS1521_0001:1:1:978:13435#0 Every two lines are part of one readgroup. I want to add two variables to every line. First variable goes to all lines with odd numbers. Second variable should be appended to all even number lines. like the following: HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2301 HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2302 HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2301 HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2302 Since I cannot read the entire file, I wanted to cat the file something like this: cat myfile | python myscript.py > myfile.sam I do not know how to execute my logic after I read the line, althought I tried: myscript.py: while True: second = raw_input() x = second.split('\t') Could someone help me here either what I want to do. Or suggesting a different method. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Jun 14 00:42:01 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 13 Jun 2010 18:42:01 -0400 Subject: [Tutor] large file In-Reply-To: <461181.1334.qm@web111209.mail.gq1.yahoo.com> References: <461181.1334.qm@web111209.mail.gq1.yahoo.com> Message-ID: <4C155EB9.1060200@gmail.com> On 6/13/2010 5:45 PM, Hs Hs wrote: > hi: > > I have a very large file 15Gb. Starting from 15th line this file shows > the following lines: > > HWUSI-EAS1211_0001:1:1:977:20764#0 > > HWUSI-EAS1211_0001:1:1:977:20764#0 > > HWUSI-EAS1521_0001:1:1:978:13435#0 > > HWUSI-EAS1521_0001:1:1:978:13435#0 > > > Every two lines are part of one readgroup. I want to add two variables > to every line. First variable goes to all lines with odd numbers. > Second variable should be appended to all even number lines. like the > following: > > HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2301 > > HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2302 > > HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2301 > > HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2302 > > Since I cannot read the entire file, I wanted to cat the file > > something like this: > > cat myfile | python myscript.py > myfile.sam > > > I do not know how to execute my logic after I read the line, althought > I tried: > > myscript.py: > > while True: > second = raw_input() > x = second.split('\t') > > # do something with first 14 lines? while True: line = raw_input().rstrip() if not line: break print line + " RG:Z:2301" line = raw_input().rstrip() if not line: break print line + " RG:Z:2302" -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 14 02:19:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Jun 2010 01:19:21 +0100 Subject: [Tutor] large file References: <461181.1334.qm@web111209.mail.gq1.yahoo.com> Message-ID: "Hs Hs" wrote > I have a very large file 15Gb. > Every two lines are part of one readgroup. > I want to add two variables to every line. > HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2301 > HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2302 > ... > Since I cannot read the entire file, I wanted to cat the file What makes you think you cannot read the entire file? > something like this: > > cat myfile | python myscript.py > myfile.sam How does that help over Python reading the file line by line? > I do not know how to execute my logic after I read the line, > althought I tried: > while True: > second = raw_input() > x = second.split('\t') Why are you splitting theline? You only need to append data to the end of the line... > Could someone help me here either what I want to do. In pseudo code: open input and ouput files read the first 14 lines from input oddLine = True while True: read line from input if oddLine: append odd data else append evenData write line to output file oddLine = not oddLine You probably want a try/except in there to catch the end of file. This is not very different from the menu example in the file handling topic of my tutorial... HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Jun 14 03:08:36 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Jun 2010 11:08:36 +1000 Subject: [Tutor] large file In-Reply-To: <461181.1334.qm@web111209.mail.gq1.yahoo.com> References: <461181.1334.qm@web111209.mail.gq1.yahoo.com> Message-ID: <201006141108.36575.steve@pearwood.info> On Mon, 14 Jun 2010 07:45:45 am Hs Hs wrote: > hi: > > I have a very large file 15Gb. Starting from 15th line this file > shows the following lines: > > HWUSI-EAS1211_0001:1:1:977:20764#0 > HWUSI-EAS1211_0001:1:1:977:20764#0 > HWUSI-EAS1521_0001:1:1:978:13435#0 > HWUSI-EAS1521_0001:1:1:978:13435#0 It looks to me that your file has a *lot* of redundant information. Does the first part of the line "HWUSI-EAS1211_0001:1:1:" ever change? If it does not, then you can save approximately 65% of the file size by just recording it once, instead of 400 million times: [first 14 lines] prefix = HWUSI-EAS1211_0001:1:1: 977:20764#0 977:20764#0 978:13435#0 978:13435#0 [...] That will bring the file down from 15GB to less than 6GB, and speed up processing time and decrease storage requirements significantly. > Every two lines are part of one readgroup. I want to add two > variables to every line. First variable goes to all lines with odd > numbers. Second variable should be appended to all even number lines. How are these variables calculated? You need some way of automatically calculating them, perhaps by looking them up in a database. I don't know how you calculate them, so I will invent two simple stubs: def suffix1(line): # Calculate the first suffix variable. return " RG:Z:2301" def suffix2(line): # Calculate the first suffix variable. return " RG:Z:2302" > Since I cannot read the entire file, I wanted to cat the file Of course you can read the file, you just can't read it ALL AT ONCE. There's no need to use cat, you just have to read the file line by line and then do something with each line. infile = open("myfile", "r") outfile = open("output.sam", "w") # Skip over the first 15 lines. for i in range(15): infile.next() # Read one line. suffixes = [suffix1, suffix2] # Store the function objects. n = 0 # Process the lines. for line in infile: line = line.strip() # Which suffix function do we want to call? suffix = suffixes[n] outfile.write(line + suffix(line) + '\n') n = 1 - n # n -> 1, 0, 1, 0, 1, 0, ... outfile.close() infile.close() -- Steven D'Aprano From cristetoespiritante at gmail.com Mon Jun 14 13:06:54 2010 From: cristetoespiritante at gmail.com (cristeto1981) Date: Mon, 14 Jun 2010 04:06:54 -0700 (PDT) Subject: [Tutor] New to Programming In-Reply-To: <4C1362B7.6070702@ieee.org> References: <4C1362B7.6070702@ieee.org> Message-ID: <28878181.post@talk.nabble.com> Dave Angel wrote: > > Kaushal Shriyan wrote: >> Hi, >> >> I am absolutely new to programming language. Dont have any programming >> experience. Can some one guide me please. is python a good start for >> novice. >> >> Thanks, >> >> Kaushal >> >> > Like nearly all questions, the answer is "it depends." > > Mainly, it depends on what your goal is. In my case, I made my living > with programming, for many years. And in the process, learned and used > about 35 languages, plus a few more for fun. I wish I had discovered > Python much earlier, though it couldn't have been my first, since it > wasn't around. But it'd have been much better than Fortran was, for > learning. > > So tell us about your goals. Abstract knowledge, console utilities, gui > development, games, web development, networking communication, ... > > Next, you might want to evaluate what you already know. There are a lot > of non-programming things that a programmer needs to understand. If you > already know many of them, that's a big head start. If you already know > how to administer a Linux system, you're already a programmer and didn't > know it. If you write complex formulas for Excel, you're a programmer. > If you already know modus ponens, and understand what a contrapositive > is, you've got a head start towards logic (neither is a programming > subject, just a start towards logical thinking). If you've worked on a > large document, and kept backups of incremental versions, so you could > rework the current version based on earlier ones, that's a plus. If you > know why a file's timestamp might change when you copy it from hard disk > to a USB drive and back again, you've got a head start. If you know why > it might have a different timestamp when you look at it six months from > now without changing it, you've got a head start. > > If you're using Windows and never used a command prompt, you have a ways > to go. If you don't know what a file really is, or how directories are > organized, you have a ways to go. And if you think a computer is > intelligent, you have a long way to go. > > Python is a powerful tool. But if you're totally new to programming, it > can also be daunting. And most people have no idea how easy some > programs are, nor how hard some other programs are, to build. > > In any case, some of the things recommending Python as a first language > are: > 1) an interactive interpreter - you can experiment, trivially > 2) very fast turnaround, from the time you make a change, till you > can see how it works. This can be true even for large programs > 3) this mailing list > > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks for this thread. It really helps. Those links were very informative. :) ----- [url=http://crosspromotion.wizard4u.com/]joint ventures[/url] -- View this message in context: http://old.nabble.com/-Tutor--New-to-Programming-tp28863541p28878181.html Sent from the Python - tutor mailing list archive at Nabble.com. From cristetoespiritante at gmail.com Mon Jun 14 13:08:13 2010 From: cristetoespiritante at gmail.com (cristeto1981) Date: Mon, 14 Jun 2010 04:08:13 -0700 (PDT) Subject: [Tutor] large file In-Reply-To: References: <461181.1334.qm@web111209.mail.gq1.yahoo.com> Message-ID: <28878191.post@talk.nabble.com> Alan Gauld wrote: > > > "Hs Hs" wrote > >> I have a very large file 15Gb. > >> Every two lines are part of one readgroup. >> I want to add two variables to every line. > >> HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2301 >> HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2302 >> ... >> Since I cannot read the entire file, I wanted to cat the file > > What makes you think you cannot read the entire file? > >> something like this: >> >> cat myfile | python myscript.py > myfile.sam > > How does that help over Python reading the file line by line? > >> I do not know how to execute my logic after I read the line, >> althought I tried: > >> while True: >> second = raw_input() >> x = second.split('\t') > > Why are you splitting theline? You only need to append > data to the end of the line... > >> Could someone help me here either what I want to do. > > In pseudo code: > > open input and ouput files > read the first 14 lines from input > oddLine = True > while True: > read line from input > if oddLine: > append odd data > else > append evenData > write line to output file > oddLine = not oddLine > > You probably want a try/except in there to catch the end of file. > > > This is not very different from the menu example in the file > handling topic of my tutorial... > > HTH > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks for this thread. This is very helful. I'm learning a lot from you guys. :) ----- [url=http://crosspromotion.wizard4u.com/]joint ventures[/url] -- View this message in context: http://old.nabble.com/-Tutor--large-file-tp28874185p28878191.html Sent from the Python - tutor mailing list archive at Nabble.com. From advertising at robbstucky.net Mon Jun 14 21:06:01 2010 From: advertising at robbstucky.net (Advertising Department) Date: Mon, 14 Jun 2010 15:06:01 -0400 Subject: [Tutor] Better construct? Message-ID: Many thanks to all, repeat WHILE is exactly what I needed. I got BASIC stuck in my head. GOTO line# YUCK! From alan.gauld at btinternet.com Tue Jun 15 01:30:29 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Jun 2010 00:30:29 +0100 Subject: [Tutor] Better construct? References: Message-ID: "Advertising Department" wrote > repeat WHILE > is exactly what I needed. > > I got BASIC stuck in my head. GOTO line# YUCK! BASIC has a WHILE/WEND construct too :-) Even GW Basic supported that. Alan G. From lang at tharin.com Tue Jun 15 02:08:38 2010 From: lang at tharin.com (Lang Hurst) Date: Mon, 14 Jun 2010 17:08:38 -0700 Subject: [Tutor] Structuring a class Message-ID: <4C16C486.70804@tharin.com> I'm trying to figure out how to deal with data which will look something like: Student:Bob Hurley ID: 123456 Period:4 Grad_class: 2012 Credits: Algebra C (20P) Chapter 1 Date: September 14, 2010 Grade: 87 Credits:1.5 Notes: Probably cheated on final. Really watch on next quiz/test. Chapter 2 Date: October 31, 2010 . . **and so on** . Consumer Math (24G) Module 2 . . **more information like above** . So, I just figured that I would have a couple of nested dictionaries. bob = Student('123456','Bob Hurley') bob.period = 4 bob.grad_class = 2010 bob['credits']['Algebra C (20P)']={'Chapter 1':{'Date':'September 12, 2010', 'Grade':'87', **and so on**}} This works, for the most part, from the command line. So I decided to set up a class and see if I could work it from that standpoint (I'm doing this to scratch an itch, and try to learn). My preliminary class looks like: class Student: def __init__(self, ident=' ', name=' ', period=' ', grad_class=' ', subject=' ', notes=' ', credit=' '): self.name = name self.ident = ident self.period = period self.notes = notes self.grad_class = grad_class # self.credit = {{}} <--- BAD self.credit = {} I'm sure that someone will enlighten me as to where my poor coding skills are especially weak. It's the last line there (self.credit...) which I can't figure out. The credits may be in any of about 30 different subjects (teaching at a continuation high school makes for interesting times). If I don't set it to anything, ie, like it is, I get an error Stud instance has no attribute '__getitem__' If I try to leave it available for adding to somewhat dynamically, I get a 'wtf' from python. Sorry for the novel, I'm just wondering if someone would set me straight. Should I even use a class? If so, how do I set up a class item which let's me add dictionaries to it? Thanks. -Lang -- There are no stupid questions, just stupid people. From bgailer at gmail.com Tue Jun 15 05:13:00 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Jun 2010 23:13:00 -0400 Subject: [Tutor] Structuring a class In-Reply-To: <4C16C486.70804@tharin.com> References: <4C16C486.70804@tharin.com> Message-ID: <4C16EFBC.6080907@gmail.com> On 6/14/2010 8:08 PM, Lang Hurst wrote: > I'm trying to figure out how to deal with data which will look > something like: > > Student:Bob Hurley > ID: 123456 > Period:4 > Grad_class: 2012 > Credits: > Algebra C (20P) > Chapter 1 > Date: September 14, 2010 > Grade: 87 > Credits:1.5 > Notes: Probably cheated on final. Really watch on > next quiz/test. > Chapter 2 > Date: October 31, 2010 > . > . **and so on** > . > Consumer Math (24G) > Module 2 > . > . **more information like above** > . > Before deciding on data structures I suggest you give the big picture. Where will data come from? What do you plan to do with it? Often a case like this is better handled using a relational database. Python happens to come with the sqlite3 module which makes database work quite easy. > > So, I just figured that I would have a couple of nested dictionaries. > > bob = Student('123456','Bob Hurley') > bob.period = 4 > bob.grad_class = 2010 > bob['credits']['Algebra C (20P)']={'Chapter 1':{'Date':'September > 12, 2010', 'Grade':'87', **and so on**}} > > This works, for the most part, from the command line. So I decided to > set up a class and see if I could work it from that standpoint (I'm > doing this to scratch an itch, and try to learn). My preliminary > class looks like: > > class Student: > def __init__(self, ident=' ', name=' ', period=' ', > grad_class=' ', subject=' ', notes=' ', credit=' '): > self.name = name > self.ident = ident > self.period = period > self.notes = notes > self.grad_class = grad_class > # self.credit = {{}} <--- BAD > self.credit = {} > > I'm sure that someone will enlighten me as to where my poor coding > skills are especially weak. It's the last line there (self.credit...) > which I can't figure out. The credits may be in any of about 30 > different subjects (teaching at a continuation high school makes for > interesting times). You should define a class for Credit, which will hold the credit attributes, just like you did for Student. Then assign instances of Credit to entries in self.credit. > > If I don't set it to anything, ie, like it is, I get an error > > Stud instance has no attribute '__getitem__' > > If I try to leave it available for adding to somewhat dynamically, I > get a 'wtf' from python. Sorry I don't understand these. It is a good idea to post full tracebacks and the code that raises the exception. -- Bob Gailer 919-636-4239 Chapel Hill NC From lang at tharin.com Tue Jun 15 06:01:31 2010 From: lang at tharin.com (Lang Hurst) Date: Mon, 14 Jun 2010 21:01:31 -0700 Subject: [Tutor] Structuring a class In-Reply-To: <4C16EFBC.6080907@gmail.com> References: <4C16C486.70804@tharin.com> <4C16EFBC.6080907@gmail.com> Message-ID: <4C16FB1B.30405@tharin.com> bob gailer wrote: > > Often a case like this is better handled using a relational database. > Python happens to come with the sqlite3 module which makes database > work quite easy. > > > You should define a class for Credit, which will hold the credit > attributes, just like you did for Student. Then assign instances of > Credit to entries in self.credit. >> Last time I did anything with python, it was years ago on a web application and I ended up using gadfly as a database. I did not know that sqlite3 came as a module for python. That just made it much, much easier. I've done much more work with databases. Thank you. I figured that I was probably missing something obvious. -Lang -- There are no stupid questions, just stupid people. From eduardo.susan at gmail.com Tue Jun 15 06:11:59 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 14 Jun 2010 22:11:59 -0600 Subject: [Tutor] large file In-Reply-To: <28878191.post@talk.nabble.com> References: <461181.1334.qm@web111209.mail.gq1.yahoo.com> <28878191.post@talk.nabble.com> Message-ID: > Thanks for this thread. This is very helful. I'm learning a lot from you > guys. :) > > ----- > [url=http://crosspromotion.wizard4u.com/]joint ventures[/url] > > -- > View this message in context: http://old.nabble.com/-Tutor--large-file-tp28874185p28878191.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think this subscriber is just spamming. Two post with the same text. Eduardo From hgfernan at gmail.com Tue Jun 15 02:36:57 2010 From: hgfernan at gmail.com (Hilton Fernandes) Date: Mon, 14 Jun 2010 21:36:57 -0300 Subject: [Tutor] Better construct? In-Reply-To: References: Message-ID: Alan, GW-Basic supported that, but it was not common programming use. :) I've learned programming using Algol (parent of Pascal) and people used to frown at my insistence in using WHILE/WEND Thanks, Hilton On Mon, Jun 14, 2010 at 8:30 PM, Alan Gauld wrote: > > "Advertising Department" wrote > >> ?repeat WHILE >> is exactly what I needed. >> >> I got BASIC stuck in my head. GOTO line# YUCK! > > BASIC has a WHILE/WEND construct too :-) > Even GW Basic supported that. > > Alan G. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Jun 15 09:44:15 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Jun 2010 08:44:15 +0100 Subject: [Tutor] Structuring a class References: <4C16C486.70804@tharin.com> Message-ID: "Lang Hurst" wrote > I'm trying to figure out how to deal with data which will look > something like: > > Student:Bob Hurley > Credits: > Algebra C (20P) > Chapter 1 > Chapter 2 > Consumer Math (24G) > Module 2 > > So, I just figured that I would have a couple of nested > dictionaries. Or 3 classes: Student, Credit, Module But classses will be most useful if you are doing a lot of interaction between the students or calculations based on the credits. As Bob suggested, if you mainly just want to add/delete/modify and report on the data a database is a better bet. You mght still create a Student class to structure the data coming back from the database but the other classes will probably be overkill and your double dict will be as effective. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pedrooconnell at gmail.com Tue Jun 15 14:27:43 2010 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 15 Jun 2010 21:57:43 +0930 Subject: [Tutor] conventions for establishing and saving default values for variables Message-ID: Hi I was wondering if anyone could give me some insight as to the best way to get and save variables from a user the first time a script is opened. For example if the script prompts something like "What is the path to the folder?" and the result is held in a variable called thePath, what is the best way to have that variable saved for all subsequent uses of the script by the same user. Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Jun 15 15:02:22 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 15 Jun 2010 15:02:22 +0200 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: References: Message-ID: <4C1779DE.6070408@compuscan.co.za> Pete O'Connell wrote: > Hi I was wondering if anyone could give me some insight as to the best > way to get and save variables from a user the first time a script is > opened. For example if the script prompts something like "What is the > path to the folder?" and the result is held in a variable called > thePath, what is the best way to have that variable saved for all > subsequent uses of the script by the same user. > Pete > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ConfigParser can read/write config files or using Pickle/cPickle to save & load your variables or using something like JSON (JavaScript Object Notation) will do what you want. For something like just storing a path for future use using ConfigParser would be perfectly suited to the task. import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read('options.cfg') if not cfg.sections(): work_path = raw_input('Please enter the workspace path: ') cfg.add_section('PATH') cfg.set('PATH', 'workspace', work_path) f = open('options.cfg', 'w') cfg.write(f) f.close() else: work_path = cfg.get('PATH', 'workspace') -- Kind Regards, Christian Witts From hugo.yoshi at gmail.com Tue Jun 15 15:04:55 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 15 Jun 2010 15:04:55 +0200 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: References: Message-ID: On Tue, Jun 15, 2010 at 2:27 PM, Pete O'Connell wrote: > Hi I was wondering if anyone could give me some insight as to the best way > to get and save variables from a user the first time a script is opened. For > example if the script prompts something like "What is the path to the > folder?" and the result is held in a variable called thePath, what is the > best way to have that variable saved for all subsequent uses of the script > by the same user. > Pete In UNIX-likes, It would be a configuration file in their home directory, I suppose. Under windows, probably the registry. There's the _winreg and configparser modules. Hugo From steve at pearwood.info Tue Jun 15 15:40:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Jun 2010 23:40:38 +1000 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: References: Message-ID: <201006152340.38925.steve@pearwood.info> On Tue, 15 Jun 2010 10:27:43 pm Pete O'Connell wrote: > Hi I was wondering if anyone could give me some insight as to the > best way to get and save variables from a user the first time a > script is opened. For example if the script prompts something like > "What is the path to the folder?" and the result is held in a > variable called thePath, what is the best way to have that variable > saved for all subsequent uses of the script by the same user. Others have already mentioned ConfigParser. You should also check out plistlib, in the standard library since version 2.6. Other alternatives include pickle, XML, JSON or YAML (although since YAML is not part of the standard library, you will need to download a package for it). On Windows you can write to the registry, although since I'm not a Windows user I don't know how. Or if your config is simple enough, you can just write your data to the file manually. But honestly, you can't get much simpler than ConfigParser or plistlib. -- Steven D'Aprano From jeff at dcsoftware.com Tue Jun 15 17:18:54 2010 From: jeff at dcsoftware.com (Jeff Johnson) Date: Tue, 15 Jun 2010 08:18:54 -0700 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: <201006152340.38925.steve@pearwood.info> References: <201006152340.38925.steve@pearwood.info> Message-ID: <4C1799DE.8000105@dcsoftware.com> Steven D'Aprano wrote: > On Tue, 15 Jun 2010 10:27:43 pm Pete O'Connell wrote: > >> Hi I was wondering if anyone could give me some insight as to the >> best way to get and save variables from a user the first time a >> script is opened. For example if the script prompts something like >> "What is the path to the folder?" and the result is held in a >> variable called thePath, what is the best way to have that variable >> saved for all subsequent uses of the script by the same user. >> > > Others have already mentioned ConfigParser. You should also check out > plistlib, in the standard library since version 2.6. > > Other alternatives include pickle, XML, JSON or YAML (although since > YAML is not part of the standard library, you will need to download a > package for it). On Windows you can write to the registry, although > since I'm not a Windows user I don't know how. Or if your config is > simple enough, you can just write your data to the file manually. But > honestly, you can't get much simpler than ConfigParser or plistlib. > > > > On Windows I create an ".ini" file in the user profile instead of the registry. Windows API has GetPrivateProfileString and WritePrivateProfileString. On Linux I use ConfigParser to read and write to an ".ini" file in the home directory. I have avoided the Windows registry completely. Obviously you could use ConfigParser on Windows because of Python. -- Jeff ------------------- Jeff Johnson jeff at dcsoftware.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From juhasecke at googlemail.com Tue Jun 15 19:26:15 2010 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Tue, 15 Jun 2010 19:26:15 +0200 Subject: [Tutor] What's the catch with ZopeDB? In-Reply-To: <4C1291AB.40804@googlemail.com> References: <4C1291AB.40804@googlemail.com> Message-ID: Am 11.06.10 21:42, schrieb Knacktus: > So, has anyone experience with ZopeDB? Are there some drawbacks I should > be aware of before getting a book and dive in? (It sounds too good ;-)) You can easily use the ZODB to create pure python applications. There are some tutorials around, like this one: http://www.zodb.org/documentation/tutorial.html Check out: http://www.zodb.org/ The Zope Community uses the ZODB for several mission critical applications like content management systems and other very huge web applications. There are no drawbacks I heard of, but it all depends on your usecase. juh From alan.gauld at btinternet.com Tue Jun 15 19:49:40 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Jun 2010 18:49:40 +0100 Subject: [Tutor] conventions for establishing and saving default values forvariables References: Message-ID: "Pete O'Connell" wrote > Hi I was wondering if anyone could give me some insight as to the > best way > to get and save variables from a user the first time a script is > opened. For > example if the script prompts something like "What is the path to > the > folder?" and the result is held in a variable called thePath, what > is the > best way to have that variable saved for all subsequent uses of the > script > by the same user. Others have mentioned ini files on Windows and resource files in *nix as well as other options. Another option depending on the purpose might be an environment variable. But that would normally only be used to, for example, set a path to where the ini file was located - especially if it wasn't in the default location, maybe being shared by a user group, say. So it depends on the function of your variable too. Personally I'd go with an ini/resource file in the users home directory as being the most consistent and simplest solution. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From hgfernan at gmail.com Tue Jun 15 20:17:31 2010 From: hgfernan at gmail.com (Hilton Fernandes) Date: Tue, 15 Jun 2010 15:17:31 -0300 Subject: [Tutor] Structuring a class In-Reply-To: References: <4C16C486.70804@tharin.com> Message-ID: inded, a relational database is the best bet here. however, a direct implementation in Python may need less previous knowledge. On Tue, Jun 15, 2010 at 4:44 AM, Alan Gauld wrote: > "Lang Hurst" wrote > >> I'm trying to figure out how to deal with data which will look something >> like: >> >> ? Student:Bob Hurley >> ? Credits: >> ? ? ?Algebra C (20P) >> ? ? ? ? ? ?Chapter 1 >> ? ? ? ? ? ?Chapter 2 >> ? ? ?Consumer Math (24G) >> ? ? ? ? ? ?Module 2 >> >> So, I just figured that I would have a couple of nested dictionaries. > > Or 3 classes: Student, Credit, Module > > But classses will be most useful if you are doing a lot of > interaction between the students or calculations based on the credits. > > As Bob suggested, if you mainly just want to add/delete/modify > and report on the data a database is a better bet. > > You mght still create a Student class to structure the data > coming back from the database but the other classes will > probably be overkill and your double dict will be as effective. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From jf_byrnes at comcast.net Tue Jun 15 22:39:27 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 15 Jun 2010 15:39:27 -0500 Subject: [Tutor] Tkinter - master attribute In-Reply-To: References: <4C0E7204.6080908@comcast.net> Message-ID: <4C17E4FF.6020705@comcast.net> Alan Gauld wrote: > > "Jim Byrnes" wrote in > >> When reading code examples I see things like > >> theframe.master.title('spam) > >> def __init__(self, master): >> frame = Frame(master) > >> When I encounter these I tend to get bogged down trying to decide if >> "master" has special meaning or is just a name the author has chosen. > > In the first case master is an attribute of the frame and as > such is defined by the frame definition. > > In the second case master is just an arbitrary name for a > parameter like any other. Because it is being used to correspond > to the master attribute of the Framer(as seen in the call to Frame() ) > the author has used the name master too. But other common > names for the same attribute are parent, root, top, etc > >> For example is it similar to Buttton(text='spam) where text in this >> case has special meaning. > > In the first example yes, in the second no. > Although 'text' is even more special because it is actually defined in > the underlying Tk code rather than in Tkinter Python code. > >> I've goolged and found references to "widgets master attributes" but >> nothing to really explain it. Could someone point me to a good >> reference so that I could better understand it use. > > Because Tkinter is a thin wrapper around the underlying Tk tookit > many atttributes of widgets are actually defined in the Tk code > and simply mirrored by Tkinter. In that sense the widget attributes > tend to have fixed names. But in Tkinter code the naming is > essentially arbitrary and follows the usual Python naming > conventions. > > HTH, > Alan, Sorry it took so long for me to get back to this issue. Thanks to you and Steve for your replies. I still am having trouble understanding the use of "master" in Tkinter. I think the problem is I can't find any reference that explains the concept around master, like the Button example I gave above. If I want to put the word spam on a Button I found a reference that said you type the word text followed by an equal sign followed by spam in quotes. Let me try another example. The code snippet below comes from a working example out of a book: class CanvasEventsDemo(canvasDraw.CanvasEventsDemo): def __init__(self, parent=None): canvasDraw.CanvasEventsDemo.__init__(self, parent) self.canvas.create_text(75, 8, text='Press o and r to move shapes') self.canvas.master.bind('', self.onMoveOvals) self.canvas.master.bind('', self.onMoveRectangles) self.kinds = self.create_oval_tagged, self.create_rectangle_tagged The word master appears only twice in the entire script so it is not defined somewhere else in the script. As an experiment I changed them both to masterx. When I ran the script I got the following error: Traceback (most recent call last): File "canvasDraw_tags.py", line 41, in CanvasEventsDemo() File "canvasDraw_tags.py", line 16, in __init__ self.canvas.masterx.bind('', self.onMoveOvals) AttributeError: Canvas instance has no attribute 'masterx' So the Canvas does not have a masterx attribute but does have one called master. Maybe the bottom line question is where can I look to see a list of a widgets attributes? Sorry to be so dense about this but I just don't get it yet. Thanks, Jim From alan.gauld at btinternet.com Wed Jun 16 02:30:31 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 16 Jun 2010 00:30:31 +0000 (GMT) Subject: [Tutor] Tkinter - master attribute In-Reply-To: <4C17E4FF.6020705@comcast.net> References: <4C0E7204.6080908@comcast.net> <4C17E4FF.6020705@comcast.net> Message-ID: <428097.47271.qm@web86702.mail.ird.yahoo.com> > I still am having trouble understanding the use of "master" in > Tkinter. I think the problem is I can't find any reference that explains the > concept around master, If you read the GUI topic in my tutorial it explains the concept of a containment tree that is common to ost GUI frameworks including Tkinter. All widgets belong to a parent or master widget until you get to some kind of root or main window that is the master odf all its sub widgets. When you delete a window you delete the master and it deletes all its children. The children delete their children, and so on until all the widgets making up the window are deleted. Thats how GUIs work. Similarly if you add a widget to a window you must tell the new widget where within the containment tree it sits, you tell it who its master is. Usually the widget will register itself with its master. > put the word spam on a Button I found a reference that said you type the word > text followed by an equal sign followed by spam in quotes. That's slightly different in that text is an attribute of the widget itself. By assigning 'Spam' to the attribute you control the look of that particular Button widget. class CanvasEventsDemo(canvasDraw.CanvasEventsDemo): def __init__(self, parent=None): canvasDraw.CanvasEventsDemo.__init__(self, parent) Here parent is being used instead of master. Thats quite common. > self.canvas.master.bind('', self.onMoveOvals) Here the master attribute is being accessed. That is an attribute of the canvas widget. > word master appears only twice in the entire script so it is not defined > somewhere else in the script. It is an inherited attribute and is inherited by all widgets although from where is a little bit mysterious - see below... > AttributeError: Canvas instance has no attribute > 'masterx' > > So the Canvas does not have a masterx attribute but does have > one called master. Maybe the bottom line question is where can I look to > see a list of a widgets attributes? You can use dir() or help(). However in Tkinter it is further complicated by the mapping of Tkinter to the underlying Tk widgets. It is not always 1-1 and some attributes are implemented by the Tk tookit rather than at the Tkinter level and these do not always show up in dir(). Master appears to be one of these. However, on digging a little deeper it seems there is a subtle distinction in Tkinter between the containment hierarchy and the geometry manager hierarchy. I confess that I've never noticed this before and have only skimmed the material(Grayson's Tkinter book) but it seems that master refers to the GM hierarchy and parent to the containment one. In most cases they will be the same but they can be different. But because of this master seems to be implemented somewhere in the GM code rather than the widget code... In most cases you can ignore that - as I have been doing for the last 10 years! :-) Just use master as an inherited attribute that is present in all widgets. > Sorry to be so dense about this but I just don't get it yet. You are not being dense but asking rather deep questions which probably need someone who understands the Tkinter implementatioon to answer. You probably don't really need to know the detail, just accept that master will be the attribute and it will be there in each widget class you use. If I get the time I will try to track this down further now that you have piqued my curiosity. HTH, Alan G. From david.fockens at gmail.com Wed Jun 16 03:21:39 2010 From: david.fockens at gmail.com (David) Date: Tue, 15 Jun 2010 18:21:39 -0700 Subject: [Tutor] Passing arguments to CGI script Message-ID: <20100615182139.0593dd38@gmail.com> Hi, I'm trying to pass arguments to a python script running on my webserver. Here is the script: import cgi import cgitb import sys cgitb.enable() form = cgi.FieldStorage() title = form.getvalue("title") print """Content-type: text/html """ print form.keys() print """ """ When I run it on the website like http://mf-doom.com/album.py?title=blah it just prints out an empty array. Is there something wrong with my code? Or is there something wrong with the way my server's configured? From amonroe at columbus.rr.com Wed Jun 16 13:39:44 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 16 Jun 2010 07:39:44 -0400 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: References: Message-ID: <193806680405.20100616073944@columbus.rr.com> > On Tue, Jun 15, 2010 at 2:27 PM, Pete O'Connell wrote: >> Hi I was wondering if anyone could give me some insight as to the best way >> to get and save variables from a user the first time a script is opened. For >> example if the script prompts something like "What is the path to the >> folder?" and the result is held in a variable called thePath, what is the >> best way to have that variable saved for all subsequent uses of the script >> by the same user. >> Pete > In UNIX-likes, It would be a configuration file in their home > directory, I suppose. Under windows, probably the registry. There's > the _winreg and configparser modules. Consider using the %USERPROFILE% environment variable rather than the registry. Alan From alan.gauld at btinternet.com Wed Jun 16 19:25:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Jun 2010 18:25:03 +0100 Subject: [Tutor] conventions for establishing and saving default valuesfor variables References: <193806680405.20100616073944@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote >> directory, I suppose. Under windows, probably the registry. There's >> the _winreg and configparser modules. > > Consider using the %USERPROFILE% environment variable rather than > the > registry. How would that work? That is just a single variable that points to the users Settings folder. Effectively their home directory in unix terms, so you could store the config file there. But you couldn't store the kind of data you would store in the registry? I'm confused. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jeff at dcsoftware.com Wed Jun 16 19:44:58 2010 From: jeff at dcsoftware.com (Jeff Johnson) Date: Wed, 16 Jun 2010 10:44:58 -0700 Subject: [Tutor] conventions for establishing and saving default values for variables In-Reply-To: References: Message-ID: <4C190D9A.3010403@dcsoftware.com> Pete O'Connell wrote: > Hi I was wondering if anyone could give me some insight as to the best > way to get and save variables from a user the first time a script is > opened. For example if the script prompts something like "What is the > path to the folder?" and the result is held in a variable called > thePath, what is the best way to have that variable saved for all > subsequent uses of the script by the same user. > Pete > ------------------------------------------------------------------------ > > I will send you my python script that reads and writes to a windows style .ini file if you want me to. -- Jeff ------------------- Jeff Johnson jeff at dcsoftware.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Wed Jun 16 22:39:44 2010 From: knacktus at googlemail.com (Knacktus) Date: Wed, 16 Jun 2010 22:39:44 +0200 Subject: [Tutor] How to model objects aimed to persistence? Message-ID: <4C193690.5070103@googlemail.com> Hi everyone, within a python application I can easily model object association with simple references, e.g.: ################################################################# class FavoritMovies(object): def __init__(self, movies): self.movies = movies class Movie(object): def __init__(self, name, actor): self.name = name self.actor = actor gladiator = Movie("Gladiator", "Russel Crowe") my_favorit_movies = FavoritMovies([gladiator]) kung_fu_panda = Movie("Kung Fu Panda", "Jack Black") your_favorit_movies = FavoritMovies([gladiator, kung_fu_panda]) ################################################################## So far, so good. But what is best practise to prepare this data for general persistence? It should be usable for serialisation to xml or storing to an RDBMS or ObjectDatabase ... I guess I have to incorporate some kind of id for every object and use this as reference with some kind of look-up dictionary, but I wouldn't like it and hope that there're some other sweet pythonic solutions? Cheers, Jan From breamoreboy at yahoo.co.uk Wed Jun 16 23:07:11 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 16 Jun 2010 22:07:11 +0100 Subject: [Tutor] How to model objects aimed to persistence? In-Reply-To: <4C193690.5070103@googlemail.com> References: <4C193690.5070103@googlemail.com> Message-ID: On 16/06/2010 21:39, Knacktus wrote: > Hi everyone, > > within a python application I can easily model object association with > simple references, e.g.: > > ################################################################# > class FavoritMovies(object): > def __init__(self, movies): > self.movies = movies > > class Movie(object): > def __init__(self, name, actor): > self.name = name > self.actor = actor > > gladiator = Movie("Gladiator", "Russel Crowe") > my_favorit_movies = FavoritMovies([gladiator]) > > kung_fu_panda = Movie("Kung Fu Panda", "Jack Black") > your_favorit_movies = FavoritMovies([gladiator, kung_fu_panda]) > ################################################################## > > So far, so good. But what is best practise to prepare this data for > general persistence? It should be usable for serialisation to xml or > storing to an RDBMS or ObjectDatabase ... > > I guess I have to incorporate some kind of id for every object and use > this as reference with some kind of look-up dictionary, but I wouldn't > like it and hope that there're some other sweet pythonic solutions? > > Cheers, > > Jan > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi Jan, I guess you're looking for something like the shelve or pickle modules. http://docs.python.org/library/shelve.html http://docs.python.org/library/pickle.html HTH. Mark Lawrence. From steve at pearwood.info Thu Jun 17 00:52:26 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jun 2010 08:52:26 +1000 Subject: [Tutor] =?utf-8?q?conventions_for_establishing_and_saving_default?= =?utf-8?q?_values_for=09variables?= In-Reply-To: <4C190D9A.3010403@dcsoftware.com> References: <4C190D9A.3010403@dcsoftware.com> Message-ID: <201006170852.27699.steve@pearwood.info> On Thu, 17 Jun 2010 03:44:58 am Jeff Johnson wrote: > I will send you my python script that reads and writes to a windows > style .ini file if you want me to. How is your script different from the standard ConfigParser module? -- Steven D'Aprano From steve at pearwood.info Thu Jun 17 01:19:58 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jun 2010 09:19:58 +1000 Subject: [Tutor] conventions for establishing and saving default valuesfor variables In-Reply-To: References: <193806680405.20100616073944@columbus.rr.com> Message-ID: <201006170919.58630.steve@pearwood.info> On Thu, 17 Jun 2010 03:25:03 am Alan Gauld wrote: > "R. Alan Monroe" wrote > > >> directory, I suppose. Under windows, probably the registry. > >> There's the _winreg and configparser modules. > > > > Consider using the %USERPROFILE% environment variable rather than > > the > > registry. > > How would that work? That is just a single variable that points > to the users Settings folder. Effectively their home directory in > unix terms, so you could store the config file there. But > you couldn't store the kind of data you would store in the > registry? > > I'm confused. Environment variables are not permanent storage. They only exist in RAM unless you take steps to recreate them from permanent storage. Under Linux, for example, environment variables are recreated each time you log in after being read from a config file, such as .bashrc. My .bashrc includes: export PYTHONPATH=/home/steve/python/ export PYTHONSTARTUP=/home/steve/python/startup.py So even if you wrote the values you cared about to one or more environment variable, they would disappear as soon as the user logged out or rebooted. It gets worse... Python includes the command os.putenv to set environment variables, but they are only set for subprocesses of the Python process that sets them. So for example, I can do this: >>> os.putenv('myenvvar', 'value') >>> os.system('echo $myenvvar') value 0 but if I turn to another shell (not a subshell) it doesn't exist: [steve at sylar ~]$ echo $myenvvar [steve at sylar ~]$ See also this: http://code.activestate.com/recipes/159462-how-to-set-environment-variables/ So unless I've missed something exceedingly subtle, writing to environment variables is not a solution to the problem of saving default values. It's not even part of a solution. -- Steven D'Aprano From steve at pearwood.info Thu Jun 17 01:47:13 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jun 2010 09:47:13 +1000 Subject: [Tutor] How to model objects aimed to persistence? In-Reply-To: <4C193690.5070103@googlemail.com> References: <4C193690.5070103@googlemail.com> Message-ID: <201006170947.14116.steve@pearwood.info> On Thu, 17 Jun 2010 06:39:44 am Knacktus wrote: > So far, so good. But what is best practise to prepare this data for > general persistence? It should be usable for serialisation to xml or > storing to an RDBMS or ObjectDatabase ... Oh wow, deja vu... this is nearly the same question as just asked a day or so ago, in the thread "conventions for establishing and saving default values for?variables". The answer I give will be more or less the same as was already given in that thread: Use ConfigParser for ini-style config files. Use pickle or shelve for serialising arbitrary Python objects. You probably shouldn't use marshal, as that's awfully limited and really only designed for serialising Python byte code. You can roll your own XML solution using the various XML modules in the standard library, or use plistlib, an XML-based storage format borrowed from Mac OS X. Or one of the other standard serialisers like JSON or YAML, although YAML is not in the standard library yet. Or you can use any one of many different databases, although that's probably massive overkill. > I guess I have to incorporate some kind of id for every object and > use this as reference with some kind of look-up dictionary, "Have to"? Certainly not. If your data doesn't need an ID field, there's no need to add one just for serialisation. It would be a pretty bizarre serialiser that couldn't handle this: {key: value} but could handle this: ({id: key}, {key: value}) > but I > wouldn't like it and hope that there're some other sweet pythonic > solutions? There's a few... :) By the way, looking at your class name: class FavoritMovies(object): I can forgive the American (mis)spelling of Favo(u)rite, but why have you dropped the E off the end of "favorite"? I'd almost think your keyboard was broken, but no, you have E in Movies and object. Deliberate misspellings in class and variable names will cost you *far* more in debugging time when you forget to misspell the words than they will save you in typing. Trust me on this. -- Steven D'Aprano From alan.gauld at btinternet.com Thu Jun 17 02:17:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jun 2010 01:17:13 +0100 Subject: [Tutor] How to model objects aimed to persistence? References: <4C193690.5070103@googlemail.com> <201006170947.14116.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Deliberate misspellings in class and variable names > will cost you *far* more in debugging time when you > forget to misspell the words than they will save you > in typing. Trust me on this. I don't normally do "me too" postings but this is such a big deal that I just have to concur with Steven. It doesn't matter too much if you abbreviate local variables but anything that might be exposed at the module level and visible across imports should be spelled in full. It will only cause grief and pain later, if not to you then to anyone who imports your code... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jf_byrnes at comcast.net Thu Jun 17 04:35:07 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 16 Jun 2010 21:35:07 -0500 Subject: [Tutor] Tkinter - master attribute In-Reply-To: <428097.47271.qm@web86702.mail.ird.yahoo.com> References: <4C0E7204.6080908@comcast.net> <4C17E4FF.6020705@comcast.net> <428097.47271.qm@web86702.mail.ird.yahoo.com> Message-ID: <4C1989DB.2010009@comcast.net> ALAN GAULD wrote: > > >> I still am having trouble understanding the use of "master" in >> Tkinter. I think the problem is I can't find any reference that explains the >> concept around master, > > If you read the GUI topic in my tutorial it explains the concept > of a containment tree that is common to ost GUI frameworks > including Tkinter. All widgets belong to a parent or master > widget until you get to some kind of root or main window that > is the master odf all its sub widgets. I'll make it my next stop. > When you delete a window you delete the master and it deletes > all its children. The children delete their children, and so on until > all the widgets making up the window are deleted. Thats how GUIs work. > Similarly if you add a widget to a window you must tell the new > widget where within the containment tree it sits, you tell it who > its master is. Usually the widget will register itself with its master. > >> put the word spam on a Button I found a reference that said you type the word >> text followed by an equal sign followed by spam in quotes. > > That's slightly different in that text is an attribute of the widget itself. > By assigning 'Spam' to the attribute you control the look of that particular > Button widget. OK. That was the best example I could come up with to convey my confusion concerning master. I could look at a reference and see that in that context the word text had a special purpose, I couldn't do that with master. > class CanvasEventsDemo(canvasDraw.CanvasEventsDemo): > def __init__(self, parent=None): > canvasDraw.CanvasEventsDemo.__init__(self, parent) > > Here parent is being used instead of master. Thats quite common. Its usage like this that tends to confuse me. If I change all occurrences of of parent to Xparent the program runs. If I replace parent with master the program runs. If I replace canvas.master with canvas.xmaster I get an error. >> self.canvas.master.bind('', self.onMoveOvals) > > Here the master attribute is being accessed. That is an attribute > of the canvas widget. > >> word master appears only twice in the entire script so it is not defined >> somewhere else in the script. > > It is an inherited attribute and is inherited by all widgets > although from where is a little bit mysterious - see below... > >> AttributeError: Canvas instance has no attribute >> 'masterx' >> >> So the Canvas does not have a masterx attribute but does have >> one called master. Maybe the bottom line question is where can I look to >> see a list of a widgets attributes? > > You can use dir() or help(). > However in Tkinter it is further complicated by the mapping of Tkinter > to the underlying Tk widgets. It is not always 1-1 and some attributes > are implemented by the Tk tookit rather than at the Tkinter level and > these do not always show up in dir(). Master appears to be one of these. > > However, on digging a little deeper it seems there is a subtle distinction > in Tkinter between the containment hierarchy and the geometry manager > hierarchy. I confess that I've never noticed this before and have only > skimmed the material(Grayson's Tkinter book) but it seems that master > refers to the GM hierarchy and parent to the containment one. In most > cases they will be the same but they can be different. But because of > this master seems to be implemented somewhere in the GM code > rather than the widget code... > > In most cases you can ignore that - as I have been doing for the last 10 years! :-) > Just use master as an inherited attribute that is present in all widgets. OK, good. This is what I was looking for, an explicit statement of what master is. >> Sorry to be so dense about this but I just don't get it yet. > > You are not being dense but asking rather deep questions which > probably need someone who understands the Tkinter implementatioon > to answer. You probably don't really need to know the detail, just accept > that master will be the attribute and it will be there in each widget class > you use. I really wasn't trying to delve deep into the innards of Tkinter, it just seemed like master was appearing like magic and I just wanted to nail it down so I could get on learning Python. > If I get the time I will try to track this down further now that you have > piqued my curiosity. > > HTH, It does, I finally feel like I have a handle on it. Thanks for your time and patience. Regards, Jim > Alan G. > From payal-python at scriptkitchen.com Thu Jun 17 04:48:19 2010 From: payal-python at scriptkitchen.com (Payal) Date: Wed, 16 Jun 2010 19:48:19 -0700 Subject: [Tutor] pickling/shelve classes Message-ID: <20100617024819.GA8835@scriptkitchen.com> Hi all, Can someone please help in this below? class F(object) : ...: def __init__(self, amt) : self.amt = amt ...: def dis(self) : print 'Amount : ', self.amt ...: def add(self, na) : ...: self.amt += na ...: F.dis(self) pickle.dumps(F) gives PicklingError: Can't pickle : it's not found as __main__.F What is my mistake? I want to pickle and shelve classes as well as instances. With warm regards, -Payal -- From knacktus at googlemail.com Thu Jun 17 06:07:26 2010 From: knacktus at googlemail.com (Knacktus) Date: Thu, 17 Jun 2010 06:07:26 +0200 Subject: [Tutor] How to model objects aimed to persistence? In-Reply-To: References: <4C193690.5070103@googlemail.com> <201006170947.14116.steve@pearwood.info> Message-ID: <4C199F7E.1080201@googlemail.com> Am 17.06.2010 02:17, schrieb Alan Gauld: > "Steven D'Aprano" wrote >> Deliberate misspellings in class and variable names will cost you >> *far* more in debugging time when you forget to misspell the words >> than they will save you in typing. Trust me on this. Thanks for that hint. I can imagine the nightmares ... It was just a spelling mistake. English is not my native language and I sometime tend to skip trailing "e"s ;-). But I think I need to clarify my question a bit. The point I'm unsure with is how to best model references in python for persistence when not using pickle or any dedicated python. Python doesn't even need names as reference to the objects location in memory. I could do something like this: ########################################################################### my_favourite_movies = FavouriteMovies([Movie("Gladiator", "Russel Crowe")]) ########################################################################### When I want to rebuild the data from a xml file or database, my objects somehow need to know which references to other objects they hold. I don't now wether I have to use explicit indices in my python code to make it "xml-ready" and if that's the case, how to do it smoothly. Or whether there's some other trick. Cheers, Jan From nbr1ninrsan7 at yahoo.com Thu Jun 17 09:10:32 2010 From: nbr1ninrsan7 at yahoo.com (Independent Learner) Date: Thu, 17 Jun 2010 00:10:32 -0700 (PDT) Subject: [Tutor] Importing files not located on the home directory or standardard library Message-ID: <962622.95064.qm@web120013.mail.ne1.yahoo.com> I am having trouble figuring out how to import modules not located on the home directory or standard library of modules. Meaning say I write a module and instead of saving it on the home directory I save in a folder in my desktop. I do not know how to retrieve it by way of the import statement. I know it has something to do with the PYTHONPATH or .pth,? however I am not sure how to configure these, right now I am reading Learning Pythong 3rd ed. by Mark Lutz and unfortnately that book has a lot more words then examples so I am usually left to figure alot of the concepts myself while rereading word for word to try to figure out how the heck it applies to IDLE and practical uses for code. I thoroughly understand modules and how to import them when they are in the home directory or standard library, thats pretty simple, however like I said I do not know how to import files outside of these directories. I am using windows 7 and python 2.6.5 Lets say I want to load a file called quiz located in C:\Users\Julius Hernandez\Desktop\Python2.6.5\Online Course\Chp.4 How would I configure PYTHONPATH or .pth? or what ever to import this file from IDLE I am also having slight trouble understanding module packages as well, though I suspect it has something to do with not knowing how to configure PYTHONPATH or .pth files Thanks =) ~Julius H. -------------- next part -------------- An HTML attachment was scrubbed... URL: From k247d0 at gmail.com Thu Jun 17 09:28:37 2010 From: k247d0 at gmail.com (KB SU) Date: Thu, 17 Jun 2010 00:28:37 -0700 Subject: [Tutor] help Message-ID: help -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Thu Jun 17 11:11:11 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 17 Jun 2010 11:11:11 +0200 Subject: [Tutor] pickling/shelve classes In-Reply-To: <20100617024819.GA8835@scriptkitchen.com> References: <20100617024819.GA8835@scriptkitchen.com> Message-ID: <201006171111.11757.eike.welk@gmx.net> Hello Payal! On Thursday June 17 2010 04:48:19 Payal wrote: > Hi all, > Can someone please help in this below? > > class F(object) : > ...: def __init__(self, amt) : self.amt = amt > ...: def dis(self) : print 'Amount : ', self.amt > ...: def add(self, na) : > ...: self.amt += na > ...: F.dis(self) > > pickle.dumps(F) > gives PicklingError: Can't pickle : it's not found > as __main__.F I think it is a bug in IPython: I can do this in regular Python, but in IPython I get the same error that you get: Python 2.6.2 (r262:71600, Mar 29 2010, 15:30:01) [GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object):pass ... >>> import pickle >>> pickle.dumps(A) 'c__main__\nA\np0\n.' >>> You should file a bug report in their bug tracker: http://github.com/ipython/ipython/issues Eike. From modulok at gmail.com Thu Jun 17 11:23:57 2010 From: modulok at gmail.com (Modulok) Date: Thu, 17 Jun 2010 03:23:57 -0600 Subject: [Tutor] help In-Reply-To: References: Message-ID: Solution: width times height. On 6/17/10, KB SU wrote: > help > From modulok at gmail.com Thu Jun 17 11:25:57 2010 From: modulok at gmail.com (Modulok) Date: Thu, 17 Jun 2010 03:25:57 -0600 Subject: [Tutor] Trouble with sockets... Message-ID: List, I'm new to sockets and having trouble. I tried to write a simple client/server program (see code below). The client would send a string to the server. The server would echo that back to the client. PROBLEM: I can send data to the server, and get data back, but only for the first call to the 'sendall()' method. If I try to call it in a loop on the client, to print a count-down, only the first call gets echoed. Clearly, I'm missing something. EXAMPLE: (They're on the same physical machine.) Shell on the server: Modulok at modUnix> ./socket_server.py Listening for clients... Got connection from 192.168.1.1 Shell on the client: Modulok at modUnix> ./latency_client.py 192.168.1.1 2554 0 What I wanted: [-]Modulok at modUnix> ./latency_client.py 192.168.1.1 2554 0 1 2 CODE: ################################ # The client program: ################################ import socket import sys def main(): '''Send data to a server and receive the data echoed back to us.''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect( ('192.168.1.1', 2554) ) for i in range(3): s.sendall(str(i)) print s.recv(1024) s.close() # Execution starts here: try: main() except KeyboardInterrupt: sys.exit("Aborting.") ################################ # The server program: ################################ import socket import sys def main(): '''Listen for a client and echo data back to them.''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind( ('192.168.1.1', 2554) ) s.listen(5) print "Listening for clients..." while True: channel, client = s.accept() print "Got connection from %s" % client[0] message = channel.recv(1024) channel.send(message) channel.close() # Execution starts here: try: main() except KeyboardInterrupt: sys.exit("Aborting.") From hugo.yoshi at gmail.com Thu Jun 17 13:13:55 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 17 Jun 2010 13:13:55 +0200 Subject: [Tutor] conventions for establishing and saving default valuesfor variables In-Reply-To: <201006170919.58630.steve@pearwood.info> References: <193806680405.20100616073944@columbus.rr.com> <201006170919.58630.steve@pearwood.info> Message-ID: On Thu, Jun 17, 2010 at 1:19 AM, Steven D'Aprano wrote: > On Thu, 17 Jun 2010 03:25:03 am Alan Gauld wrote: >> "R. Alan Monroe" wrote >> >> >> directory, I suppose. Under windows, probably the registry. >> >> There's the _winreg and configparser modules. >> > >> > Consider using the %USERPROFILE% environment variable rather than >> > the >> > registry. >> >> How would that work? That is just a single variable that points >> to the users Settings folder. Effectively their home directory in >> unix terms, so you could store the config file there. But >> you couldn't store the kind of data you would store in the >> registry? >> >> I'm confused. > > [snip explanation of environment variables] > > So unless I've missed something exceedingly subtle, writing to > environment variables is not a solution to the problem of saving > default values. It's not even part of a solution. > Just speculation here, but.. I suppose what he's suggesting is that you use ConfigParser on both linux and windows, rather than the registry on one platform and a config file on the other. on windows you'd then place the config file in the %USERPROFILE% directory. It's actually a rather good idea, not having to bother with the registry saves you a lot of work. Hugo From steve at pearwood.info Thu Jun 17 14:20:24 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jun 2010 22:20:24 +1000 Subject: [Tutor] help In-Reply-To: References: Message-ID: <201006172220.25156.steve@pearwood.info> On Thu, 17 Jun 2010 05:28:37 pm KB SU wrote: > help No no, don't tell us what you need help about! I love guessing games! Let me see now... I'm guessing that your problem is that don't know how to work out the length of a string. Here's one way: string = "something" count = 1 for char in string: count *= 10 import math print "The string has", math.log10(count), "characters." There's probably a shorter way too. -- Steven D'Aprano From breamoreboy at yahoo.co.uk Thu Jun 17 14:30:08 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 Jun 2010 13:30:08 +0100 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 17/06/2010 08:28, KB SU wrote: > help > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Help, I need somebody, Help, not just anybody, Help, you know I need someone, help. I'll leave you to find out the rests of the lyrics. :) Mark Lawrence. From alan.gauld at btinternet.com Thu Jun 17 19:14:16 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jun 2010 18:14:16 +0100 Subject: [Tutor] How to model objects aimed to persistence? References: <4C193690.5070103@googlemail.com> <201006170947.14116.steve@pearwood.info> <4C199F7E.1080201@googlemail.com> Message-ID: "Knacktus" wrote ########################################################################### > my_favourite_movies = FavouriteMovies([Movie("Gladiator", "Russel > Crowe")]) > ########################################################################### > > When I want to rebuild the data from a xml file or database, my > objects somehow need to know which references to other objects they > hold. OK, If you limit yourself to XML or a database then yes you will need an ID and use the IDs as references. Thats why Pickle/Shelve are so convenient for persistence - they don;t need the references, you can just pickle the list of objects, or whatever. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 17 19:21:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jun 2010 18:21:59 +0100 Subject: [Tutor] Importing files not located on the home directory orstandardard library References: <962622.95064.qm@web120013.mail.ne1.yahoo.com> Message-ID: "Independent Learner" wrote > Lets say I want to load a file called quiz located in > C:\Users\Julius > Hernandez\Desktop\Python2.6.5\Online Course\Chp.4 > > How would I configure PYTHONPATH or .pth or what ever > to import this file from IDLE The IDLE bit is irrelevant its how the underlying Python interpreter does things that matters. You would need to set your PYTHONPATH environment variable to include the directory containing your modules. Do you know how to add values to a Windows Environment variable? If not go to the Getting Started topic of my tutor for an example of setting the PATH variable (You do the same but for PYTHONPATH, the only difference is you might need to create it if it doesn't already exist!) Otherwise, Where are you having problems? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lowelltackett at yahoo.com Thu Jun 17 20:22:20 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 17 Jun 2010 11:22:20 -0700 (PDT) Subject: [Tutor] help In-Reply-To: Message-ID: <785881.53712.qm@web110113.mail.gq1.yahoo.com> >From the virtual desk of Lowell Tackett? --- On Thu, 6/17/10, Mark Lawrence wrote: From: Mark Lawrence Subject: Re: [Tutor] help To: tutor at python.org Date: Thursday, June 17, 2010, 8:30 AM On 17/06/2010 08:28, KB SU wrote: > help > > > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Help, I need somebody, Help, not just anybody, Help, you know I need someone, help. I'll leave you to find out the rests of the lyrics. :) Mark Lawrence. You're "dating" yourself!? (I was in 'Nam when that song came out.) _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Thu Jun 17 20:49:00 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 17 Jun 2010 20:49:00 +0200 Subject: [Tutor] pickling/shelve classes In-Reply-To: <201006171111.11757.eike.welk@gmx.net> References: <20100617024819.GA8835@scriptkitchen.com> <201006171111.11757.eike.welk@gmx.net> Message-ID: <201006172049.00367.eike.welk@gmx.net> On Thursday June 17 2010 11:11:11 Eike Welk wrote: > You should file a bug report in their bug tracker: > http://github.com/ipython/ipython/issues I believe tthis is the bug: http://github.com/ipython/ipython/issues/#issue/29 It seems that objects defined on IPython's top-level can't be pickled. Eike. From breamoreboy at yahoo.co.uk Thu Jun 17 20:53:31 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 Jun 2010 19:53:31 +0100 Subject: [Tutor] help In-Reply-To: <785881.53712.qm@web110113.mail.gq1.yahoo.com> References: <785881.53712.qm@web110113.mail.gq1.yahoo.com> Message-ID: On 17/06/2010 19:22, Lowell Tackett wrote: > >> From the virtual desk of Lowell Tackett > > --- On Thu, 6/17/10, Mark Lawrence wrote: > > From: Mark Lawrence > Subject: Re: [Tutor] help > To: tutor at python.org > Date: Thursday, June 17, 2010, 8:30 AM > > On 17/06/2010 08:28, KB SU wrote: >> help >> > > Help, I need somebody, > Help, not just anybody, > Help, you know I need someone, help. > > I'll leave you to find out the rests of the lyrics. :) > > Mark Lawrence. > > You're "dating" yourself! (I was in 'Nam when that song came out.) Jeesh, unlucky you :( (I was in shorts at our village primary school) Another lyric, "I hope I die before I get old", similar sort of era, eh? :) Regards. Mark Lawrence. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kaushalshriyan at gmail.com Thu Jun 17 20:53:49 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Fri, 18 Jun 2010 00:23:49 +0530 Subject: [Tutor] collectd application Message-ID: Hi, For example I do wget -O file.png "http://collectd.example.com/collectd/cgi-bin/collection.cgi?action=show_plugin;host=testdb;timespan=day;plugin=mysql" for a single host "testdb" and plugin "mysql" I do /usr/bin/mime-construct --header 'Sender: MOR_FAX at TEST.COM' --header 'From: MOR_FAX at TEST.COM' --to your at mail.com --subject 'Email test' --file-attach /var/tmp/file.png That would be a manual way of doing it. I do have numerous servers and multiple plugins. Basically i would like to do it without manual intervention. Please suggest further to send multiple png files from multiple servers with multiple collectd plugins. is that possible using python ? Thanks, Kaushal From rick at niof.net Thu Jun 17 22:41:08 2010 From: rick at niof.net (Rick Pasotto) Date: Thu, 17 Jun 2010 16:41:08 -0400 Subject: [Tutor] string encoding Message-ID: <20100617204108.GA4846@niof.net> I'm using BeautifulSoup to process a webpage. One of the fields has a unicode character in it. (It's the 'registered trademark' symbol.) When I try to write this string to another file I get this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) In the interpreter the offending string portion shows as: 'Realtors\xc2\xae'. How can I deal with this single string? The rest of the document works fine. -- "Freedom can't be kept for nothing. If you set a high value on liberty, you must set a low value on everything else." -- Lucius Annaeus Seneca, 65 A.D. Rick Pasotto rick at niof.net http://www.niof.net From lie.1296 at gmail.com Fri Jun 18 04:24:25 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 18 Jun 2010 12:24:25 +1000 Subject: [Tutor] string encoding In-Reply-To: <20100617204108.GA4846@niof.net> References: <20100617204108.GA4846@niof.net> Message-ID: On 06/18/10 06:41, Rick Pasotto wrote: > I'm using BeautifulSoup to process a webpage. One of the fields has a > unicode character in it. (It's the 'registered trademark' symbol.) When > I try to write this string to another file I get this error: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) > > In the interpreter the offending string portion shows as: 'Realtors\xc2\xae'. > > How can I deal with this single string? The rest of the document works > fine. You need to tell BeautifulSoup the encoding of the HTML document. You can encode this information in either the: - (preferred) Encoding is specified externally from HTTP Header ContentType declaration, e.g.: Content-Type: text/html; charset=utf-8 - HTML ContentType declaration: e.g. - XML declaration -- for XHTML document used for parsing using XML parser (hint: BeautifulSoup isn't XML/XHTML parser), e.g.: However, BeautifulSoup will also uses some heuristics to *guess* the encoding of a tag soup that doesn't have a proper encoding. So, the most likely reason is this, from Beautiful Soup's FAQ: http://www.crummy.com/software/BeautifulSoup/documentation.html#Why can't Beautiful Soup print out the non-ASCII characters I gave it? """ Why can't Beautiful Soup print out the non-ASCII characters I gave it? If you're getting errors that say: "'ascii' codec can't encode character 'x' in position y: ordinal not in range(128)", the problem is probably with your Python installation rather than with Beautiful Soup. Try printing out the non-ASCII characters without running them through Beautiful Soup and you should have the same problem. For instance, try running code like this: latin1word = 'Sacr\xe9 bleu!' unicodeword = unicode(latin1word, 'latin-1') print unicodeword If this works but Beautiful Soup doesn't, there's probably a bug in Beautiful Soup. However, if this doesn't work, the problem's with your Python setup. Python is playing it safe and not sending non-ASCII characters to your terminal. There are two ways to override this behavior. 1. The easy way is to remap standard output to a converter that's not afraid to send ISO-Latin-1 or UTF-8 characters to the terminal. import codecs import sys streamWriter = codecs.lookup('utf-8')[-1] sys.stdout = streamWriter(sys.stdout) codecs.lookup returns a number of bound methods and other objects related to a codec. The last one is a StreamWriter object capable of wrapping an output stream. 2. The hard way is to create a sitecustomize.py file in your Python installation which sets the default encoding to ISO-Latin-1 or to UTF-8. Then all your Python programs will use that encoding for standard output, without you having to do something for each program. In my installation, I have a /usr/lib/python/sitecustomize.py which looks like this: import sys sys.setdefaultencoding("utf-8") For more information about Python's Unicode support, look at Unicode for Programmers or End to End Unicode Web Applications in Python. Recipes 1.20 and 1.21 in the Python cookbook are also very helpful. Remember, even if your terminal display is restricted to ASCII, you can still use Beautiful Soup to parse, process, and write documents in UTF-8 and other encodings. You just can't print certain strings with print. """ From rick at niof.net Fri Jun 18 06:21:25 2010 From: rick at niof.net (Rick Pasotto) Date: Fri, 18 Jun 2010 00:21:25 -0400 Subject: [Tutor] string encoding In-Reply-To: References: <20100617204108.GA4846@niof.net> Message-ID: <20100618042125.GM4846@niof.net> On Fri, Jun 18, 2010 at 12:24:25PM +1000, Lie Ryan wrote: > On 06/18/10 06:41, Rick Pasotto wrote: > > I'm using BeautifulSoup to process a webpage. One of the fields has a > > unicode character in it. (It's the 'registered trademark' symbol.) When > > I try to write this string to another file I get this error: > > > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) > > > > In the interpreter the offending string portion shows as: 'Realtors\xc2\xae'. > > > > How can I deal with this single string? The rest of the document works > > fine. > > You need to tell BeautifulSoup the encoding of the HTML document. You > can encode this information in either the: > > - (preferred) Encoding is specified externally from HTTP Header > ContentType declaration, e.g.: > Content-Type: text/html; charset=utf-8 > > - HTML ContentType declaration: e.g. > The document has: When I look at the document in vim and when I 'print' in python I see the two characters of an acented capital A and the circled 'r'. > latin1word = 'Sacr\xe9 bleu!' > unicodeword = unicode(latin1word, 'latin-1') > print unicodeword TypeError: decoding Unicode is not supported > If this works but Beautiful Soup doesn't, there's probably a bug in > Beautiful Soup. However, if this doesn't work, the problem's with your > Python setup. Python is playing it safe and not sending non-ASCII > characters to your terminal. There are two ways to override this behavior. > > 1. The easy way is to remap standard output to a converter that's not > afraid to send ISO-Latin-1 or UTF-8 characters to the terminal. > > import codecs > import sys > streamWriter = codecs.lookup('utf-8')[-1] > sys.stdout = streamWriter(sys.stdout) > > codecs.lookup returns a number of bound methods and other objects > related to a codec. The last one is a StreamWriter object capable of > wrapping an output stream. Those four lines executed but I still get TypeError: decoding Unicode is not supported > Remember, even if your terminal display is restricted to ASCII, you can > still use Beautiful Soup to parse, process, and write documents in UTF-8 > and other encodings. You just can't print certain strings with print. I can print the string fine. It's f.write(string_with_unicode) that fails with: UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) Shouldn't I be able to f.write() *any* 8bit byte(s)? repr() gives: u"Realtors\\xc2\\xae" BTW, I'm running python 2.5.5 on debian linux. -- "Making fun of born-again christians is like hunting dairy cows with a high powered rifle and scope." -- P.J. O'Rourke Rick Pasotto rick at niof.net http://www.niof.net From steve at pearwood.info Fri Jun 18 07:45:17 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Jun 2010 15:45:17 +1000 Subject: [Tutor] collectd application In-Reply-To: References: Message-ID: <201006181545.17738.steve@pearwood.info> On Fri, 18 Jun 2010 04:53:49 am Kaushal Shriyan wrote: [...] > is that possible using python ? Yes. Python is a Turing complete language, it can do anything that any other language can do. This site will probably help you: http://www.catb.org/%7Eesr/faqs/smart-questions.html Good luck, and we look forward to you coming back with a better question! -- Steven D'Aprano From lang at tharin.com Fri Jun 18 07:54:05 2010 From: lang at tharin.com (Lang Hurst) Date: Thu, 17 Jun 2010 22:54:05 -0700 Subject: [Tutor] sqlite3 select extra characters Message-ID: <4C1B09FD.3060803@tharin.com> Is there a way to just return the values when using sqlite3? If I: names = c.execute('select names from students') for name in names: print names I get the list I want, but they look like (u'Cleese, John') (u'Jones, Terry') (u'Gillaim, Terry') is there a way to just return Cleese, John Jones, Terry Gillaim, Terry ? It seems a shame to have to run the answers through a stip process. -- There are no stupid questions, just stupid people. From alan.gauld at btinternet.com Fri Jun 18 09:20:41 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Jun 2010 08:20:41 +0100 Subject: [Tutor] sqlite3 select extra characters References: <4C1B09FD.3060803@tharin.com> Message-ID: "Lang Hurst" wrote > Is there a way to just return the values when using sqlite3? I don't think so, select returns a tuple of values, even if there is only one value. > I get the list I want, but they look like > > (u'Cleese, John') > is there a way to just return > > Cleese, John > > It seems a shame to have to run the answers through a stip process. It's hardly a major effort to index the item? print name[0] instead of print name HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Jun 18 11:22:52 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Jun 2010 19:22:52 +1000 Subject: [Tutor] sqlite3 select extra characters In-Reply-To: <4C1B09FD.3060803@tharin.com> References: <4C1B09FD.3060803@tharin.com> Message-ID: <201006181922.52798.steve@pearwood.info> On Fri, 18 Jun 2010 03:54:05 pm Lang Hurst wrote: > Is there a way to just return the values when using sqlite3? > > If I: > > names = c.execute('select names from students') > for name in names: print names What is c? A Cursor or a Connection object? It probably doesn't make any real difference, but it could, and so you should say. > I get the list I want, but they look like > > (u'Cleese, John') > (u'Jones, Terry') > (u'Gillaim, Terry') I doubt it. Did you mean this? (u'Cleese, John',) Note the comma at the end. A subtle difference, but a HUGE one. Punctuation is important: it's what makes the difference between: "Let's eat, Grandma!" and "Let's eat Grandma!" In Python, the comma makes it a tuple, rather than a meaningless pair of parentheses. > is there a way to just return > > Cleese, John > Jones, Terry > Gillaim, Terry No, because you're not *returning* anything, you're *printing*, and printing a tuple prints the opening and closing brackets plus the repr() of each internal object. Compare the following: >>> t = (u"Cleese, John",) # a tuple like that returned by execute >>> print t # print the tuple (u'Cleese, John',) >>> print t[0] # print the unicode string alone Cleese, John >>> print repr(t[0]) # print the unicode string's repr() u'Cleese, John' This is fundamental stuff: objects are not their printable representation, any more than you are a photo of you. What is printed is not the same as the object itself. Every object has its own printable representation. In some cases it looks exactly the same as the way you enter the object as a literal: >>> print 42 42 in other cases it is not: >>> print "Hello world" Hello world >>> print repr("Hello world") 'Hello world' >>> print "Hello world" # includes a tab character Hello world >>> print repr("Hello world") 'Hello\tworld' In this case, the object returned by execute is a list of tuples. If there is only a single object in each tuple, it is still a tuple, and it still prints as a tuple. If you want to print something other than a tuple, don't print the tuple: names = c.execute('select names from students') for t in names: name = t[0] # Extract the first item from each tuple. print name Of course you can combine the two lines inside the loop: print t[0] > It seems a shame to have to run the answers through a stip process. It would be more of a shame if execute sometimes returned a list of tuples, and sometimes a list of other objects, with no easy way before hand of knowing what it would return. -- Steven D'Aprano From payal-python at scriptkitchen.com Fri Jun 18 12:02:13 2010 From: payal-python at scriptkitchen.com (Payal) Date: Fri, 18 Jun 2010 03:02:13 -0700 Subject: [Tutor] pickling/shelve classes In-Reply-To: <201006171111.11757.eike.welk@gmx.net> References: <20100617024819.GA8835@scriptkitchen.com> <201006171111.11757.eike.welk@gmx.net> Message-ID: <20100618100213.GA27438@scriptkitchen.com> On Thu, Jun 17, 2010 at 11:11:11AM +0200, Eike Welk wrote: > I think it is a bug in IPython: I can do this in regular Python, but in > IPython I get the same error that you get: > Thanks a lot. It works in normal python. Thanks again. With warm regards, -Payal -- From payal-python at scriptkitchen.com Fri Jun 18 12:22:26 2010 From: payal-python at scriptkitchen.com (Payal) Date: Fri, 18 Jun 2010 03:22:26 -0700 Subject: [Tutor] how to shelve classes Message-ID: <20100618102226.GA27650@scriptkitchen.com> Hi, I want to carry my classes around, so I wrote foo.py as, #!/usr/bin/python import pickle, shelve f = shelve.open('movies') class F(object) : def __init__(self, amt) : self.amt = amt def dis(self) : print 'Amount : ', self.amt def add(self, na) : self.amt += na F.dis(self) f['k'] = F x=F(99) f['k2']=x Now in python interpreter I get, >>> import shelve >>> f = shelve.open('movies') >>> F2=f['k'] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/shelve.py", line 122, in __getitem__ value = Unpickler(f).load() AttributeError: 'module' object has no attribute 'F' How do I carry around my classes and instances? With warm regards, -Payal -- From lie.1296 at gmail.com Fri Jun 18 12:35:44 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 18 Jun 2010 20:35:44 +1000 Subject: [Tutor] string encoding In-Reply-To: <20100618042125.GM4846@niof.net> References: <20100617204108.GA4846@niof.net> <20100618042125.GM4846@niof.net> Message-ID: On 06/18/10 14:21, Rick Pasotto wrote: >> Remember, even if your terminal display is restricted to ASCII, you can >> still use Beautiful Soup to parse, process, and write documents in UTF-8 >> and other encodings. You just can't print certain strings with print. > > I can print the string fine. It's f.write(string_with_unicode) that fails with: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) > > Shouldn't I be able to f.write() *any* 8bit byte(s)? > > repr() gives: u"Realtors\\xc2\\xae" > > BTW, I'm running python 2.5.5 on debian linux. > The FAQ explains half of it, except that in your case, substitute what it says about "terminal" with "file object". Python plays it safe and does not implicitly encode a unicode string when writing into a file. If you have a unicode string and you want to .write() that unicode string to a file, you need to .encode() the string first, so: string_with_unicode = u"Realtors\xc2\xae" f.write(string_with_unicode.encode('utf-8')) otherwise, you can use the codecs module to wrap the file object: f = codecs.open('filename.txt', 'w', encoding="utf-8") f.write(string_with_unicode) # now you can send unicode string to f From davea at ieee.org Fri Jun 18 13:50:28 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Jun 2010 07:50:28 -0400 Subject: [Tutor] string encoding In-Reply-To: <20100618042125.GM4846@niof.net> References: <20100617204108.GA4846@niof.net> <20100618042125.GM4846@niof.net> Message-ID: <4C1B5D84.6090302@ieee.org> Rick Pasotto wrote: > > I can print the string fine. It's f.write(string_with_unicode) that fails with: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128) > > Shouldn't I be able to f.write() *any* 8bit byte(s)? > > repr() gives: u"Realtors\\xc2\\xae" > > BTW, I'm running python 2.5.5 on debian linux. > > You can write any 8 bit string. But you have a Unicode string, which is 16 or 32 bits per character. To write it to a file, it must be encoded, and the default encoder is ASCII. The cure is to encode it yourself, using the encoding that your spec calls for. I'll assume utf8 below: >>> name = u"Realtors\xc2\xae" >>> repr(name) "u'Realtors\\xc2\\xae'" >>> outfile = open("junk.txt", "w") >>> outfile.write(name) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-9: ordin al not in range(128) >>> outfile.write(name.encode("utf8")) >>> outfile.close() DaveA From eike.welk at gmx.net Fri Jun 18 15:16:36 2010 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 18 Jun 2010 15:16:36 +0200 Subject: [Tutor] how to shelve classes In-Reply-To: <20100618102226.GA27650@scriptkitchen.com> References: <20100618102226.GA27650@scriptkitchen.com> Message-ID: <201006181516.36192.eike.welk@gmx.net> On Friday June 18 2010 12:22:26 Payal wrote: > Hi, > I want to carry my classes around, so I wrote foo.py as, > > #!/usr/bin/python > > import pickle, shelve > > f = shelve.open('movies') > > class F(object) : > def __init__(self, amt) : self.amt = amt > def dis(self) : print 'Amount : ', self.amt > def add(self, na) : > self.amt += na > F.dis(self) > > f['k'] = F > x=F(99) > f['k2']=x > > Now in python interpreter I get, > > >>> import shelve > >>> f = shelve.open('movies') > >>> F2=f['k'] > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/shelve.py", line 122, in __getitem__ > value = Unpickler(f).load() > AttributeError: 'module' object has no attribute 'F' > > How do I carry around my classes and instances? Classes don't really get pickled. Only a little bit of information describing the class. The class definition has to be visible to the interpreter when a class or one of its instances is unpickled. Therefore you have to import the class first (IMHO, I didn't test anything): from foo import F import shelve f = shelve.open('movies') F2=f['k'] See: http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled "..., classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class?s code or data is pickled, ..." Eike. From steve at pearwood.info Fri Jun 18 16:48:59 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Jun 2010 00:48:59 +1000 Subject: [Tutor] Importing files not located on the home directory or standardard library In-Reply-To: <962622.95064.qm@web120013.mail.ne1.yahoo.com> References: <962622.95064.qm@web120013.mail.ne1.yahoo.com> Message-ID: <201006190049.00221.steve@pearwood.info> On Thu, 17 Jun 2010 05:10:32 pm Independent Learner wrote: > Lets say I want to load a file called quiz located in C:\Users\Julius > Hernandez\Desktop\Python2.6.5\Online Course\Chp.4 > > How would I configure PYTHONPATH or .pth? or what ever to import this > file from IDLE I don't use Windows, so I can't tell you the specific Windows commands to use, but I'll tell you the general steps and you can convert them to Windows-specific instructions. You need to: (1) Create an environment variable called PYTHONPATH; (2) Set it to the path (or paths) you want; (3) Ensure it gets automatically re-created each time you log in. (4) When you restart Python, it will add the value of PYTHONPATH to your module search path. Here is an example from Linux. I have this command in my .bashrc file: export PYTHONPATH=/home/steve/python/ The "export" shell command creates the environment variable PYTHONPATH and sets it to "/home/steve/python/". By placing it in .bashrc, it will automatically be executed each time I log in or start a new shell. Alternatively, you can use a .pth file. That's probably better if you have lots of directories to add. I've never done this, so take this with a grain of salt: (1) Find the location of your Python 2.6 installation. This is probably something like C:\Applications\Python2.6.5\ or similar. (2) Inside that directory should be another directory called "site-packages". It may or may not already have files or folders in it. (3) Find, or create, a file called ".pth" inside site-packages. You may need to instruct Windows to show hidden files. (4) Add the line: C:\Users\Julius Hernandez\Desktop\Python2.6.5\Online Course\Chp.4\ to that file, optionally together with C:\Users\Julius Hernandez\Desktop\Python2.6.5\Online Course\Chp.1\ C:\Users\Julius Hernandez\Desktop\Python2.6.5\Online Course\Chp.2\ C:\Users\Julius Hernandez\Desktop\Python2.6.5\Online Course\Chp.3\ etc. (5) Save and close the file, then restart Python. > I am also having slight trouble understanding module packages as > well, though I suspect it has something to do with not knowing how to > configure PYTHONPATH or .pth files A *module* is a single file containing Python code. Source code is name.py (also name.pyw on Windows only) while compiled byte code is name.pyc or name.pyo. There may be a few other extensions allowed on some other platforms. A *package* is a directory containing multiple modules which make up a unified whole. Not every directory containing modules is a package -- you need a special file called __init__.py for Python to treat it as a package. (That's underscore underscore i n i t underscore underscore dot p y.) If you have a directory structure like this: alpha/ +-- __init__.py +-- beta.py +-- gamma.py +-- delta/ +-- __init__.py +-- epsilon.py then you have a package alpha containing two modules beta and gamma and one sub-package delta. Now put the whole thing (the alpha directory plus it's contents) somewhere in the Python path, and it will be visible to Python. Then you can do this: import alpha and then this: x = alpha.delta.epsilon.some_function(1) y = alpha.gamma.something(2) z = alpha.something_else(3) and so forth. By the way, __init__.py doesn't have to contain anything, although it can contain code. It just needs to exist. -- Steven D'Aprano From lang at tharin.com Fri Jun 18 17:14:00 2010 From: lang at tharin.com (Lang Hurst) Date: Fri, 18 Jun 2010 08:14:00 -0700 Subject: [Tutor] sqlite3 select extra characters In-Reply-To: References: <4C1B09FD.3060803@tharin.com> Message-ID: <4C1B8D38.20802@tharin.com> Thanks. Alan Gauld wrote: > "Lang Hurst" wrote > >> Is there a way to just return the values when using sqlite3? > > I don't think so, select returns a tuple of values, even if there is > only one value. > >> I get the list I want, but they look like >> >> (u'Cleese, John') > >> is there a way to just return >> >> Cleese, John >> >> It seems a shame to have to run the answers through a stip process. > > It's hardly a major effort to index the item? > > print name[0] > > instead of > > print name > > HTH, > -- There are no stupid questions, just stupid people. From payal-tutor at scriptkitchen.com Fri Jun 18 16:11:59 2010 From: payal-tutor at scriptkitchen.com (Payal) Date: Fri, 18 Jun 2010 07:11:59 -0700 Subject: [Tutor] how to shelve classes In-Reply-To: <201006181516.36192.eike.welk@gmx.net> References: <20100618102226.GA27650@scriptkitchen.com> <201006181516.36192.eike.welk@gmx.net> Message-ID: <20100618141159.GA29599@scriptkitchen.com> On Fri, Jun 18, 2010 at 03:16:36PM +0200, Eike Welk wrote: > See: > http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled Thanks for the link and the explanation. With warm regards, -Payal -- From bgailer at gmail.com Fri Jun 18 19:50:45 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Jun 2010 13:50:45 -0400 Subject: [Tutor] Trouble with sockets... In-Reply-To: References: Message-ID: <4C1BB1F5.5060005@gmail.com> On 6/17/2010 5:25 AM, Modulok wrote: > List, > > I'm new to sockets and having trouble. I tried to write a simple > client/server program (see code below). The client would send a string > to the server. The server would echo that back to the client. > > PROBLEM: > I can send data to the server, and get data back, but only for the > first call to the 'sendall()' method. If I try to call it in a loop on > the client, to print a count-down, only the first call gets echoed. > Clearly, I'm missing something. > > EXAMPLE: (They're on the same physical machine.) > Shell on the server: > Modulok at modUnix> ./socket_server.py > Listening for clients... > Got connection from 192.168.1.1 > > Shell on the client: > Modulok at modUnix> ./latency_client.py 192.168.1.1 2554 > 0 > > What I wanted: > [-]Modulok at modUnix> ./latency_client.py 192.168.1.1 2554 > 0 > 1 > 2 > > > CODE: > ################################ > # The client program: > ################################ > import socket > import sys > def main(): > '''Send data to a server and receive the data echoed back to us.''' > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect( ('192.168.1.1', 2554) ) > > for i in range(3): > s.sendall(str(i)) > print s.recv(1024) > s.close() > > # Execution starts here: > try: > main() > except KeyboardInterrupt: > sys.exit("Aborting.") > > ################################ > # The server program: > ################################ > import socket > import sys > def main(): > '''Listen for a client and echo data back to them.''' > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind( ('192.168.1.1', 2554) ) > s.listen(5) > > print "Listening for clients..." > while True: > channel, client = s.accept() > print "Got connection from %s" % client[0] > message = channel.recv(1024) > channel.send(message) > channel.close() > Problem is you close the channel after one string is processed. That in turn closes the client socket. Either keep the channel open or put the client connect in the loop. > # Execution starts here: > try: > main() > except KeyboardInterrupt: > sys.exit("Aborting.") > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill NC From amartin7211 at gmail.com Fri Jun 18 19:53:14 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Fri, 18 Jun 2010 13:53:14 -0400 Subject: [Tutor] pydoc? Message-ID: Hey, everyone, I am new to programming and just downloaded Python 2.6 onto my windows vista laptop. I am attempting to follow 4.11 of the tutorial called "How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation" ( http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I am having some trouble. I am trying to use pydoc to search through the python libraries installed on my computer but keep getting an error involving the $ symbol. $ pydoc -g SyntaxError: invalid syntax Can anyone help me out? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Jun 18 20:19:23 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Jun 2010 14:19:23 -0400 Subject: [Tutor] pydoc? In-Reply-To: References: Message-ID: <4C1BB8AB.5070106@gmail.com> On 6/18/2010 1:53 PM, Andrew Martin wrote: > Hey, everyone, I am new to programming and just downloaded Python 2.6 > onto my windows vista laptop. I am attempting to follow 4.11 of the > tutorial called "How to Think Like a Computer Scientist: Learning with > Python v2nd Edition documentation" > (http://openbookproject.net/thinkcs/python/english2e/ch04.html). > However, I am having some trouble. I am trying to use pydoc to search > through the python libraries installed on my computer but keep getting > an error involving the $ symbol. It is good that you keep getting it. Consistency is valuable. > > $ pydoc -g > SyntaxError: invalid syntax Where are you typing this? Where did you get the idea that $ pydoc -g is a valid thing to do? In what way does this relate to the tutorial? What OS are you using? Please learn to ask "good" questions - which in this case means to tell us a lot more about what you are doing. Please also reply-all so a copy of your reply goes to the tutor list. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Fri Jun 18 20:29:11 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Jun 2010 14:29:11 -0400 Subject: [Tutor] pydoc? In-Reply-To: References: Message-ID: <4C1BBAF7.5070605@gmail.com> On 6/18/2010 1:53 PM, Andrew Martin wrote: > Hey, everyone, I am new to programming and just downloaded Python 2.6 > onto my windows vista laptop. I am attempting to follow 4.11 of the > tutorial called "How to Think Like a Computer Scientist: Learning with > Python v2nd Edition documentation" > (http://openbookproject.net/thinkcs/python/english2e/ch04.html). > However, I am having some trouble. I am trying to use pydoc to search > through the python libraries installed on my computer but keep getting > an error involving the $ symbol. > > $ pydoc -g > SyntaxError: invalid syntax I make a guess - that you are typing $ pydoc -g at the Python Interpreter prompt (>>>) The manual recommends typing it a the shell prompt. In which case the $ represents the prompt and you should just type pydoc -g. -- Bob Gailer 919-636-4239 Chapel Hill NC From lowelltackett at yahoo.com Fri Jun 18 23:42:48 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 18 Jun 2010 14:42:48 -0700 (PDT) Subject: [Tutor] pydoc? Message-ID: <139671.48213.qm@web110107.mail.gq1.yahoo.com> >From the virtual desk of Lowell Tackett --- On Fri, 6/18/10, Andrew Martin wrote: From: Andrew Martin Subject: [Tutor] pydoc? To: tutor at python.org Date: Friday, June 18, 2010, 1:53 PM Hey, everyone, I am new to programming and just downloaded Python 2.6 onto my windows vista laptop. I am attempting to follow 4.11 of the tutorial called "How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation" (http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I am having some trouble. I am trying to use pydoc to search through the python libraries installed on my computer but keep getting an error involving the $ symbol. $ pydoc -g SyntaxError: invalid syntax Can anyone help me out? Thanks You're getting awfully close. Again, assuming that you are in python; at the prompt type: pydoc modules which will list all the module names, but...it's more than one screen and you can't go backwards, so you lose the first half. So, type (instead): pydoc modules > made-upfilename and you will create an ascii file (with the name you gave it) containing all the pydoc names in it. The easiest way to open that file is: less made-upfilename "less" is a bash command that opens files for reading. As you'll see, it will allow you to scroll forward in the file (space bar) or backwards, with the "b" key. To close that file, just type a "q" for quit. And while your at it, while at bash's ($) the command line, type in "man less" w/o the quotes (that stands for "manual for 'less'"), and begin learning how the bash commands work, and how you can access great info as to how they work. Good luck. From amartin7211 at gmail.com Sat Jun 19 01:13:41 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Fri, 18 Jun 2010 19:13:41 -0400 Subject: [Tutor] pydoc? In-Reply-To: <139671.48213.qm@web110107.mail.gq1.yahoo.com> References: <139671.48213.qm@web110107.mail.gq1.yahoo.com> Message-ID: Alright I got it. Although i didn't end up doing any typing. All I did was go to start/module docs and then press open browser. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amartin7211 at gmail.com Sat Jun 19 01:14:31 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Fri, 18 Jun 2010 19:14:31 -0400 Subject: [Tutor] pydoc? In-Reply-To: References: <139671.48213.qm@web110107.mail.gq1.yahoo.com> Message-ID: On Fri, Jun 18, 2010 at 7:13 PM, Andrew Martin wrote: > Alright I got it. Although i didn't end up doing any typing. All I did was > go to start/module docs and then press open browser. > > Thanks again and next time i will supply more info with the question -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 19 01:56:10 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jun 2010 00:56:10 +0100 Subject: [Tutor] pydoc? References: Message-ID: "Andrew Martin" wrote > Hey, everyone, I am new to programming and just downloaded Python > 2.6 onto > my windows vista laptop. I am attempting to follow 4.11 of the > tutorial > ....I am trying to use pydoc to search through the > python libraries installed on my computer but keep getting an error > involving the $ symbol. > > $ pydoc -g > SyntaxError: invalid syntax OK, There are lots of problems hidden within this request. First, you are on windows Vista and the $ sign is the Linux command prompt. So you need to use a Windows command console which will have a prompt that looks something like: C:\WINDOWS> And you dont type the $. You will find that a lot of programmers prefer Linux to Windows and so a lot of the documentation tends to be Linux focused. You can usually find Windows equivalents but it takes a bit of extra thought or research sometimes. Get used to using the command console because a lot of programming tasks are best done there. In programming, GUIs are not always a good thing... However the error you get looks like a Python error which implies you are at the pyhon interpreter prompt (>>>). That is not the right place to be typing pydoc. That needs to be at the OS command prompt. However, the final problem is that pydoc is not set up to run from the command prompt - at least not on my PC. So before you could get that to work you would also need to add the Tools\scripts folder to your path.... The lesson to be learned is that translating instructions intended for Linux into Windows is non-trivial. BTW. The easiest way to start a Windows command prompt - if you don't have a shortcut on your desktop - is to go to Start->Run and type CMD in the dialog. Then hit OK. A black command window should appear. You'll find more detailed instructions and links to some help info in the "Getting Started" topic of my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lang at tharin.com Sat Jun 19 03:08:40 2010 From: lang at tharin.com (Lang Hurst) Date: Fri, 18 Jun 2010 18:08:40 -0700 Subject: [Tutor] sqlite3 select extra characters In-Reply-To: <201006181922.52798.steve@pearwood.info> References: <4C1B09FD.3060803@tharin.com> <201006181922.52798.steve@pearwood.info> Message-ID: <4C1C1898.3010209@tharin.com> Steven D'Aprano wrote: > On Fri, 18 Jun 2010 03:54:05 pm Lang Hurst wrote: > >> Is there a way to just return the values when using sqlite3? >> >> If I: >> >> names = c.execute('select names from students') >> for name in names: print names >> > > What is c? A Cursor or a Connection object? It probably doesn't make any > real difference, but it could, and so you should say. > > > I'm doing my best. c was a cursor. Perhaps not the best naming convention. [snip] > I doubt it. Did you mean this? > > (u'Cleese, John',) > > Note the comma at the end. A subtle difference, but a HUGE one. > Punctuation is important: it's what makes the difference between: > > Yup, you're right. > In Python, the comma makes it a tuple, rather than a meaningless pair of > parentheses. > > > > >> is there a way to just return >> >> Cleese, John >> Jones, Terry >> Gillaim, Terry >> > > No, because you're not *returning* anything, you're *printing*, and > printing a tuple prints the opening and closing brackets plus the > repr() of each internal object. > > I guess I should have been more clear. By return, I suppose I meant assign. I'm trying to pull the names from rows of data and append each name to a ListStore, for entry completion. I was using "print" just to show what I was hoping to get into the ListStore, and at that point, I was only getting the tuple, not the object. > This is fundamental stuff: objects are not their printable > representation, any more than you are a photo of you. > > What is printed is not the same as the object itself. Every object has > its own printable representation. In some cases it looks exactly the > same as the way you enter the object as a literal: > > [snip] > In this case, the object returned by execute is a list of tuples. If > there is only a single object in each tuple, it is still a tuple, and > it still prints as a tuple. If you want to print something other than a > tuple, don't print the tuple: > > names = c.execute('select names from students') > for t in names: > name = t[0] # Extract the first item from each tuple. > print name > > Of course you can combine the two lines inside the loop: > > print t[0] > OK. >> It seems a shame to have to run the answers through a stip process. >> > > It would be more of a shame if execute sometimes returned a list of > tuples, and sometimes a list of other objects, with no easy way before > hand of knowing what it would return. > > Actually, I know you were being facetious, but with my skills so poor, often that seems like what is happening. I'm killing myself right now trying to troubleshoot glade, python and entrycompletion. I know it will soon be as clear as a tuple vs an object; I just hope that transition happens soon. Thanks again for walking me through the terminology, it is appreciated. -- There are no stupid questions, just stupid people. From lang at tharin.com Sat Jun 19 04:18:55 2010 From: lang at tharin.com (Lang Hurst) Date: Fri, 18 Jun 2010 19:18:55 -0700 Subject: [Tutor] Python glade Message-ID: <4C1C290F.4060403@tharin.com> OK, I created a UI in glade which has the following: True True 25 basically, a text box. I'm trying to set it up to automatically complete names as I type. My py file has the following: def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file('gradebook.glade') self.window = self.builder.get_object('winapp') self.builder.connect_signals(self) # self.student_change = gtk.Entry() completion = gtk.EntryCompletion() self.names = gtk.ListStore(str) query = "SELECT * from students" db = sqlite3.connect('gradebook.db') cursor = db.cursor() cursor.execute(query) students = cursor.fetchall() for student in students: self.names.append([student[1]]) print student[1] cursor.close() completion.set_model(self.names) self.student_change.set_completion(completion) completion.set_text_column(0) When I try to run this, I get AttributeError: 'appGUI' object has no attribute 'student_change' But if I uncomment the self.student_change line from up above, it runs but doesn't do completion. I modeled this after http://www.koders.com/python/fid755022E2A82A54C79A7CF86C00438E6F825676C3.aspx?s=gtk#L4 I'm pretty sure the problem is somewhere in the gtk.Builder part of what I'm doing, but I can't for the life of me figure this out. -- There are no stupid questions, just stupid people. From nbr1ninrsan7 at yahoo.com Sat Jun 19 05:55:05 2010 From: nbr1ninrsan7 at yahoo.com (Independent Learner) Date: Fri, 18 Jun 2010 20:55:05 -0700 (PDT) Subject: [Tutor] Question Message-ID: <729070.67817.qm@web120014.mail.ne1.yahoo.com> ~After doing a google search, I could not find any good solid anwsers. So I will apologize ahead of time since this is not really a Python specific question. However... ~I was wondering if I should try to learn 2 programming languages at once, Python and C++. Obviously I am working on learning python right now, I have gotten up to Classes(I am studying from Learning Python 3rd and 4th editions from Mark Lutz on Safari online books), and feel like I have a pretty good?idea of everything before classes. Yea there are still a lot of things I am not really fully comprehending, but like I said I have a pretty good idea. ~Perhaps it is also worth nothing?Python is pretty much my first real Programming?Language. Yea I took an intro to comp sci?class(like 2 years ago) and a computer programming logic class(also like 2 years ago) both using?pseudocode?and have since dabbled in C(I?started a programming class for school but dropped?out twice?after about 1/3 of? the semester, for two consecutive semesters about?9?months ago) So here I am,?a?computer engineering?major failure who had to change?my major to Physics so I wouldn't have to take all those dammed comp sci classes Figured I could just teach myself. I mention this because I want to make clear I have the logic and critical thinking skills down, and in my opinion the aptitude as well. ~So is it better to learn 1 programming language first, then learn another. Or better to pretty much learn them at the same time? And why? ++Thank you so much if you have actually taken the time to read this. =)?P.S. Julius Hernandez -------------- next part -------------- An HTML attachment was scrubbed... URL: From lang at tharin.com Sat Jun 19 06:50:23 2010 From: lang at tharin.com (Lang Hurst) Date: Fri, 18 Jun 2010 21:50:23 -0700 Subject: [Tutor] Python glade In-Reply-To: <4C1C290F.4060403@tharin.com> References: <4C1C290F.4060403@tharin.com> Message-ID: <4C1C4C8F.7080907@tharin.com> Found the problem. If you want to do this, you have to access the gtkEntry like this self.builder.get_object('student_change').set_completion(completion) instead of self.student_change.set_completion(completion) Lang Hurst wrote: > OK, I created a UI in glade which has the following: > > > True > True > name="invisible_char">● > 25 > handler="student_change_activate_cb"/> > > > > basically, a text box. I'm trying to set it up to automatically > complete names as I type. My py file has the following: > > def __init__(self): > self.builder = gtk.Builder() > self.builder.add_from_file('gradebook.glade') > self.window = self.builder.get_object('winapp') > self.builder.connect_signals(self) > # self.student_change = gtk.Entry() > completion = gtk.EntryCompletion() > self.names = gtk.ListStore(str) > query = "SELECT * from students" > db = sqlite3.connect('gradebook.db') > cursor = db.cursor() > cursor.execute(query) > students = cursor.fetchall() > for student in students: > self.names.append([student[1]]) > print student[1] > cursor.close() > completion.set_model(self.names) > self.student_change.set_completion(completion) > completion.set_text_column(0) > > > When I try to run this, I get > > AttributeError: 'appGUI' object has no attribute 'student_change' > > > But if I uncomment the self.student_change line from up above, it runs > but doesn't do completion. > > I modeled this after > > http://www.koders.com/python/fid755022E2A82A54C79A7CF86C00438E6F825676C3.aspx?s=gtk#L4 > > > I'm pretty sure the problem is somewhere in the gtk.Builder part of > what I'm doing, but I can't for the life of me figure this out. > -- There are no stupid questions, just stupid people. From alan.gauld at btinternet.com Sat Jun 19 10:19:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jun 2010 09:19:09 +0100 Subject: [Tutor] Question References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: "Independent Learner" wrote > ~I was wondering if I should try to learn 2 programming languages > at once, Python and C++. No, no no! If it had been a different pair I might have said try it. But C++ is one of the most difficult, complex and difficult programming lamnguages out there. It is full of subtle things that can trip you up and cause very weird and subtle bugs that are diffficult to find. And it has similar concepts to Python but implemented so entirely differently that studying the two together will be an exercise in frustration. Part of the reason why C++ is so difficult is because it is so powerful. You have full access to the machine through the C language elements, plus a full OOP environment, plus a powerful generic type system. Plus it combines static and dynamic variables with a reference model all with slightly different syntax and semantic behaviours. At work I hardly ever recommend that people go on language training courses, C++ is the exception! You can learn C++ by yourself but you will need a good book and a lot of time and patience. > Obviously I am working on learning python right now, > I have gotten up to Classes Stick with Python and get comfortable with that. Then move onto C++ as a separate and significant project if you really feel you have a need to know it. > there are still a lot of things I am not really fully > comprehending, but like I said I have a pretty good idea. Ask questions here. That's what the tutor list is for. > ~So is it better to learn 1 programming language > first, then learn another. Or better to pretty much > learn them at the same time? And why? If you had asked about Python and Object Pascal or Ruby or even Lisp I'd have said sure, if you enjoy comparative learning. Those languages are sufficiently close to makle it worthwhile. (That's why I teach VBScript and JavaScript as well as Python in my tutor) But C++ is awash with gotchas and has an internal object model completely different to Python. (COBOL is another one that I'd never recommend as a comparative languiage!) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Jun 19 10:56:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Jun 2010 18:56:34 +1000 Subject: [Tutor] Question In-Reply-To: <729070.67817.qm@web120014.mail.ne1.yahoo.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: <201006191856.34526.steve@pearwood.info> On Sat, 19 Jun 2010 01:55:05 pm Independent Learner wrote: > ~I was wondering if I should try to learn 2 programming languages at > once, Python and C++. I don't know. That depends on you. How much time do you have to spend on learning the languages? If it's one hour a week, you'll have trouble learning *one* language, never mind two. It really depends on you, and since we don't know you, we can't answer that. Alan has said "No" because Python and C++ have radically different programming models, and suggested that you should consider two languages that are much more similar such as Python and Ruby. I don't know about that... I think I'd much rather learn two different languages, so that I could compartmentalise "these are Python rules" and "these are C++ rules", rather constantly mixing up Python and Ruby syntax and idioms and getting them confused. But your mileage may vary -- maybe you're more like Alan than me. > Yea I took an intro to comp sci?class(like 2 years ago) and a > computer programming logic class(also like 2 years ago) both > using?pseudocode? Good grief! How do they teach a class in computer programming using pseudocode??? That's like teaching somebody to cook by handing them Playdough and a toy oven that doesn't even get warm! > and have since dabbled in C(I?started a programming > class for school but dropped?out twice?after about 1/3 of? the > semester, for two consecutive semesters about?9?months ago) So here I > am,?a?computer engineering?major failure who had to change?my major > to Physics so I wouldn't have to take all those dammed comp sci > classes Figured I could just teach myself. I mention this because I > want to make clear I have the logic and critical thinking skills > down, and in my opinion the aptitude as well. I don't mean to be negative, but if you've dropped out of a programming course *twice*, and then changed your major to avoid programming, perhaps you're not cut out for programming? Obviously I don't know you, maybe you have good reasons for dropping out unrelated to your ability and intelligence, but speaking as a stranger, when you say "Hey guys, I have a history of dropping out of a basic programming courses, but don't worry, I've got the aptitude to be a programmer", it doesn't really fill me with confidence. Perhaps that's something you should keep more to yourself until *after* you've proven you do have the chops? -- Steven D'Aprano From davea at ieee.org Sat Jun 19 12:31:30 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Jun 2010 06:31:30 -0400 Subject: [Tutor] Question In-Reply-To: References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: <4C1C9C82.80107@ieee.org> Alan Gauld wrote: >
      "Independent Learner" wrote >> ~I was wondering if I should try to learn 2 programming languages at >> once, Python and C++. > > No, no no! If it had been a different pair I might have said try it. > But C++ is one of the most difficult, complex and difficult > programming lamnguages out there. It is full of subtle things that can > trip you up and cause very weird and subtle bugs that are diffficult > to find. And it has similar concepts to Python but implemented so > entirely differently that studying the two together will be an > exercise in frustration. > > Part of the reason why C++ is so difficult is because it is so > powerful. You have full access to the machine through the C language > elements, plus a full OOP environment, plus a powerful generic type > system. Plus it combines static and dynamic variables with a reference > model all with slightly different syntax and semantic behaviours. > > At work I hardly ever recommend that people go on language training > courses, C++ is the exception! You can learn C++ by yourself but you > will need a good book and a lot of time and patience. > >> Obviously I am working on learning python right now, I have gotten up >> to Classes > > Stick with Python and get comfortable with that. > > I concur 100% with Alan's advice to learn one language thoroughly first, and I think Python is the one that would have best suited me as a first language, if it had been available. Python was approximately number 30 for me, not counting the languages I learned entirely for personal reasons. Currently on the job I mostly use C++, Python, and Perl. C++ was indeed the hardest language for me to learn, but was the most rewarding for its time. It's the only language I went to classes for, and one of the lectures was taught by Bjarne Stroustrup. Fortunately, I had a coworker on the ANSI language standardization committee, and access to lots of other people who knew it rather well. Once you have one or two languages very comfortably under your belt, then go ahead and learn anything else you like. But even then, if you have to learn two new ones at the same time, I'd recommend they be very unlike. So you could learn Lisp or Forth at the same time as you were learning Ruby, but I'd not try to learn Perl and Python at the same time. (Actually, Perl is driving me crazy at the moment, and I'm only using it because we have a series of large scripts written in it.) I drive a motorcycle for my main transportation, and my wife's van otherwise. And I never get confused between the controls on one and on the other. But at one time I had a Harley with the brake on the left, and gearshift on the right (ie. normal at the time), and switching back and forth between that motorcycle and others almost caused an accident. When learning to ride, I can't imagine using two different motorcycles with swapped controls. Good luck, and post questions here when you have them. DaveA From alan.gauld at btinternet.com Sat Jun 19 13:24:44 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 19 Jun 2010 11:24:44 +0000 (GMT) Subject: [Tutor] Question In-Reply-To: <4C1C9C82.80107@ieee.org> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <4C1C9C82.80107@ieee.org> Message-ID: <270541.73354.qm@web86704.mail.ird.yahoo.com> > belt, then go ahead and learn anything else you like. But even then, if you have > to learn two new ones at the same time, I'd recommend they be very unlike. > So you could learn Lisp or Forth at the same time as you were learning Ruby, but > I'd not try to learn Perl and Python at the same time. Actually that's a point. I favour learning two languages that are semantically similar buut syntactically different. Thats why I chose JavaScript and VBScript as my tutorial languages, because the syntax of each is so different you are less likely to get confused, but the underlying programming model is very similar in each case. So with Bob's illustration of the Harley in mind I'll withdraw the suggestion to learn Python and Ruby - because the syntax is very similar - but keep the Python/Lisp/Object Pascal ccombinations. Having said that I stll recommend that most folks learn one at a time. Unless you are the kind of person that actively prefers comparative study it will be better to keep to one language. Alan G From smokefloat at gmail.com Sat Jun 19 17:39:33 2010 From: smokefloat at gmail.com (David Hutto) Date: Sat, 19 Jun 2010 11:39:33 -0400 Subject: [Tutor] Question In-Reply-To: <270541.73354.qm@web86704.mail.ird.yahoo.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <4C1C9C82.80107@ieee.org> <270541.73354.qm@web86704.mail.ird.yahoo.com> Message-ID: On Sat, Jun 19, 2010 at 7:24 AM, ALAN GAULD wrote: > > >> belt, then go ahead and learn anything else you like. But even then, if you have >> to learn two new ones at the same time, I'd recommend they be very unlike. >> So you could learn Lisp or Forth at the same time as you were learning Ruby, but >> I'd not try to learn Perl and Python at the same time. > > Actually that's a point. I favour learning two languages that are semantically > similar buut syntactically different. Thats why I chose JavaScript and VBScript > as my tutorial languages, because the syntax of each is so different you are > less likely to get confused, but the underlying programming model is very > similar in each case. > > So with Bob's illustration of the Harley in mind I'll withdraw the suggestion to > learn Python and Ruby - because the syntax is very similar - but keep the > Python/Lisp/Object Pascal ccombinations. > > Having said that I stll recommend that most folks learn one at a time. Unless > you are the kind of person that actively prefers comparative study it will > be better to keep to one language. > > Alan G > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Being an independent learner/hobbyist scholar myself, I have to wonder what the motivation is for wanting to learn two languages. Is it just for satisfaction to bring the dead, curious cat back, or maybe to impress friends,, or to accomplish some task, or to understand the technology you use better...or... In other words, what's the reason behind your goal? Mine, for instance, is that once I started to learn the languages, I also had a curiosity towards the inner workings, so it seemed that the obvious path is to move towards the lower level languages from a programming stand point, but it also makes since to learn from the power plant through the outlet. I enjoy communicating with the electrons, so I want to go at it from both ends, so if better understanding technology is your motivation, then I say take the most well rounded, comprehensive approach to what you want to know more about. So, I think, the question isn't should I learn two languages, but what is the ultimate goal of my understanding, and what is the more well rounded means to meet this end desire. From bricker.steve at imonmail.com Sat Jun 19 17:51:31 2010 From: bricker.steve at imonmail.com (Steve Bricker) Date: Sat, 19 Jun 2010 10:51:31 -0500 Subject: [Tutor] Question Message-ID: <2216.1276962691@imonmail.com> Back in ancient days, my college training began with FORTRAN the first semester, then COBOL, ALC (BAL), and RPG in the second semester. Even though this was back when dinosaurs were still ruling the earth, the learning program remains relevant. Understand one language in a practical way, then use that to move on to others. Steve Bricker On Fri 10/06/18 22:55 , Independent Learner nbr1ninrsan7 at yahoo.com sent: ~After doing a google search, I could not find any good solid anwsers. So I will apologize ahead of time since this is not really a Python specific question. However... ~I was wondering if I should try to learn 2 programming languages at once, Python and C++. Obviously I am working on learning python right now, I have gotten up to Classes(I am studying from Learning Python 3rd and 4th editions from Mark Lutz on Safari online books), and feel like I have a pretty good idea of everything before classes. Yea there are still a lot of things I am not really fully comprehending, but like I said I have a pretty good idea. ~Perhaps it is also worth nothing Python is pretty much my first real Programming Language. Yea I took an intro to comp sci class(like 2 years ago) and a computer programming logic class(also like 2 years ago) both using pseudocode and have since dabbled in C(I started a programming class for school but dropped out twice after about 1/3 of the semester, for two consecutive semesters about 9 months ago) So here I am, a computer engineering major failure who had to change my major to Physics so I wouldn't have to take all those dammed comp sci classes Figured I could just teach myself. I mention this because I want to make clear I have the logic and critical thinking skills down, and in my opinion the aptitude as well. ~So is it better to learn 1 programming language first, then learn another. Or better to pretty much learn them at the same time? And why? ++Thank you so much if you have actually taken the time to read this. =) P.S. Julius Hernandez -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Jun 19 19:02:18 2010 From: smokefloat at gmail.com (David Hutto) Date: Sat, 19 Jun 2010 13:02:18 -0400 Subject: [Tutor] Question In-Reply-To: <201006191856.34526.steve@pearwood.info> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <201006191856.34526.steve@pearwood.info> Message-ID: On Sat, Jun 19, 2010 at 4:56 AM, Steven D'Aprano wrote: > On Sat, 19 Jun 2010 01:55:05 pm Independent Learner wrote: > >> ~I was wondering if I should try to learn 2 programming languages at >> once, Python and C++. > > I don't know. That depends on you. > > How much time do you have to spend on learning the languages? If it's > one hour a week, you'll have trouble learning *one* language, never > mind two. > > It really depends on you, and since we don't know you, we can't answer > that. > > Alan has said "No" because Python and C++ have radically different > programming models, and suggested that you should consider two > languages that are much more similar such as Python and Ruby. I don't > know about that... I think I'd much rather learn two different > languages, so that I could compartmentalise "these are Python rules" > and "these are C++ rules", rather constantly mixing up Python and Ruby > syntax and idioms and getting them confused. But your mileage may > vary -- maybe you're more like Alan than me. > > >> Yea I took an intro to comp sci?class(like 2 years ago) and a >> computer programming logic class(also like 2 years ago) both >> using?pseudocode > > Good grief! How do they teach a class in computer programming using > pseudocode??? That's like teaching somebody to cook by handing them > Playdough and a toy oven that doesn't even get warm! > > >> and have since dabbled in C(I?started a programming >> class for school but dropped?out twice?after about 1/3 of? the >> semester, for two consecutive semesters about?9?months ago) So here I >> am,?a?computer engineering?major failure who had to change?my major >> to Physics so I wouldn't have to take all those dammed comp sci >> classes Figured I could just teach myself. I mention this because I >> want to make clear I have the logic and critical thinking skills >> down, and in my opinion the aptitude as well. > > I don't mean to be negative, but if you've dropped out of a programming > course *twice*, and then changed your major to avoid programming, > perhaps you're not cut out for programming? I see your point, but I place quitting learning as synonymous with quiting smoking, the higher the rate at which you go back to something, means you have a desire to achieve the activity, so the repetition of attempts means they have the desire, and will have a higher 'receptive potential' than those that are forced to learn. Obviously I don't know you, > maybe you have good reasons for dropping out unrelated to your ability > and intelligence, but speaking as a stranger, when you say "Hey guys, I > have a history of dropping out of a basic programming courses, but > don't worry, I've got the aptitude to be a programmer", it doesn't > really fill me with confidence. Perhaps that's something you should > keep more to yourself until *after* you've proven you do have the > chops? > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From breamoreboy at yahoo.co.uk Sat Jun 19 19:12:16 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 19 Jun 2010 18:12:16 +0100 Subject: [Tutor] Question In-Reply-To: <729070.67817.qm@web120014.mail.ne1.yahoo.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: On 19/06/2010 04:55, Independent Learner wrote: > ~After doing a google search, I could not find any good solid anwsers. So I will apologize ahead of time since this is not really a Python specific question. However... > > ~I was wondering if I should try to learn 2 programming languages at once, Python and C++. Obviously I am working on learning python right now, I have gotten up to Classes(I am studying from Learning Python 3rd and 4th editions from Mark Lutz on Safari online books), and feel like I have a pretty good idea of everything before classes. Yea there are still a lot of things I am not really fully comprehending, but like I said I have a pretty good idea. > > ~Perhaps it is also worth nothing Python is pretty much my first real Programming Language. Yea I took an intro to comp sci class(like 2 years ago) and a computer programming logic class(also like 2 years ago) both using pseudocode and have since dabbled in C(I started a programming class for school but dropped out twice after about 1/3 of the semester, for two consecutive semesters about 9 months ago) So here I am, a computer engineering major failure who had to change my major to Physics so I wouldn't have to take all those dammed comp sci classes Figured I could just teach myself. I mention this because I want to make clear I have the logic and critical thinking skills down, and in my opinion the aptitude as well. > > ~So is it better to learn 1 programming language first, then learn another. Or better to pretty much learn them at the same time? And why? > > ++Thank you so much if you have actually taken the time to read this. =) P.S. Julius Hernandez > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You've had a lot of sound advice, but I take issue with this "learn a language in five minutes" bit. It took me five years to get to grips with plain old C. Assume that the same applies to all other languages to make it simple, that means for me to get to grips with 30 languages takes 150 years. I don't think I'll live to do that. Just my viewpoint. Kindest regards. Mark Lawrence. From knacktus at googlemail.com Sat Jun 19 21:17:11 2010 From: knacktus at googlemail.com (Knacktus) Date: Sat, 19 Jun 2010 21:17:11 +0200 Subject: [Tutor] Question In-Reply-To: <729070.67817.qm@web120014.mail.ne1.yahoo.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: <4C1D17B7.4020306@googlemail.com> > ~So is it better to learn 1 programming language first, then learn > another. Or better to pretty much learn them at the same time? And why? First, I think python is a bit underrated for creating "real" applications. I'm amazed again and again by it's power on all programming scales (e.g. quick and dirty csv-file hacks, medium scripts to bigger app with gui (e.g. pyqt is unbelievable powerful) and database-connections). So, I hardly see something of an urge for learning c++. Python will bring you a looooooong way. Then, I think when learning to programm, there're two big levels. Level one is to learn the language syntax, basic algorithms, data types, etc.. The second level is how to design larger programs. How to make them as easy and clear to understand (and to maintain) as possible. You'll find yourself thinking about what to place where in the code, read stuff about OO-Programming and Design Patterns etc.. I'm currently at this level. So, if you start learning another language, it will broaden your level 1 skills, but I think it'll be more valuable to become better at level 2. So, once you're familiar with python, I would start creating some bigger apps. One thing to keep in mind is that python has a lot of patterns build in due to its dynamic typing and first class callables. A lot of things can be expressed much easier with python than with Java or C++. That will leave you more brain power for innovation. But for the pure sake of learning design patterns, Java might be a candidate. Jan From bgailer at gmail.com Sun Jun 20 00:06:35 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Jun 2010 18:06:35 -0400 Subject: [Tutor] Question In-Reply-To: <2216.1276962691@imonmail.com> References: <2216.1276962691@imonmail.com> Message-ID: <4C1D3F6B.20507@gmail.com> 6/19/2010 11:51 AM, Steve Bricker wrote: > Back in ancient days, my college training began with FORTRAN the first > semester, then COBOL, ALC (BAL), and RPG in the second semester. Back in even more ancient days, my college training began with IBM 650 machine language, then ALC (SOAP), then CLASSMATE all of which which we fed into the computer via a card reader That was all a subset of a logic class. That was all the school offered computer-wise then. //I also reacted to introducing programming via pseudo-code. Might just as well ue Python (since it is like pseudo code) and at least see some results. It also reminds me of a FORTRAN course I was asked to teach. The students spent the first morning learning how to write expressions (e.g. operators and precedence). They had no contetxt for why they would do that or what a FORTRAN program looked like. As soon at I could I rewrote the entire course, starting them with a program that read 2 numbers, added them and printed the result. In those days students sat at terminals, edited program files, submitted them to the resident HP 3000 computer and shortly received printouts. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lang at tharin.com Sun Jun 20 02:16:56 2010 From: lang at tharin.com (Lang Hurst) Date: Sat, 19 Jun 2010 17:16:56 -0700 Subject: [Tutor] How to add extra Vbox fields dynamically Message-ID: <4C1D5DF8.9040009@tharin.com> I hope that I'm asking this in the right place. I don't have too much trouble hacking together command line stuff, but the GUI part is a struggle for me. I created a UI in glade. It has a couple of Vboxes for information. The final box is filled with a TextView. In my program, I'm connecting to a database and pulling out a series of records. As it stands, I can pull out all the records and view them in the TextView, but I would like to be able to have each result be a separate TextView (which I then have to figure out how to make clickable...) Right now, this part looks like: query = 'SELECT subject, chapter_module, credits, final_test_score, notes FROM credits WHERE id=' + student[0][6] cursor.execute(query) credits = cursor.fetchall() temp = '' for credit in credits: sub_buf = 15 - len(credit[0]) chap_buf = 15 - len(credit[1]) cred_buf = 5 - len(credit[2]) score_buf = 5 - len(credit[1]) temp = temp + credit[0] + " " * sub_buf + credit[1] + " " * chap_buf + "Credits: " + credit[2] + " " * chap_buf + "Score: " + credit[3] + "\n\nNOTES: " + credit[4] + "\n" + " " * 5 + "-" * 50 + "\n\n" # I would like to loop something here # to have multiple text areas added buff = self.builder.get_object('textview1').get_buffer() buff.set_text(temp) This works fine. It pulls the records out of the database, and then cats the results together and throws it into my TextView. I'm happy with the results so far, but I would like to be able to click on each record if I see something that needs to be modified. As always, any help is appreciated. Also, can anyone recommend a good book for gtk + glade + python? I went out and bought Learning Python, but book at B&N that were remotely GUI related seems very outdated or just tkinter related, and just about all the gtk+python examples and tutorials don't use glade. Thanks again. -Lang -- There are no stupid questions, just stupid people. From lang at tharin.com Sun Jun 20 04:04:48 2010 From: lang at tharin.com (Lang Hurst) Date: Sat, 19 Jun 2010 19:04:48 -0700 Subject: [Tutor] How to add extra Vbox fields dynamically In-Reply-To: <4C1D5DF8.9040009@tharin.com> References: <4C1D5DF8.9040009@tharin.com> Message-ID: <4C1D7740.6010008@tharin.com> OK, I just did the ugliest hack, from someone who only seems to do ugly hacks. I set up a bunch of textview areas and defaulted them to 'not visible'. Then as I loop through my query results, I make them visible one at a time. Well, it works perfect, but it just doesn't seem right for some reason. Lang Hurst wrote: > I hope that I'm asking this in the right place. I don't have too much > trouble hacking together command line stuff, but the GUI part is a > struggle for me. > > I created a UI in glade. It has a couple of Vboxes for information. > The final box is filled with a TextView. In my program, I'm > connecting to a database and pulling out a series of records. As it > stands, I can pull out all the records and view them in the TextView, > but I would like to be able to have each result be a separate TextView > (which I then have to figure out how to make clickable...) > > Right now, this part looks like: > > query = 'SELECT subject, chapter_module, credits, final_test_score, > notes FROM credits WHERE id=' + student[0][6] > cursor.execute(query) > credits = cursor.fetchall() > temp = '' > for credit in credits: > sub_buf = 15 - len(credit[0]) > chap_buf = 15 - len(credit[1]) > cred_buf = 5 - len(credit[2]) > score_buf = 5 - len(credit[1]) > temp = temp + credit[0] + " " * sub_buf + credit[1] + " " * > chap_buf + "Credits: " + credit[2] + " " * chap_buf + "Score: " + > credit[3] + "\n\nNOTES: " + credit[4] + "\n" + " " * 5 + "-" * 50 + > "\n\n" > > # I would like to loop something here > # to have multiple text areas added > > buff = self.builder.get_object('textview1').get_buffer() > buff.set_text(temp) > > > This works fine. It pulls the records out of the database, and then > cats the results together and throws it into my TextView. I'm happy > with the results so far, but I would like to be able to click on each > record if I see something that needs to be modified. As always, any > help is appreciated. > > Also, can anyone recommend a good book for gtk + glade + python? I > went out and bought Learning Python, but book at B&N that were > remotely GUI related seems very outdated or just tkinter related, and > just about all the gtk+python examples and tutorials don't use glade. > Thanks again. > > > -Lang > -- There are no stupid questions, just stupid people. From trdillah at gmail.com Sun Jun 20 08:03:00 2010 From: trdillah at gmail.com (T.R. D.) Date: Sun, 20 Jun 2010 02:03:00 -0400 Subject: [Tutor] Extracting xml text Message-ID: Hi, I'm trying to parse a list of xml strings and so far it looks like the xml.parsers.expat is the way to go but I'm not quite sure how it works. I'm trying to parse something similar to the following. I'd like to collect all headings and bodies and associate them in a variable (dictionary for example). How would I use the expat class to do this? Tove Jani Reminder Don't forget me this weekend! Jani Tovi Reminder 2 Don't forget to bring snacks! .... Here's the code that I have so far based on the documents I've read: actions = test.actions # Parse stepgreen actions parser = xml.parsers.expat.ParserCreate() parser.Parse(reminderXML) print parser.StartElementHandler; This doesn't work.... (even if there's one item in the list). Could someone please point me in the right direction? I haven't found any examples of what I'd like to do and I don't understand how expat works. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Sun Jun 20 10:12:27 2010 From: karim.liateni at free.fr (Karim) Date: Sun, 20 Jun 2010 10:12:27 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: References: Message-ID: <4C1DCD6B.1080707@free.fr> Hello, The following is an example which works for me to count opening tags in a xml doc, if it can help: # -*- coding: iso-8859-1 -*- import sys from xml.parsers.expat import ParserCreate n = 0 def start_element(name, attrs): # callback declaration global n n += 1 parser = ParserCreate() # cr?ation du parser parser.StartElementHandler = start_element # initialization parser.ParseFile(file(sys.argv[1])) # get the input file print '%d opening tags' % n Regards Karim France On 06/20/2010 08:03 AM, T.R. D. wrote: > xml strings and so far it looks like the xml.parsers.expat is the way > to go but I'm not quite sure how it works. From stefan_ml at behnel.de Sun Jun 20 10:14:52 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 20 Jun 2010 10:14:52 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: References: Message-ID: T.R. D., 20.06.2010 08:03: > I'm trying to parse a list of xml strings and so far it looks like the > xml.parsers.expat is the way to go but I'm not quite sure how it works. > > I'm trying to parse something similar to the following. I'd like to collect > all headings and bodies and associate them in a variable (dictionary for > example). How would I use the expat class to do this? Well, you *could* use it, but I *would* not recommend it. :) > > Tove > Jani > Reminder > Don't forget me this weekend! > > > > Jani > Tovi > Reminder 2 > Don't forget to bring snacks! > Use ElementTree's iterparse: from xml.etree.cElementTree import iterparse for _, element in iterparse("the_file.xml"): if element.tag == 'note': # find text in interesting child elements print element.findtext('heading'), element.findtext('body') # safe some memory by removing the handled content element.clear() iterparse() iterates over parser events, but it builds an in-memory XML tree while doing so. That makes it trivial to find things in the stream. The above code receives an event whenever a tag closes, and starts working when the closing tag is a 'note' element, i.e. when the complete subtree of the note element has been parsed into memory. Stefan From karim.liateni at free.fr Sun Jun 20 10:19:02 2010 From: karim.liateni at free.fr (Karim) Date: Sun, 20 Jun 2010 10:19:02 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: <4C1DCD6B.1080707@free.fr> References: <4C1DCD6B.1080707@free.fr> Message-ID: <4C1DCEF6.4070100@free.fr> In fact you must initialize the handler before parsing the xml doc and it should work. Regards Karim France On 06/20/2010 10:12 AM, Karim wrote: > > Hello, > > The following is an example which works for me to count opening tags > in a xml doc, > if it can help: > > # -*- coding: iso-8859-1 -*- > import sys > from xml.parsers.expat import ParserCreate > > n = 0 > def start_element(name, attrs): # callback declaration > global n > n += 1 > > parser = ParserCreate() # cr?ation du parser > parser.StartElementHandler = start_element # initialization > parser.ParseFile(file(sys.argv[1])) # get the input file > print '%d opening tags' % n > > Regards > Karim > France > > > On 06/20/2010 08:03 AM, T.R. D. wrote: >> xml strings and so far it looks like the xml.parsers.expat is the way >> to go but I'm not quite sure how it works. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Sun Jun 20 10:24:56 2010 From: karim.liateni at free.fr (Karim) Date: Sun, 20 Jun 2010 10:24:56 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: References: Message-ID: <4C1DD058.6070601@free.fr> Hello Stefan, I know you are promoting Etree and I am very interesting in it. Is there any chance to have it integrated in future standard Python version? Regards Karim On 06/20/2010 10:14 AM, Stefan Behnel wrote: > T.R. D., 20.06.2010 08:03: >> I'm trying to parse a list of xml strings and so far it looks like the >> xml.parsers.expat is the way to go but I'm not quite sure how it works. >> >> I'm trying to parse something similar to the following. I'd like to >> collect >> all headings and bodies and associate them in a variable (dictionary for >> example). How would I use the expat class to do this? > > Well, you *could* use it, but I *would* not recommend it. :) > > >> >> Tove >> Jani >> Reminder >> Don't forget me this weekend! >> >> >> >> Jani >> Tovi >> Reminder 2 >> Don't forget to bring snacks! >> > > Use ElementTree's iterparse: > > from xml.etree.cElementTree import iterparse > > for _, element in iterparse("the_file.xml"): > if element.tag == 'note': > # find text in interesting child elements > print element.findtext('heading'), element.findtext('body') > > # safe some memory by removing the handled content > element.clear() > > iterparse() iterates over parser events, but it builds an in-memory > XML tree while doing so. That makes it trivial to find things in the > stream. The above code receives an event whenever a tag closes, and > starts working when the closing tag is a 'note' element, i.e. when the > complete subtree of the note element has been parsed into memory. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Sun Jun 20 10:32:33 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 20 Jun 2010 10:32:33 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: <4C1DD058.6070601@free.fr> References: <4C1DD058.6070601@free.fr> Message-ID: Hi, please don't top-post, it makes your replies hard to read in context. Karim, 20.06.2010 10:24: > On 06/20/2010 10:14 AM, Stefan Behnel wrote: >> Use ElementTree's iterparse: >> >> from xml.etree.cElementTree import iterparse >> [...] > > I know you are promoting Etree and I am very interesting in it. > Is there any chance to have it integrated in future standard Python > version? The import above comes directly from the standard library (Python 2.5 and later). You may be referring to lxml.etree, which will most likely never make it into the stdlib. Stefan From timomlists at gmail.com Sun Jun 20 11:16:30 2010 From: timomlists at gmail.com (Timo) Date: Sun, 20 Jun 2010 11:16:30 +0200 Subject: [Tutor] How to add extra Vbox fields dynamically In-Reply-To: <4C1D7740.6010008@tharin.com> References: <4C1D5DF8.9040009@tharin.com> <4C1D7740.6010008@tharin.com> Message-ID: <4C1DDC6E.2010206@gmail.com> On 20-06-10 04:04, Lang Hurst wrote: > OK, I just did the ugliest hack, from someone who only seems to do > ugly hacks. I set up a bunch of textview areas and defaulted them to > 'not visible'. Then as I loop through my query results, I make them > visible one at a time. Well, it works perfect, but it just doesn't > seem right for some reason. You also posted this on the PyGTK mailing list, which is the correct place for these problems. Please post your PyGTK questions only there, do not double post. I'll answer you there. Cheers, Timo > > Lang Hurst wrote: >> I hope that I'm asking this in the right place. I don't have too >> much trouble hacking together command line stuff, but the GUI part is >> a struggle for me. >> >> I created a UI in glade. It has a couple of Vboxes for information. >> The final box is filled with a TextView. In my program, I'm >> connecting to a database and pulling out a series of records. As it >> stands, I can pull out all the records and view them in the TextView, >> but I would like to be able to have each result be a separate >> TextView (which I then have to figure out how to make clickable...) >> >> Right now, this part looks like: >> >> query = 'SELECT subject, chapter_module, credits, final_test_score, >> notes FROM credits WHERE id=' + student[0][6] >> cursor.execute(query) >> credits = cursor.fetchall() >> temp = '' >> for credit in credits: >> sub_buf = 15 - len(credit[0]) >> chap_buf = 15 - len(credit[1]) >> cred_buf = 5 - len(credit[2]) >> score_buf = 5 - len(credit[1]) >> temp = temp + credit[0] + " " * sub_buf + credit[1] + " " * >> chap_buf + "Credits: " + credit[2] + " " * chap_buf + "Score: " + >> credit[3] + "\n\nNOTES: " + credit[4] + "\n" + " " * 5 + "-" * 50 + >> "\n\n" >> >> # I would like to loop something here >> # to have multiple text areas added >> >> buff = self.builder.get_object('textview1').get_buffer() >> buff.set_text(temp) >> >> >> This works fine. It pulls the records out of the database, and then >> cats the results together and throws it into my TextView. I'm happy >> with the results so far, but I would like to be able to click on each >> record if I see something that needs to be modified. As always, any >> help is appreciated. >> >> Also, can anyone recommend a good book for gtk + glade + python? I >> went out and bought Learning Python, but book at B&N that were >> remotely GUI related seems very outdated or just tkinter related, and >> just about all the gtk+python examples and tutorials don't use >> glade. Thanks again. >> >> >> -Lang >> > > From payal-python at scriptkitchen.com Sun Jun 20 11:54:13 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 20 Jun 2010 02:54:13 -0700 Subject: [Tutor] re.sub() query Message-ID: <20100620095413.GA18626@scriptkitchen.com> Hi, Is it possible to solve the below, w/o making a re object? >>> a 'Mary Had a Little Lamb' >>> p=re.compile('l',re.I) >>> re.sub(p,'-',a) 'Mary Had a -itt-e -amb' I cannot figure how to se re.I w/o involving p. Thanks. With warm regards, -Payal -- From payal-python at scriptkitchen.com Sun Jun 20 11:59:35 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 20 Jun 2010 02:59:35 -0700 Subject: [Tutor] Question In-Reply-To: <270541.73354.qm@web86704.mail.ird.yahoo.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <4C1C9C82.80107@ieee.org> <270541.73354.qm@web86704.mail.ird.yahoo.com> Message-ID: <20100620095935.GB18626@scriptkitchen.com> On Sat, Jun 19, 2010 at 11:24:44AM +0000, ALAN GAULD wrote: > Actually that's a point. I favour learning two languages that are semantically > similar buut syntactically different. Thats why I chose JavaScript and VBScript > as my tutorial languages, because the syntax of each is so different you are > less likely to get confused, but the underlying programming model is very > similar in each case. Hijacking the thread a bit. What about learning Jython and Python? Do I need to know Java to learn Jython? With warm regards, -Payal -- From evert.rol at gmail.com Sun Jun 20 12:03:47 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 20 Jun 2010 12:03:47 +0200 Subject: [Tutor] re.sub() query In-Reply-To: <20100620095413.GA18626@scriptkitchen.com> References: <20100620095413.GA18626@scriptkitchen.com> Message-ID: > Is it possible to solve the below, w/o making a re object? > >>>> a > 'Mary Had a Little Lamb' >>>> p=re.compile('l',re.I) >>>> re.sub(p,'-',a) > 'Mary Had a -itt-e -amb' > > I cannot figure how to se re.I w/o involving p. Would this work? >>> re.sub('(?i)l', '-', a) See http://docs.python.org/library/re.html#regular-expression-syntax , search for iLmsux, which provide flags inside the regex. From payal-python at scriptkitchen.com Sun Jun 20 12:12:36 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 20 Jun 2010 03:12:36 -0700 Subject: [Tutor] re.sub() query In-Reply-To: References: <20100620095413.GA18626@scriptkitchen.com> Message-ID: <20100620101236.GC18626@scriptkitchen.com> On Sun, Jun 20, 2010 at 12:03:47PM +0200, Evert Rol wrote: > >>> re.sub('(?i)l', '-', a) > > See http://docs.python.org/library/re.html#regular-expression-syntax , search for iLmsux, which provide flags inside the regex. Goodness that was fast. Thanks a lot Evert. For records, >>> re.sub('l(?i)','-',a) 'Mary Had a -itt-e -amb' With warm regards, -Payal -- From breamoreboy at yahoo.co.uk Sun Jun 20 12:20:14 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Jun 2010 11:20:14 +0100 Subject: [Tutor] re.sub() query In-Reply-To: <20100620095413.GA18626@scriptkitchen.com> References: <20100620095413.GA18626@scriptkitchen.com> Message-ID: On 20/06/2010 10:54, Payal wrote: > Hi, > Is it possible to solve the below, w/o making a re object? > >>>> a > 'Mary Had a Little Lamb' >>>> p=re.compile('l',re.I) >>>> re.sub(p,'-',a) > 'Mary Had a -itt-e -amb' > > I cannot figure how to se re.I w/o involving p. > > Thanks. > With warm regards, > -Payal You can do this. >>> re.sub('[lL]','-',a) 'Mary Had a -itt-e -amb' However it strikes me as overkill to use an re for something that could be done with the string replace function. Kindest regards. Mark Lawrence. From edwardlang at optonline.net Sun Jun 20 13:01:20 2010 From: edwardlang at optonline.net (Edward Lang) Date: Sun, 20 Jun 2010 07:01:20 -0400 Subject: [Tutor] (no subject) Message-ID: A From edwardlang at optonline.net Sun Jun 20 12:46:25 2010 From: edwardlang at optonline.net (Edward Lang) Date: Sun, 20 Jun 2010 06:46:25 -0400 Subject: [Tutor] Tutor Digest, Vol 76, Issue 57 Message-ID: e 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. Re: Python glade (Lang Hurst) > 2. Re: Question (Alan Gauld) > 3. Re: Question (Steven D'Aprano) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Fri, 18 Jun 2010 21:50:23 -0700 >From: Lang Hurst >To: tutor at python.org >Subject: Re: [Tutor] Python glade >Message-ID: <4C1C4C8F.7080907 at tharin.com> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >Found the problem. If you want to do this, you have to access the >gtkEntry like this > > self.builder.get_object('student_change').set_completion(completion) > > >instead of > > self.student_change.set_completion(completion) > > > > > >Lang Hurst wrote: >> OK, I created a UI in glade which has the following: >> >> >> True >> True >> > name="invisible_char">● >> 25 >> > handler="student_change_activate_cb"/> >> >> >> >> basically, a text box. I'm trying to set it up to automatically >> complete names as I type. My py file has the following: >> >> def __init__(self): >> self.builder = gtk.Builder() >> self.builder.add_from_file('gradebook.glade') >> self.window = self.builder.get_object('winapp') >> self.builder.connect_signals(self) >> # self.student_change = gtk.Entry() >> completion = gtk.EntryCompletion() >> self.names = gtk.ListStore(str) >> query = "SELECT * from students" >> db = sqlite3.connect('gradebook.db') >> cursor = db.cursor() >> cursor.execute(query) >> students = cursor.fetchall() >> for student in students: >> self.names.append([student[1]]) >> print student[1] >> cursor.close() >> completion.set_model(self.names) >> self.student_change.set_completion(completion) >> completion.set_text_column(0) >> >> >> When I try to run this, I get >> >> AttributeError: 'appGUI' object has no attribute 'student_change' >> >> >> But if I uncomment the self.student_change line from up above, it runs >> but doesn't do completion. >> >> I modeled this after >> >> http://www.koders.com/python/fid755022E2A82A54C79A7CF86C00438E6F825676C3.aspx?s=gtk#L4 >> >> >> I'm pretty sure the problem is somewhere in the gtk.Builder part of >> what I'm doing, but I can't for the life of me figure this out. >> > > >-- >There are no stupid questions, just stupid people. > > > >------------------------------ > >Message: 2 >Date: Sat, 19 Jun 2010 09:19:09 +0100 >From: "Alan Gauld" >To: tutor at python.org >Subject: Re: [Tutor] Question >Message-ID: >Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > >"Independent Learner" wrote > >> ~I was wondering if I should try to learn 2 programming languages >> at once, Python and C++. > >No, no no! If it had been a different pair I might have said try it. >But C++ is one of the most difficult, complex and difficult >programming lamnguages out there. It is full of subtle things >that can trip you up and cause very weird and subtle bugs >that are diffficult to find. And it has similar concepts to Python >but implemented so entirely differently that studying the two >together will be an exercise in frustration. > >Part of the reason why C++ is so difficult is because it is >so powerful. You have full access to the machine through >the C language elements, plus a full OOP environment, >plus a powerful generic type system. Plus it combines >static and dynamic variables with a reference model all with >slightly different syntax and semantic behaviours. > >At work I hardly ever recommend that people go on language >training courses, C++ is the exception! You can learn C++ >by yourself but you will need a good book and a lot of >time and patience. > >> Obviously I am working on learning python right now, >> I have gotten up to Classes > >Stick with Python and get comfortable with that. > >Then move onto C++ as a separate and significant project >if you really feel you have a need to know it. > >> there are still a lot of things I am not really fully >> comprehending, but like I said I have a pretty good idea. > >Ask questions here. That's what the tutor list is for. > >> ~So is it better to learn 1 programming language >> first, then learn another. Or better to pretty much >> learn them at the same time? And why? > >If you had asked about Python and Object Pascal >or Ruby or even Lisp I'd have said sure, if you enjoy >comparative learning. Those languages are sufficiently >close to makle it worthwhile. (That's why I teach >VBScript and JavaScript as well as Python in >my tutor) But C++ is awash with gotchas and has >an internal object model completely different to Python. >(COBOL is another one that I'd never recommend >as a comparative languiage!) > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > > > > >------------------------------ > >Message: 3 >Date: Sat, 19 Jun 2010 18:56:34 +1000 >From: Steven D'Aprano >To: tutor at python.org >Subject: Re: [Tutor] Question >Message-ID: <201006191856.34526.steve at pearwood.info> >Content-Type: text/plain; charset="utf-8" > >On Sat, 19 Jun 2010 01:55:05 pm Independent Learner wrote: > >> ~I was wondering if I should try to learn 2 programming languages at >> once, Python and C++. > >I don't know. That depends on you. > >How much time do you have to spend on learning the languages? If it's >one hour a week, you'll have trouble learning *one* language, never >mind two. > >It really depends on you, and since we don't know you, we can't answer >that. > >Alan has said "No" because Python and C++ have radically different >programming models, and suggested that you should consider two >languages that are much more similar such as Python and Ruby. I don't >know about that... I think I'd much rather learn two different >languages, so that I could compartmentalise "these are Python rules" >and "these are C++ rules", rather constantly mixing up Python and Ruby >syntax and idioms and getting them confused. But your mileage may >vary -- maybe you're more like Alan than me. > > >> Yea I took an intro to comp sci?class(like 2 years ago) and a >> computer programming logic class(also like 2 years ago) both >> using?pseudocode? > >Good grief! How do they teach a class in computer programming using >pseudocode??? That's like teaching somebody to cook by handing them >Playdough and a toy oven that doesn't even get warm! > > >> and have since dabbled in C(I?started a programming >> class for school but dropped?out twice?after about 1/3 of? the >> semester, for two consecutive semesters about?9?months ago) So here I >> am,?a?computer engineering?major failure who had to change?my major >> to Physics so I wouldn't have to take all those dammed comp sci >> classes Figured I could just teach myself. I mention this because I >> want to make clear I have the logic and critical thinking skills >> down, and in my opinion the aptitude as well. > >I don't mean to be negative, but if you've dropped out of a programming >course *twice*, and then changed your major to avoid programming, >perhaps you're not cut out for programming? Obviously I don't know you, >maybe you have good reasons for dropping out unrelated to your ability >and intelligence, but speaking as a stranger, when you say "Hey guys, I >have a history of dropping out of a basic programming courses, but >don't worry, I've got the aptitude to be a programmer", it doesn't >really fill me with confidence. Perhaps that's something you should >keep more to yourself until *after* you've proven you do have the >chops? > > > >-- >Steven D'Aprano > > >------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest, Vol 76, Issue 57 >************************************* From bgailer at gmail.com Sun Jun 20 15:55:47 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 20 Jun 2010 09:55:47 -0400 Subject: [Tutor] Question In-Reply-To: <20100620095935.GB18626@scriptkitchen.com> References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <4C1C9C82.80107@ieee.org> <270541.73354.qm@web86704.mail.ird.yahoo.com> <20100620095935.GB18626@scriptkitchen.com> Message-ID: <4C1E1DE3.6040304@gmail.com> On 6/20/2010 5:59 AM, Payal wrote: > On Sat, Jun 19, 2010 at 11:24:44AM +0000, ALAN GAULD wrote: > >> Actually that's a point. I favour learning two languages that are semantically >> similar buut syntactically different. Thats why I chose JavaScript and VBScript >> as my tutorial languages, because the syntax of each is so different you are >> less likely to get confused, but the underlying programming model is very >> similar in each case. >> > Hijacking the thread a bit. What about learning Jython and Python? Do I > need to know Java to learn Jython? > No. Jython is "just" a Python interpreter written in Java. It allows you to use Java classes in your Python code. You might want to learn Java to take advantage of that. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Sun Jun 20 15:57:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Jun 2010 14:57:42 +0100 Subject: [Tutor] Question References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <201006191856.34526.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> Yea I took an intro to comp sci class(like 2 years ago) and a >> computer programming logic class(also like 2 years ago) both >> using pseudocode > > Good grief! How do they teach a class in computer programming using > pseudocode??? Yes, doing that 2 years ago seems odd. OTOH When I started at university the first year of comp sci we did everything in pseudo code. That was to emphasise that comp sci was the science of computation not computer programming. So the emphasis was on the theory of algorithms, logic and so on. (And comp sci dept was just a sub department of the math school...) But that was in the days when programs were punched out on paper tape (no card readers for me Bob :-) and the results came back in the post two days later - usually saying "missing semi colon: line 93". So using pseudo code to focus on the content rather than the mechancs made sense. 2 years ago that surely wouldn't have been true! But maybe the prof harked back to those "golden days"... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From trdillah at gmail.com Sun Jun 20 16:04:33 2010 From: trdillah at gmail.com (T.R. D.) Date: Sun, 20 Jun 2010 10:04:33 -0400 Subject: [Tutor] Extracting xml text In-Reply-To: References: <4C1DD058.6070601@free.fr> Message-ID: Thanks all for your help. I decided to go with iterparse but trying the simple example in the python interpreter led to an error (see below) and when I tried this with a much larger xml sample, it seemed to print the full elements, not the specific values of the element. For example, given what I entered in the python interpreter, the result would have been the full xml example, and not "Reminder" "Don't forget me this weekend". Did I do something wrong in the sample below? Thanks again. >>> from xml.etree.cElementTree import iterparse >>> sample = '''\ ... ... Tove ... Jani ... Reminder ... Don't forget me this weekend! ... ... ''' >>> print sample Tove Jani Reminder Don't forget me this weekend! >>> for event, elem in iterparse(sample): ... if elem.tag == 'note': ... print elem.findtext('heading'), elem.findtext('body') ... elem.clear() ... ... Traceback (most recent call last): File "", line 1, in File "", line 52, in __init__ IOError: [Errno 2] No such file or directory: "\n\tTove\n\tJani\n\tReminder\n\tDon't forget me this weekend!\n\n" >>> On Sun, Jun 20, 2010 at 4:32 AM, Stefan Behnel wrote: > Hi, > > please don't top-post, it makes your replies hard to read in context. > > Karim, 20.06.2010 10:24: > >> On 06/20/2010 10:14 AM, Stefan Behnel wrote: >> >>> Use ElementTree's iterparse: >>> >>> from xml.etree.cElementTree import iterparse >>> >> >> [...] > > > > >> I know you are promoting Etree and I am very interesting in it. >> Is there any chance to have it integrated in future standard Python >> version? >> > > The import above comes directly from the standard library (Python 2.5 and > later). You may be referring to lxml.etree, which will most likely never > make it into the stdlib. > > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sun Jun 20 16:15:55 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 20 Jun 2010 16:15:55 +0200 Subject: [Tutor] Extracting xml text In-Reply-To: References: <4C1DD058.6070601@free.fr> Message-ID: T.R. D., 20.06.2010 16:04: > I decided to go with iterparse but trying the simple example in the python > interpreter led to an error (see below) and when I tried this with a much > larger xml sample, it seemed to print the full elements, not the specific > values of the element. For example, given what I entered in the python > interpreter, the result would have been the full xml example, and not > "Reminder" "Don't forget me this weekend". > > Did I do something wrong in the sample below? Yes. You didn't follow the example and you didn't read the docs. > >>> from xml.etree.cElementTree import iterparse > >>> sample = '''\ > ... > ...Tove > ...Jani > ...Reminder > ...Don't forget me this weekend! > ... > ... ''' > >>> print sample > > Tove > Jani > Reminder > Don't forget me this weekend! > > > >>> for event, elem in iterparse(sample): > ... if elem.tag == 'note': > ... print elem.findtext('heading'), elem.findtext('body') > ... elem.clear() > ... > ... > Traceback (most recent call last): > File "", line 1, in > File "", line 52, in __init__ > IOError: [Errno 2] No such file or directory: > "\n\tTove\n\tJani\n\tReminder\n\tDon't > forget me this weekend!\n\n" That's pretty telling, isn't it? It's looking for the file of which you passed the filename. Since you passed XML string data as filename here, it can't find it. Wrap the data in a StringIO.StringIO instance instead (or io.BytesIO in Python 2.6 and later) and pass that into iterparse(). Stefan From alan.gauld at btinternet.com Sun Jun 20 16:19:45 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Jun 2010 15:19:45 +0100 Subject: [Tutor] Question References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> Message-ID: "Mark Lawrence" wrote > ...I take issue with this "learn a language in five minutes" bit. > It took me five years to get to grips with plain old C. C is non trivial but not hard (certainly compared to C++) But 5 years is enough to do a lot more than "get to grips with" a language, that's what I'd expect it to take to become fully fluent, maybe even the office expert! > Assume that the same applies to all other languages No, the diffference is huge between languages. I learned both awk and Logo in a week. Smalltalk took me three attempts and I still struggle every time I go back to it after 24 years! Same with Lisp, I am still learning Lisp despite having written production code in it 15 years ago! (Fortunately I have 3 Lisp guru's, one of whom was on the standards comittee, to whom I can turn for help!) But C only took me about 6 months to become proficient(*). COBOL about the same. Forth is easy to learn but difficult to master. (*)By which I mean good enough to write a control system for a cable extrusion line in a factory and a data encryption card for the original IBM PC, including intercepting BIOS calls etc. A guru C programmer could find lots of faults in my code but it worked and the clients paid money for the results! C++ took me about 2 years to feel comfortable and about 5 years to become one of the office gurus. The biggest system I've ever been involved with was primarily written in C++ - about 3 million lines of code. It only took about 2 years away to lose that skill again! > to make it simple, that means for me to get to grips with 30 > languages takes 150 years. I don't think I'll live to do that. To me, "get to grips" means good enough to write effective working code that can be used in professional production systems. A professional programmer often has no choice but to learn a new language and a new start will be lucky to get more than a couple of months to get up to full speed. You will be expected to be writing code within a couple of weeks, albeit with the manual permanently by your side. As I said earlier I've worked on single projects with over a dozen different languages going at once, if we'd waited for 5 years for each language we'd still be studying yet! As it was the total project time was only 3 years. And some of those languages were bespoke creations for that project. You don't need to be an expert in a language to be productive. And learning new languages invariably improves your skills in the ones you already know. That's why I've learned several languages that I've never used in projects - but the concepts they embodied were significant (Smalltalk is a good example. A colleague was using it in 1986 and I was fascinated by this new OOP paradigm so I started to use his environment during lunches and so on and learn the basics, but I have never use Smalltalk myself in a paid project - but I learned a lot from it. Haskell is another in the same category) Learning multiple languages is a way of improving your skills in your existing languages. It makes you a better programmer. But, it only works once you understand the basics and for that sticking to a single language is probably best. And Python is an ideal starter. Alan G. From alan.gauld at btinternet.com Sun Jun 20 16:23:33 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Jun 2010 15:23:33 +0100 Subject: [Tutor] Question References: <729070.67817.qm@web120014.mail.ne1.yahoo.com> <4C1C9C82.80107@ieee.org><270541.73354.qm@web86704.mail.ird.yahoo.com> <20100620095935.GB18626@scriptkitchen.com> Message-ID: "Payal" wrote > Hijacking the thread a bit. What about learning Jython and Python? > Do I > need to know Java to learn Jython? No, but you will need to know the class heirarchy and reading the documentation will be difficulty without at least a basic knowledge of the Java syntax. Also you will probably need to use the Java tools so familiarity with the JDK is useful. OTOH you can treat Jython exactly like Python and never look at Java - but that would be pointless! All you would have is a slower, less fully featured version of Python! Jython only makes sense if you are mixing Python and Java code in some way. And if you are doing that you probably need to know Java too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lang at tharin.com Mon Jun 21 00:42:42 2010 From: lang at tharin.com (Lang Hurst) Date: Sun, 20 Jun 2010 15:42:42 -0700 Subject: [Tutor] How to add extra Vbox fields dynamically In-Reply-To: <4C1DDC6E.2010206@gmail.com> References: <4C1D5DF8.9040009@tharin.com> <4C1D7740.6010008@tharin.com> <4C1DDC6E.2010206@gmail.com> Message-ID: <4C1E9962.1060709@tharin.com> OK, figured that was probably bad etiquette, but there doesn't seem to be close to the same traffic. Mea culpa. I won't do it again. I think most of my issues have to do with the gtk part, so I'll post there for the most part. Thanks. Timo wrote: > On 20-06-10 04:04, Lang Hurst wrote: >> OK, I just did the ugliest hack, from someone who only seems to do >> ugly hacks. I set up a bunch of textview areas and defaulted them to >> 'not visible'. Then as I loop through my query results, I make them >> visible one at a time. Well, it works perfect, but it just doesn't >> seem right for some reason. > You also posted this on the PyGTK mailing list, which is the correct > place for these problems. Please post your PyGTK questions only there, > do not double post. I'll answer you there. > > Cheers, > Timo > >> >> Lang Hurst wrote: >>> I hope that I'm asking this in the right place. I don't have too >>> much trouble hacking together command line stuff, but the GUI part >>> is a struggle for me. >>> >>> I created a UI in glade. It has a couple of Vboxes for >>> information. The final box is filled with a TextView. In my >>> program, I'm connecting to a database and pulling out a series of >>> records. As it stands, I can pull out all the records and view them >>> in the TextView, but I would like to be able to have each result be >>> a separate TextView (which I then have to figure out how to make >>> clickable...) >>> >>> Right now, this part looks like: >>> >>> query = 'SELECT subject, chapter_module, credits, final_test_score, >>> notes FROM credits WHERE id=' + student[0][6] >>> cursor.execute(query) >>> credits = cursor.fetchall() >>> temp = '' >>> for credit in credits: >>> sub_buf = 15 - len(credit[0]) >>> chap_buf = 15 - len(credit[1]) >>> cred_buf = 5 - len(credit[2]) >>> score_buf = 5 - len(credit[1]) >>> temp = temp + credit[0] + " " * sub_buf + credit[1] + " " * >>> chap_buf + "Credits: " + credit[2] + " " * chap_buf + "Score: " + >>> credit[3] + "\n\nNOTES: " + credit[4] + "\n" + " " * 5 + "-" * 50 + >>> "\n\n" >>> >>> # I would like to loop something here >>> # to have multiple text areas added >>> >>> buff = self.builder.get_object('textview1').get_buffer() >>> buff.set_text(temp) >>> >>> >>> This works fine. It pulls the records out of the database, and then >>> cats the results together and throws it into my TextView. I'm happy >>> with the results so far, but I would like to be able to click on >>> each record if I see something that needs to be modified. As >>> always, any help is appreciated. >>> >>> Also, can anyone recommend a good book for gtk + glade + python? I >>> went out and bought Learning Python, but book at B&N that were >>> remotely GUI related seems very outdated or just tkinter related, >>> and just about all the gtk+python examples and tutorials don't use >>> glade. Thanks again. >>> >>> >>> -Lang >>> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- There are no stupid questions, just stupid people. From electroblog at gmail.com Mon Jun 21 00:52:14 2010 From: electroblog at gmail.com (Joe Veldhuis) Date: Sun, 20 Jun 2010 18:52:14 -0400 Subject: [Tutor] Converting audio samples from 16-bit signed int to float? Message-ID: <20100620185214.ca8eb023.electroblog@gmail.com> Hello all. I'm writing a program that needs to capture audio from a soundcard and run FFTs to determine peak frequency for further processing. The soundcard's native capture format is 16-bit little-endian signed integer samples (values 0-65535), and of course the FFT function requires floating-point values (-1.0 - +1.0). So, what is the most efficient way to do the necessary conversion? I'm using the pyalsaaudio module to access the soundcard, if it matters. -Joe Veldhuis From neil.thorman at gmail.com Sun Jun 20 20:38:20 2010 From: neil.thorman at gmail.com (Neil Thorman) Date: Sun, 20 Jun 2010 19:38:20 +0100 Subject: [Tutor] New to this Message-ID: I'm picking this up as a hobby really, not having done any programming since Acorn I'm pretty much starting form scratch (and even back in the BASIC day I never really got to grips with files). This is from Alan Gauld's Learning to Program: Handling Files. http://www.freenetpages.co.uk/hp/alan.gauld/ Can I just check I'm getting it? *Menu.txt contains* *Spam & Eggs* *Spam & Chips* *Spam & Spam* >>>inp = file("menu.txt", "r") *What is inp? What does it now contain?* *The following creates a list;* * * * >>>print inp.readlines() ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] but if I do it again I get: >>> print inp.readlines() [] I'm baffled, why is inp now empty? Many thanks Neil ps. I'm working in the IDLE Python Shell. * * * * * * * * * This email is confidential and intended for addressee only . -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Mon Jun 21 01:01:12 2010 From: modulok at gmail.com (Modulok) Date: Sun, 20 Jun 2010 17:01:12 -0600 Subject: [Tutor] Data exchange formats... Message-ID: List, What's the best format to send data across the wire between processes? I have some simple 'insensitive' data I need to send from a client, to a server via a TCP socket. Things like 'count = 10, name="foo"' and so forth. Basic values. I would use something like the 'pickle' module to pack them up send as encoded strings, which would then be loaded on the server. It'd be nice, but the server has no authentication. Therefore: "Warning The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source." Currently I'm sending strings and using regular expressions on the server to pluck out the needed data, but thought there must be something cleaner, nicer and better. Ideas? From mehgcap at gmail.com Mon Jun 21 01:02:55 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 20 Jun 2010 19:02:55 -0400 Subject: [Tutor] New to this In-Reply-To: References: Message-ID: On 6/20/10, Neil Thorman wrote: > I'm picking this up as a hobby really, not having done any programming since > Acorn I'm pretty much starting form scratch (and even back in the BASIC day > I never really got to grips with files). > This is from Alan Gauld's Learning to Program: Handling Files. > http://www.freenetpages.co.uk/hp/alan.gauld/ > > Can I just check I'm getting > it? > > > *Menu.txt contains* > > *Spam & Eggs* > *Spam & Chips* > *Spam & Spam* > >>>>inp = file("menu.txt", "r") > *What is inp? What does it now contain?* It is now a reference to the location of the txt file. Python calls these file "objects", where an object is just something on which you can call functions. If you had a dog object you might call a "bark" method; here, we have a file object, so we can see what the file is. inp is not the file itself, just as any object is not the full object's info but rather a pointer to where that info is. If you were to print inp, I think you would get a memory address. > *The following creates a list;* > * > * > * >>>>print inp.readlines() > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] > > but if I do it again I get: >>>> print inp.readlines() > [] > > I'm baffled, why is inp now empty? I suspect you have hit the end of the file. I rarely work with files myself, but I believe there is a way to reset your pointer in the file to the top; after the readlines call, that pointer is at the end of the file. > > Many thanks > > Neil > > ps. I'm working in the IDLE Python Shell. > * > * > * > * > * > * > * > * > * > > > This email is confidential and intended for addressee only . > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From adam.jtm30 at gmail.com Mon Jun 21 01:03:42 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 21 Jun 2010 00:03:42 +0100 Subject: [Tutor] Converting audio samples from 16-bit signed int to float? In-Reply-To: <20100620185214.ca8eb023.electroblog@gmail.com> References: <20100620185214.ca8eb023.electroblog@gmail.com> Message-ID: On 20 June 2010 23:52, Joe Veldhuis wrote: > Hello all. I'm writing a program that needs to capture audio from a > soundcard and run FFTs to determine peak frequency for further processing. > The soundcard's native capture format is 16-bit little-endian signed integer > samples (values 0-65535), and of course the FFT function requires > floating-point values (-1.0 - +1.0). > > So, what is the most efficient way to do the necessary conversion? I'm > using the pyalsaaudio module to access the soundcard, if it matters. > > -Joe Veldhuis > Not sure it's the best way but the most obvious to me would be divide by 32767.5 (ie half 65535) and minus 1 puts you into the right range: >>> 65535/32767.5-1 1.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Mon Jun 21 01:10:40 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 21 Jun 2010 00:10:40 +0100 Subject: [Tutor] New to this In-Reply-To: References: Message-ID: On 20 June 2010 19:38, Neil Thorman wrote: > I'm picking this up as a hobby really, not having done any programming > since Acorn I'm pretty much starting form scratch (and even back in the > BASIC day I never really got to grips with files). > This is from Alan Gauld's Learning to Program: Handling Files. > http://www.freenetpages.co.uk/hp/alan.gauld/ > > Can I just check I'm getting > it? > > > *Menu.txt contains* > > *Spam & Eggs* > *Spam & Chips* > *Spam & Spam* > > >>>inp = file("menu.txt", "r") > *What is inp? What does it now contain?* > *The following creates a list;* > inp is a file object. > * > * > * > >>>print inp.readlines() > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] > > * > readlines is a method of inp. It's basically a function that works specifically on that object, in this case it reads each line from the file and puts it into a list and then returns it; the shell then prints it out. > * > but if I do it again I get: > >>> print inp.readlines() > [] > > * > At this point you have reached the end of the file so there are no more lines to read, if you just want one line at a time then you should use inp.read() > * > I'm baffled, why is inp now empty? > * > inp isn't really empty it's still a file object there is just no data left to read. > * > > Many thanks > > Neil > > ps. I'm working in the IDLE Python Shell. > * > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 21 01:19:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Jun 2010 00:19:51 +0100 Subject: [Tutor] New to this References: Message-ID: "Neil Thorman" wrote >>>>inp = file("menu.txt", "r") > *What is inp? What does it now contain?* >>>>print inp.readlines() > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] > > but if I do it again I get: >>>> print inp.readlines() > [] > > I'm baffled, why is inp now empty? OK, I've been asked thios before so I guess I need to add an explanation to the tutor! When you work with files its like using a cursor to indicate where you are in the file. When you firwst open the file the cursor is at the beginning of the file. As you read content the cursor moves through the file. If you use teadlines() you read the whole file in so that the cursor is at the end of the file. If you try calling readlines again there is no more data to read so you get an empty list. You can reset the cursor using the seek() method inp.seek(0) Now readlines() will return the data again. I'll try to write that up a bit more clearly and add it to the files topic. HTH< -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 21 01:47:10 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Jun 2010 00:47:10 +0100 Subject: [Tutor] Data exchange formats... References: Message-ID: "Modulok" wrote > What's the best format to send data across the wire between > processes? That depends on what you measure as 'best' - data volume, speed of transmission, security, data complexity, flexibility, ease of decoding etc etc. > a server via a TCP socket. Things like 'count = 10, name="foo"' and > so > forth. Basic values. You could use the struct module to pack them as binary then unpack at the far end. Its space efficient and relatively easy to pack/unpack and marginally more secure than plain text. But only marginally! > I would use something like the 'pickle' module to > pack them up send as encoded strings, which would then be loaded on > the server. It'd be nice, but the server has no authentication. > Therefore: > > "Warning The pickle module is not intended to be secure against > erroneous or maliciously constructed data. Never unpickle data > received from an untrusted or unauthenticated source." That might not be a problem if security is not an issue. > Currently I'm sending strings and using regular expressions on the > server to pluck out the needed data, but thought there must be > something cleaner, nicer and better. Ideas? XML? There are a variety of parsers out there. http form submission? Again there are numerous CGI solutions. You could even use https for security... Or you can construct a plain text string - comma separated using the csv module, and then encryupt using one of the crypto algorithms available. It all depends on what you want to do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 21 01:54:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Jun 2010 00:54:43 +0100 Subject: [Tutor] New to this References: Message-ID: "Neil Thorman" wrote > This is from Alan Gauld's Learning to Program: Handling Files. > http://www.freenetpages.co.uk/hp/alan.gauld/ One other thing. That page is now quite old and out of date. You should switch to the current web site: http://www.alan-g.me.uk/ >>>>inp = file("menu.txt", "r") > *What is inp? What does it now contain?* inp is a variable and it is referencing the file object you created using the file() function. (As the tutor points out you could also use open() and in fact open() is now preferred over file() ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Jun 21 01:56:05 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Jun 2010 09:56:05 +1000 Subject: [Tutor] Data exchange formats... In-Reply-To: References: Message-ID: <201006210956.05463.steve@pearwood.info> On Mon, 21 Jun 2010 09:01:12 am Modulok wrote: > List, > > What's the best format to send data across the wire between > processes? Consider json or yaml. json comes in the standard library, at least in version 2.6; yaml does not. I don't know if they are secure, but it's worth checking. If your data consists of key:value pairs (which apparently it does), also consider the plistlib module. > I have some simple 'insensitive' data I need to send from a client, > to a server via a TCP socket. Things like 'count = 10, name="foo"' > and so forth. Basic values. I would use something like the 'pickle' > module to pack them up send as encoded strings, which would then be > loaded on the server. It'd be nice, but the server has no > authentication. Therefore: > > "Warning The pickle module is not intended to be secure against > erroneous or maliciously constructed data. Never unpickle data > received from an untrusted or unauthenticated source." What's your threat model? Malicious sys admin on the remote client? CIA listening in? Business competitor injecting erroneous data? Receiving data from random places on the Internet? You control both machines, right next to each other in the same locked server room guarded by crocodiles, and you have the only key? Depending on how serious your threat model is, the right solution might be to insist on authentication on both machines and use SSH between the two. -- Steven D'Aprano From steve at pearwood.info Mon Jun 21 02:22:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Jun 2010 10:22:34 +1000 Subject: [Tutor] New to this In-Reply-To: References: Message-ID: <201006211022.34814.steve@pearwood.info> On Mon, 21 Jun 2010 09:02:55 am Alex Hall wrote: > On 6/20/10, Neil Thorman wrote: [...] > >>>>inp = file("menu.txt", "r") > > > > *What is inp? What does it now contain?* > > It is now a reference to the location of the txt file. [pedantic] No, it's actually an abstract data structure that wraps the actual file itself. A reference to the *location* of the file would be: inp = "menu.txt" Locations are strings. File objects are file objects. [/pedantic] But in a practical sense, pay no attention to the man behind the curtain (the implementation details). inp is a file in every way which matters, just like after: n = 42 x = 1.234 n is an int and x a float in every way which matters. > Python calls > these file "objects", where an object is just something on which you > can call functions. If you had a dog object you might call a "bark" > method; here, we have a file object, so we can see what the file is. > inp is not the file itself, just as any object is not the full > object's info but rather a pointer to where that info is. If you were > to print inp, I think you would get a memory address. You would get a string printed to the console, like printing *anything*. >>> print inp That string happens to contain a hex number which looks like it could be a memory address, but that's an implementation detail because CPython doesn't sufficiently abstract its objects from the underlying C implementation. Python file objects aren't "files" only in the sense that they exist in memory rather than on disk in the file system, but other than that, I believe your explanation is at too low a level to be helpful. Neil said he's a beginner who hasn't done any programming since BASIC on an Acorn, and you're talking about low-level details like memory locations. Let me guess, you're also a C programmer? As far as coding in Python is concerned, inp = file(pathname) creates a file object, which *is* a file in all practical sense. Everything else is just an implementation detail, which could change depending on the version of Python, the operating system, and the underlying hardware. [...] > >>>>print inp.readlines() > > > > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] > > > > but if I do it again I get: > >>>> print inp.readlines() > > > > [] > > > > I'm baffled, why is inp now empty? > > I suspect you have hit the end of the file. Yes. readlines reads from the current file position, like all read operations. To read all the text again, you have to reset the file position with seek: inp.seek(0) -- Steven D'Aprano From mehgcap at gmail.com Mon Jun 21 02:37:19 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 20 Jun 2010 20:37:19 -0400 Subject: [Tutor] New to this In-Reply-To: <201006211022.34814.steve@pearwood.info> References: <201006211022.34814.steve@pearwood.info> Message-ID: On 6/20/10, Steven D'Aprano wrote: > On Mon, 21 Jun 2010 09:02:55 am Alex Hall wrote: >> On 6/20/10, Neil Thorman wrote: > [...] >> >>>>inp = file("menu.txt", "r") >> > >> > *What is inp? What does it now contain?* >> >> It is now a reference to the location of the txt file. > > [pedantic] > No, it's actually an abstract data structure that wraps the actual file > itself. A reference to the *location* of the file would be: > > inp = "menu.txt" > > Locations are strings. File objects are file objects. > [/pedantic] > > But in a practical sense, pay no attention to the man behind the curtain > (the implementation details). inp is a file in every way which matters, > just like after: > > n = 42 > x = 1.234 > > n is an int and x a float in every way which matters. > > >> Python calls >> these file "objects", where an object is just something on which you >> can call functions. If you had a dog object you might call a "bark" >> method; here, we have a file object, so we can see what the file is. >> inp is not the file itself, just as any object is not the full >> object's info but rather a pointer to where that info is. If you were >> to print inp, I think you would get a memory address. > > You would get a string printed to the console, like printing *anything*. > >>>> print inp > Oh right, the object's toString method (or whatever Python calls this; Java and Javascript call it toString, and it exists for all objects). > > That string happens to contain a hex number which looks like it could be > a memory address, but that's an implementation detail because CPython > doesn't sufficiently abstract its objects from the underlying C > implementation. > > Python file objects aren't "files" only in the sense that they exist in > memory rather than on disk in the file system, but other than that, I > believe your explanation is at too low a level to be helpful. Neil said > he's a beginner who hasn't done any programming since BASIC on an > Acorn, and you're talking about low-level details like memory > locations. Let me guess, you're also a C programmer? Good point, and sorry for going into too much detail, much of which is not on the mark anyway. :) No, I have hardly touched c++, but I am starting my final year of a computer science degree in a few months so I have had all the details of objects and how the computer actually accesses them in several classes. > > As far as coding in Python is concerned, inp = file(pathname) creates a > file object, which *is* a file in all practical sense. Everything else > is just an implementation detail, which could change depending on the > version of Python, the operating system, and the underlying hardware. Very true. > > > [...] >> >>>>print inp.readlines() >> > >> > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] >> > >> > but if I do it again I get: >> >>>> print inp.readlines() >> > >> > [] >> > >> > I'm baffled, why is inp now empty? >> >> I suspect you have hit the end of the file. > > Yes. readlines reads from the current file position, like all read > operations. To read all the text again, you have to reset the file > position with seek: > > inp.seek(0) > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From __peter__ at web.de Mon Jun 21 15:19:19 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Jun 2010 15:19:19 +0200 Subject: [Tutor] Converting audio samples from 16-bit signed int to float? References: <20100620185214.ca8eb023.electroblog@gmail.com> Message-ID: Joe Veldhuis wrote: > Hello all. I'm writing a program that needs to capture audio from a > soundcard and run FFTs to determine peak frequency for further processing. > The soundcard's native capture format is 16-bit little-endian signed > integer samples (values 0-65535), and of course the FFT function requires > floating-point values (-1.0 - +1.0). > > So, what is the most efficient way to do the necessary conversion? I'm > using the pyalsaaudio module to access the soundcard, if it matters. Using numpy should be pretty efficient. Assuming you get your data as a bytestring: >>> import numpy >>> data = "\x00\x80\x00\x00\xff\x7f" >>> a = numpy.fromstring(data, dtype=">> a array([-32768, 0, 32767], dtype=int16) >>> a/32768. array([-1. , 0. , 0.99996948]) Or, if you don't find the half-open interval acceptable: >>> (a+.5)/32767.5 array([ -1.00000000e+00, 1.52590219e-05, 1.00000000e+00]) If you want to use the full interval and avoid moving the origin: >>> (a>0)*a/32767.+(a<0)*a/32768. array([-1., 0., 1.]) (There may be a better way as I'm not very familiar with numpy and found the above by trial and error) Peter From neil.thorman.listserver at googlemail.com Mon Jun 21 15:39:26 2010 From: neil.thorman.listserver at googlemail.com (Neil Thorman) Date: Mon, 21 Jun 2010 14:39:26 +0100 Subject: [Tutor] New to this In-Reply-To: References: <201006211022.34814.steve@pearwood.info> Message-ID: Thanks all. I think my fundamental error was in thinking of *menu.tx*t as the file and * inp* as containing it's contents in some way. Much more helpful to think of *inp* as the file and then do things to it. Thanks again Neil This email is confidential and intended for addressee only . On Mon, Jun 21, 2010 at 1:37 AM, Alex Hall wrote: > On 6/20/10, Steven D'Aprano wrote: > > On Mon, 21 Jun 2010 09:02:55 am Alex Hall wrote: > >> On 6/20/10, Neil Thorman wrote: > > [...] > >> >>>>inp = file("menu.txt", "r") > >> > > >> > *What is inp? What does it now contain?* > >> > >> It is now a reference to the location of the txt file. > > > > [pedantic] > > No, it's actually an abstract data structure that wraps the actual file > > itself. A reference to the *location* of the file would be: > > > > inp = "menu.txt" > > > > Locations are strings. File objects are file objects. > > [/pedantic] > > > > But in a practical sense, pay no attention to the man behind the curtain > > (the implementation details). inp is a file in every way which matters, > > just like after: > > > > n = 42 > > x = 1.234 > > > > n is an int and x a float in every way which matters. > > > > > >> Python calls > >> these file "objects", where an object is just something on which you > >> can call functions. If you had a dog object you might call a "bark" > >> method; here, we have a file object, so we can see what the file is. > >> inp is not the file itself, just as any object is not the full > >> object's info but rather a pointer to where that info is. If you were > >> to print inp, I think you would get a memory address. > > > > You would get a string printed to the console, like printing *anything*. > > > >>>> print inp > > > Oh right, the object's toString method (or whatever Python calls this; > Java and Javascript call it toString, and it exists for all objects). > > > > That string happens to contain a hex number which looks like it could be > > a memory address, but that's an implementation detail because CPython > > doesn't sufficiently abstract its objects from the underlying C > > implementation. > > > > Python file objects aren't "files" only in the sense that they exist in > > memory rather than on disk in the file system, but other than that, I > > believe your explanation is at too low a level to be helpful. Neil said > > he's a beginner who hasn't done any programming since BASIC on an > > Acorn, and you're talking about low-level details like memory > > locations. Let me guess, you're also a C programmer? > Good point, and sorry for going into too much detail, much of which is > not on the mark anyway. :) No, I have hardly touched c++, but I am > starting my final year of a computer science degree in a few months so > I have had all the details of objects and how the computer actually > accesses them in several classes. > > > > As far as coding in Python is concerned, inp = file(pathname) creates a > > file object, which *is* a file in all practical sense. Everything else > > is just an implementation detail, which could change depending on the > > version of Python, the operating system, and the underlying hardware. > Very true. > > > > > > [...] > >> >>>>print inp.readlines() > >> > > >> > ['spam & eggs\n', 'spam & chips\n', 'spam & spam'] > >> > > >> > but if I do it again I get: > >> >>>> print inp.readlines() > >> > > >> > [] > >> > > >> > I'm baffled, why is inp now empty? > >> > >> I suspect you have hit the end of the file. > > > > Yes. readlines reads from the current file position, like all read > > operations. To read all the text again, you have to reset the file > > position with seek: > > > > inp.seek(0) > > > > > > > > -- > > Steven D'Aprano > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ahmedn82 at hotmail.com Tue Jun 22 13:13:48 2010 From: ahmedn82 at hotmail.com (Ahmed AL-Masri) Date: Tue, 22 Jun 2010 19:13:48 +0800 Subject: [Tutor] Time Message-ID: Hi, I would calculate the running time of my simulation code. any one know how to do that? example def demo(): ########### the starting point of time should be 0 f.simulate(data) ########### the end of the class so need to find the time in Sec.? ########### print time in sec. if __name__ == '__main__': demo() look forward to seeing the answer, Thanks a lot, A. Naufal -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Jun 22 13:32:19 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 22 Jun 2010 13:32:19 +0200 Subject: [Tutor] Time In-Reply-To: References: Message-ID: <4C209F43.9060905@compuscan.co.za> Ahmed AL-Masri wrote: > Hi, > I would calculate the running time of my simulation code. > any one know how to do that? > > example > > def demo(): > ########### the starting point of time should be 0 > f.simulate(data) > ########### the end of the class so need to find the time in Sec.? > ########### print time in sec. > if __name__ == '__main__': > demo() > > look forward to seeing the answer, > > Thanks a lot, > A. Naufal > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You can take a look at the timeit module [1] and some nice examples [2]. [1] http://docs.python.org/library/timeit.html [2] http://www.doughellmann.com/PyMOTW/timeit/ -- Kind Regards, Christian Witts From mehgcap at gmail.com Tue Jun 22 14:40:13 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 22 Jun 2010 08:40:13 -0400 Subject: [Tutor] upgrade from 2.6.2 to 2.6.5? Message-ID: Hi all, I am having problems with the Durus package, and I was told that changing Python versions might help. Most of the other dependencies of the project I have are 2.6 only, so I do not want to change versions from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that fixes things. Will I lose all my packages (in lib/site-packages) if I do this? Will anything else break, as far as third-party installs go? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From mail at timgolden.me.uk Tue Jun 22 15:05:11 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 Jun 2010 14:05:11 +0100 Subject: [Tutor] upgrade from 2.6.2 to 2.6.5? In-Reply-To: References: Message-ID: <4C20B507.5070702@timgolden.me.uk> On 22/06/2010 13:40, Alex Hall wrote: > Hi all, > I am having problems with the Durus package, and I was told that > changing Python versions might help. Most of the other dependencies of > the project I have are 2.6 only, so I do not want to change versions > from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that > fixes things. Will I lose all my packages (in lib/site-packages) if I > do this? Will anything else break, as far as third-party installs go? Nope. That should just work (assuming your 3rd-party installs aren't susceptible to changes occurring between 2.6.2 and 2.6.5... although, that said, you're *relying* on Durus being affected by such changes :) ) TJG From mehgcap at gmail.com Tue Jun 22 15:19:19 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 22 Jun 2010 09:19:19 -0400 Subject: [Tutor] upgrade from 2.6.2 to 2.6.5? In-Reply-To: <4C20B507.5070702@timgolden.me.uk> References: <4C20B507.5070702@timgolden.me.uk> Message-ID: Thanks, I'll go upgrade then, and hope this fixes things with this package! On 6/22/10, Tim Golden wrote: > On 22/06/2010 13:40, Alex Hall wrote: >> Hi all, >> I am having problems with the Durus package, and I was told that >> changing Python versions might help. Most of the other dependencies of >> the project I have are 2.6 only, so I do not want to change versions >> from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that >> fixes things. Will I lose all my packages (in lib/site-packages) if I >> do this? Will anything else break, as far as third-party installs go? > > Nope. That should just work (assuming your 3rd-party installs aren't > susceptible to changes occurring between 2.6.2 and 2.6.5... although, > that said, you're *relying* on Durus being affected by such changes :) ) > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From rdmoores at gmail.com Tue Jun 22 22:58:25 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 22 Jun 2010 13:58:25 -0700 Subject: [Tutor] split struggle Message-ID: Please see my Python 3.1 code pasted at . This does what I want, which is to do one of: 1. print all the elements of the list, lst. 2. print "Done" when "" is entered. 3. print the elements of lst whose indexes are entered. (sorry if all this is obvious) Now, the code works, but isn't there a better way to do what I want? I've been away from Python for a while, and have gotten rusty. Thanks Dick Moores From alan.gauld at btinternet.com Wed Jun 23 00:09:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Jun 2010 23:09:08 +0100 Subject: [Tutor] split struggle References: Message-ID: "Richard D. Moores" wrote > This does what I want, which is to do one of: > 1. print all the elements of the list, lst. > 2. print "Done" when "" is entered. > 3. print the elements of lst whose indexes are entered. > (sorry if all this is obvious) > > Now, the code works, but isn't there a better way to do what I want? > I've been away from Python for a while, and have gotten rusty. Its pretty straightforward, I'm not sure what you are thinking of to simplify/improve it. The only change I'd make is the last else: > indexes = [int(k) for k in indexes] You don't need the list comp > print(indexes) > for i in indexes: > print(lst[int(i)]) Will do what you want. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jun 23 00:11:04 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Jun 2010 08:11:04 +1000 Subject: [Tutor] split struggle In-Reply-To: References: Message-ID: <201006230811.05073.steve@pearwood.info> On Wed, 23 Jun 2010 06:58:25 am Richard D. Moores wrote: > Please see my Python 3.1 code pasted at > . > > This does what I want, which is to do one of: > 1. print all the elements of the list, lst. > 2. print "Done" when "" is entered. > 3. print the elements of lst whose indexes are entered. > (sorry if all this is obvious) > > Now, the code works, but isn't there a better way to do what I want? > I've been away from Python for a while, and have gotten rusty. Seems reasonable to me. Sometimes the simple things are the best. The only thing I'd do is pre-process the "all" case: lst = [100,101,102,103] indexes = input("'Enter indexes': ").split(",") if indexes == ["all"]: indexes = list(range(len(lst)) if indexes == [""]: print("Done") else: indexes = [int(k) for k in indexes] print(indexes) for i in indexes: print(lst[i]) -- Steven D'Aprano From clsdaniel at gmail.com Wed Jun 23 01:55:28 2010 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 22 Jun 2010 16:55:28 -0700 Subject: [Tutor] Reading Excel Files Message-ID: Hello list, I was wondering if anyone has worked with excel 2007 files (importing data from), I have done so for old format (xls) via a number of modules like xlrd and the old pyexcelerator, however none of those packages currently support new 2007 format, although xlrd may have support for it later. Has anyone had to deal with something like this recently?, I'm thinking as last resort just work with the underlying XML files of the format, but it would be nice to have an already working module. Regards, Carlos Ruvalcaba From davea at ieee.org Wed Jun 23 03:11:32 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Jun 2010 21:11:32 -0400 Subject: [Tutor] Time In-Reply-To: References: Message-ID: <4C215F44.8030104@ieee.org> Ahmed AL-Masri wrote: > Hi, > I would calculate the running time of my simulation code. > any one know how to do that? > > example > > def demo(): > ########### the starting point of time should be 0 > f.simulate(data) > ########### the end of the class so need to find the time in Sec.? > ########### print time in sec. > if __name__ == '__main__': > demo() > > look forward to seeing the answer, > > Thanks a lot, > A. Naufal > If you're really looking to measure performance, you should use the timeit module. But for simply deciding how much time has elapsed between two points in your code, you can use the time.time() function. import time start = time.time() ... do some work end = time.time()-start DaveA From rdmoores at gmail.com Wed Jun 23 04:16:59 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 22 Jun 2010 19:16:59 -0700 Subject: [Tutor] split struggle In-Reply-To: References: Message-ID: On Tue, Jun 22, 2010 at 15:09, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> This does what I want, which is to do one of: >> 1. print all the elements of the list, lst. >> 2. print "Done" when "" is entered. >> 3. print the elements of lst whose indexes are entered. >> (sorry if all this is obvious) >> >> Now, the code works, but isn't there a better way to do what I want? >> I've been away from Python for a while, and have gotten rusty. > > Its pretty straightforward, I'm not sure what you are thinking of > to simplify/improve it. > > The only change I'd make is the last else: > >> indexes = [int(k) for k in indexes] > > You don't need the list comp > >> ? print(indexes) >> ? for i in indexes: >> ? ? ? print(lst[int(i)]) > > Will do what you want. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Wed Jun 23 04:20:24 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 22 Jun 2010 19:20:24 -0700 Subject: [Tutor] split struggle In-Reply-To: References: Message-ID: On Tue, Jun 22, 2010 at 15:09, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> This does what I want, which is to do one of: >> 1. print all the elements of the list, lst. >> 2. print "Done" when "" is entered. >> 3. print the elements of lst whose indexes are entered. >> (sorry if all this is obvious) >> >> Now, the code works, but isn't there a better way to do what I want? >> I've been away from Python for a while, and have gotten rusty. > > Its pretty straightforward, I'm not sure what you are thinking of > to simplify/improve it. > > The only change I'd make is the last else: > >> indexes = [int(k) for k in indexes] > > You don't need the list comp > >> ? print(indexes) >> ? for i in indexes: >> ? ? ? print(lst[int(i)]) > > Will do what you want. Thanks, Alan, that's the kind of thing I was looking for. I also learned from Steven D'Aprano's reply. Dick Moores From lang at tharin.com Wed Jun 23 07:44:28 2010 From: lang at tharin.com (Lang Hurst) Date: Tue, 22 Jun 2010 22:44:28 -0700 Subject: [Tutor] Reading Excel Files In-Reply-To: References: Message-ID: <4C219F3C.8040701@tharin.com> Carlos Daniel Ruvalcaba Valenzuela wrote: > Hello list, > > I was wondering if anyone has worked with excel 2007 files (importing > data from), I have done so for old format (xls) via a number of > modules like xlrd and the old pyexcelerator, however none of those > packages currently support new 2007 format, although xlrd may have > support for it later. > > Couldn't you just save it in the older format? > Has anyone had to deal with something like this recently?, I'm > thinking as last resort just work with the underlying XML files of the > format, but it would be nice to have an already working module. > > The files I work with are pretty basic, so I just export them as cvs and work from there. Probably not what you want. > Regards, > Carlos Ruvalcaba > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > -- There are no stupid questions, just stupid people. From marky1991 at gmail.com Wed Jun 23 07:51:04 2010 From: marky1991 at gmail.com (Mark Young) Date: Wed, 23 Jun 2010 01:51:04 -0400 Subject: [Tutor] Calling a number's methods Message-ID: Why does this work >>> a = 6 >>> b = 7 >>> answer = a.__sub__(b.__neg__()) >>> answer 13 but this does not? >>> answer = 6.__sub__(7.__neg__()) SyntaxError: invalid syntax I searched the internet, and found someone suggest adding spaces after each number, which indeed works properly. >>> answer = 6 .__sub__(7 .__neg__()) >>> answer 13 Why does this work? I don't even understand why python recognizes that I'm trying to access the numbers' __sub__ and __neg__ methods, I would think that the spaces would cause it to not work, but obviously it works just fine. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From clsdaniel at gmail.com Wed Jun 23 07:53:46 2010 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 22 Jun 2010 22:53:46 -0700 Subject: [Tutor] Reading Excel Files In-Reply-To: <4C219F3C.8040701@tharin.com> References: <4C219F3C.8040701@tharin.com> Message-ID: That is what I'm currently doing (telling users to convert), however users tend to forget to save the file in old format or find it too much a hassle to do the extra step, in which case I would like to be able to read the new format, although I may just trow and error and recommend the user to convert the format, lets see how they take that. Regards, Carlos Ruvalcaba On Tue, Jun 22, 2010 at 10:44 PM, Lang Hurst wrote: > Carlos Daniel Ruvalcaba Valenzuela wrote: >> >> Hello list, >> >> I was wondering if anyone has worked with excel 2007 files (importing >> data from), I have done so for old format (xls) via a number of >> modules like xlrd and the old pyexcelerator, however none of those >> packages currently support new 2007 format, although xlrd may have >> support for it later. >> >> > > Couldn't you just save it in the older format? > >> Has anyone had to deal with something like this recently?, I'm >> thinking as last resort just work with the underlying XML files of the >> format, but it would be nice to have an already working module. >> >> > > The files I work with are pretty basic, so I just export them as cvs and > work from there. ?Probably not what you want. > >> Regards, >> Carlos Ruvalcaba >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > -- > There are no stupid questions, just stupid people. > > From alan.gauld at btinternet.com Wed Jun 23 08:47:47 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Jun 2010 07:47:47 +0100 Subject: [Tutor] Calling a number's methods References: Message-ID: "Mark Young" wrote > I searched the internet, and found someone suggest adding spaces > after each > number, which indeed works properly. > >>>> answer = 6 .__sub__(7 .__neg__()) >>>> answer > 13 > > Why does this work? I don't even understand why python recognizes > that I'm > trying to access the numbers' __sub__ and __neg__ methods, I would > think > that the spaces would cause it to not work, but obviously it works > just > fine. I assume that's a hard coded hack in python to avoid some ambiguity with decimal points. But I'm not sure. And I'd have thought it should be possible to disambiguate without the space... But that's my guess. I've certainly never come across this "feature" before. Alan G. From alan.gauld at btinternet.com Wed Jun 23 08:51:23 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Jun 2010 07:51:23 +0100 Subject: [Tutor] Reading Excel Files References: Message-ID: "Carlos Daniel Ruvalcaba Valenzuela" wrote > I was wondering if anyone has worked with excel 2007 files > (importing > data from), I have done so for old format (xls) via a number of > modules like xlrd and the old pyexcelerator, however none of those > packages currently support new 2007 format, although xlrd may have > support for it later. It would e a radical reworking of your code but you could use COM to access the data. That should be portable across Excel upgrades in future too. You can do COM via the pythonwin libraries. But it will only work if your program is running under Windows with Excel installed on the same machine... Just a thought, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marky1991 at gmail.com Wed Jun 23 09:41:58 2010 From: marky1991 at gmail.com (Mark Young) Date: Wed, 23 Jun 2010 03:41:58 -0400 Subject: [Tutor] Calling a number's methods In-Reply-To: References: Message-ID: Hmm, apparently python doesn't care about whitespace in method calls or attribute access: class person: def __init__(self): self.name ="jim" def hi(self): print("hello") >>> guy = person() >>> guy . name 'jim' >>> guy . hi() hello That at least explains that part of my question. I never knew this, although it's pretty ugly, so I guess it's fairly useless information. Thanks for the guess, Alan. That seems reasonable. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 23 13:28:33 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Jun 2010 21:28:33 +1000 Subject: [Tutor] Calling a number's methods In-Reply-To: References: Message-ID: <201006232128.33591.steve@pearwood.info> On Wed, 23 Jun 2010 04:47:47 pm Alan Gauld wrote: > "Mark Young" wrote > > > I searched the internet, and found someone suggest adding spaces > > after each > > number, which indeed works properly. > > > >>>> answer = 6 .__sub__(7 .__neg__()) > >>>> answer > > > > 13 > > > > Why does this work? I don't even understand why python recognizes > > that I'm > > trying to access the numbers' __sub__ and __neg__ methods, I would > > think > > that the spaces would cause it to not work, but obviously it works > > just > > fine. > > I assume that's a hard coded hack in python to avoid some ambiguity > with decimal points. But I'm not sure. No, it seems to be by design of the syntax: whitespace within an expression always separates tokens, and you can use as much of it, or as little, as you like: >>> "abc" . upper () + "XYZ".lower() 'ABCxyz' >>> [ 2 , 3 , 4 ] +[5,6,7] [2, 3, 4, 5, 6, 7] The only time when you *must* use whitespace between tokens is to avoid ambiguity, e.g. around the `is` operator, or when using dot method access on a literal int or float. I'm sure this wasn't added to Python specifically to allow calling methods on numeric literals. You can use parentheses for that: >>> (1).__str__() '1' This will be a side-effect of the fact that you can always add a space around tokens and have them still work fine. -- Steven D'Aprano From steve at pearwood.info Wed Jun 23 13:14:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Jun 2010 21:14:34 +1000 Subject: [Tutor] Time In-Reply-To: <4C215F44.8030104@ieee.org> References: <4C215F44.8030104@ieee.org> Message-ID: <201006232114.34710.steve@pearwood.info> On Wed, 23 Jun 2010 11:11:32 am Dave Angel wrote: > If you're really looking to measure performance, you should use the > timeit module. But for simply deciding how much time has elapsed > between two points in your code, you can use the time.time() > function. > > import time > > start = time.time() > ... do some work > end = time.time()-start Just to re-iterate what Dave said, don't use this technique for timing small code snippets, it isn't accurate enough to give meaningful results. For that, use timeit. But for reporting how long some big chunk of work took, that's perfectly fine, e.g. if you expect to print something like this: "Processed 1734 records in 8.2 seconds." -- Steven D'Aprano From nethirlon at gmail.com Wed Jun 23 14:29:11 2010 From: nethirlon at gmail.com (Nethirlon .) Date: Wed, 23 Jun 2010 14:29:11 +0200 Subject: [Tutor] Repeat function until... Message-ID: Hello everyone, I'm new at programming with python and have a question about how I can solve my problem the correct way. Please forgive my grammar, English is not my primary language. I'm looking for a way to repeat my function every 30 seconds. As an example I have written a ping function. But I would like this function to repeat itself every 30 seconds, without stopping until I give it a STOP command (if such a thing exists.) Code: import os, sys def check(host): try: output = os.popen('ping -ns 1 %s' % host).read() alive = output.find('Reply from') print alive if alive is -1: print '%s \t\t DOWN ' % host else: print '%s \t\t OK' % host except OSError, e: print e sys.exit() check('www.google.com') Let me know if anything is unclear or if there are other recommendations about doing some parts different. Kind regards, Nethirlon From adam.jtm30 at gmail.com Wed Jun 23 15:38:49 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 23 Jun 2010 14:38:49 +0100 Subject: [Tutor] Repeat function until... In-Reply-To: References: Message-ID: On 23 June 2010 13:29, Nethirlon . wrote: > Hello everyone, > > I'm new at programming with python and have a question about how I can > solve my problem the correct way. Please forgive my grammar, English > is not my primary language. > > I'm looking for a way to repeat my function every 30 seconds. > > As an example I have written a ping function. But I would like this > function to repeat itself every 30 seconds, without stopping until I > give it a STOP command (if such a thing exists.) > > Code: > import os, sys > > def check(host): > try: > output = os.popen('ping -ns 1 %s' % host).read() > alive = output.find('Reply from') > print alive > if alive is -1: > print '%s \t\t DOWN ' % host > else: > print '%s \t\t OK' % host > except OSError, e: > print e > sys.exit() > > check('www.google.com') > > Let me know if anything is unclear or if there are other > recommendations about doing some parts different. > > Kind regards, > Nethirlon > You should probably take a look at the time module http://docs.python.org/library/time.html for waiting (maybe time.sleep) If you want to call a function an unspecified number of times you probably want a while loop: while True: pass loops infinitely unless you quit the program though, to leave the loop you will need to use "break", you will probably want an if statement and change the value of some variable when you want to stop calling the function and break out of the loop. HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 23 15:51:25 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Jun 2010 23:51:25 +1000 Subject: [Tutor] Repeat function until... In-Reply-To: References: Message-ID: <201006232351.26290.steve@pearwood.info> On Wed, 23 Jun 2010 10:29:11 pm Nethirlon . wrote: > Hello everyone, > > I'm new at programming with python and have a question about how I > can solve my problem the correct way. Please forgive my grammar, > English is not my primary language. > > I'm looking for a way to repeat my function every 30 seconds. The easiest way is to just run forever, and stop when the user interrupts it with ctrl-D (or ctrl-Z on Windows): # untested def call_again(n, func, *args): """call func(*args) every n seconds until ctrl-D""" import time try: while 1: start = time.time() func(*args) time.sleep(n - (time.time()-start)) except KeyboardInterrupt: pass Of course, that wastes a lot of time sleeping. As an alternative, you need to look at threads. That's a big topic, you probably need to read a How To or three on threads. In the meantime, here are a couple of recipes I found by googling. I have no idea of they are good or not. http://code.activestate.com/recipes/576726-interval-execute-a-function/ http://code.activestate.com/recipes/65222-run-a-task-every-few-seconds/ > As an example I have written a ping function. But I would like this > function to repeat itself every 30 seconds, without stopping until I > give it a STOP command (if such a thing exists.) > > Code: > import os, sys > > def check(host): > try: > output = os.popen('ping -ns 1 %s' % host).read() > alive = output.find('Reply from') > print alive > if alive is -1: > print '%s \t\t DOWN ' % host > else: > print '%s \t\t OK' % host > except OSError, e: > print e > sys.exit() Why are you catching the exception, only to print it and exit? Python does that automatically. This much easier, and doesn't throw away useful information: def check(host): output = os.popen('ping -ns 1 %s' % host).read() alive = output.find('Reply from') print alive if alive is -1: print '%s \t\t DOWN ' % host else: print '%s \t\t OK' % host -- Steven D'Aprano From emile at fenx.com Wed Jun 23 16:04:42 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 23 Jun 2010 07:04:42 -0700 Subject: [Tutor] Repeat function until... In-Reply-To: <201006232351.26290.steve@pearwood.info> References: <201006232351.26290.steve@pearwood.info> Message-ID: On 6/23/2010 6:51 AM Steven D'Aprano said... > # untested > def call_again(n, func, *args): > """call func(*args) every n seconds until ctrl-D""" > import time > try: > while 1: > start = time.time() > func(*args) > time.sleep(n - (time.time()-start)) Watch out for this -- you may want to do time.sleep(n - max(0,(time.time()-start))) to avoid passing sleep a negative number which causes the big sleep... Emile From zebra05 at gmail.com Wed Jun 23 16:29:44 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Wed, 23 Jun 2010 16:29:44 +0200 Subject: [Tutor] Repeat function until... In-Reply-To: References: Message-ID: My two cents' worth added below. Seems to do what you want. You probably want to call sys.wait(x) after printing an error, so it can be read before exiting? import os, sys, time def check(host): try: output = os.popen('ping -ns 1 %s' % host).read() alive = output.find('Reply from') print alive if alive is -1: print '%s \t\t DOWN ' % host else: print '%s \t\t OK' % host except OSError, e: print e sys.exit() while alive != -1: try: time.sleep(4) check(host) except KeyboardInterrupt, k: sys.exit() def get_command(): prompt = input('Start now? Use 1 to start or 0 to exit.\n') return prompt if __name__ == '__main__': cmd = get_command() if cmd == 1: check('localhost') elif cmd == 0: sys.exit() else: get_command() On Wed, Jun 23, 2010 at 2:29 PM, Nethirlon . wrote: > Hello everyone, > > I'm new at programming with python and have a question about how I can > solve my problem the correct way. Please forgive my grammar, English > is not my primary language. > > I'm looking for a way to repeat my function every 30 seconds. > > As an example I have written a ping function. But I would like this > function to repeat itself every 30 seconds, without stopping until I > give it a STOP command (if such a thing exists.) > > Code: > import os, sys > > def check(host): > try: > output = os.popen('ping -ns 1 %s' % host).read() > alive = output.find('Reply from') > print alive > if alive is -1: > print '%s \t\t DOWN ' % host > else: > print '%s \t\t OK' % host > except OSError, e: > print e > sys.exit() > > check('www.google.com') > > Let me know if anything is unclear or if there are other > recommendations about doing some parts different. > > Kind regards, > Nethirlon > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Wed Jun 23 16:31:49 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Wed, 23 Jun 2010 16:31:49 +0200 Subject: [Tutor] Repeat function until... In-Reply-To: References: Message-ID: ^^ I meant time.sleep(x), rather. Please excuse the double post. On Wed, Jun 23, 2010 at 4:29 PM, Sithembewena Lloyd Dube wrote: > My two cents' worth added below. Seems to do what you want. You probably > want to call sys.wait(x) after printing an error, so it can be read before > exiting? > > import os, sys, time > > > def check(host): > try: > output = os.popen('ping -ns 1 %s' % host).read() > alive = output.find('Reply from') > print alive > if alive is -1: > print '%s \t\t DOWN ' % host > else: > print '%s \t\t OK' % host > > except OSError, e: > print e > sys.exit() > > while alive != -1: > try: > time.sleep(4) > check(host) > > except KeyboardInterrupt, k: > sys.exit() > > def get_command(): > prompt = input('Start now? Use 1 to start or 0 to exit.\n') > return prompt > > if __name__ == '__main__': > cmd = get_command() > if cmd == 1: > check('localhost') > > elif cmd == 0: > sys.exit() > > else: > get_command() > > On Wed, Jun 23, 2010 at 2:29 PM, Nethirlon . wrote: > >> Hello everyone, >> >> I'm new at programming with python and have a question about how I can >> solve my problem the correct way. Please forgive my grammar, English >> is not my primary language. >> >> I'm looking for a way to repeat my function every 30 seconds. >> >> As an example I have written a ping function. But I would like this >> function to repeat itself every 30 seconds, without stopping until I >> give it a STOP command (if such a thing exists.) >> >> Code: >> import os, sys >> >> def check(host): >> try: >> output = os.popen('ping -ns 1 %s' % host).read() >> alive = output.find('Reply from') >> print alive >> if alive is -1: >> print '%s \t\t DOWN ' % host >> else: >> print '%s \t\t OK' % host >> except OSError, e: >> print e >> sys.exit() >> >> check('www.google.com') >> >> Let me know if anything is unclear or if there are other >> recommendations about doing some parts different. >> >> Kind regards, >> Nethirlon >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Regards, > Sithembewena Lloyd Dube > http://www.lloyddube.com > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Jun 23 16:34:12 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 23 Jun 2010 10:34:12 -0400 Subject: [Tutor] Repeat function until... In-Reply-To: <201006232351.26290.steve@pearwood.info> References: <201006232351.26290.steve@pearwood.info> Message-ID: <4C221B64.5070902@ieee.org> Steven D'Aprano wrote: > On Wed, 23 Jun 2010 10:29:11 pm Nethirlon . wrote: > >> Hello everyone, >> >> I'm new at programming with python and have a question about how I >> can solve my problem the correct way. Please forgive my grammar, >> English is not my primary language. >> >> I'm looking for a way to repeat my function every 30 seconds. >> > > > The easiest way is to just run forever, and stop when the user > interrupts it with ctrl-D (or ctrl-Z on Windows): > > # untested > def call_again(n, func, *args): > """call func(*args) every n seconds until ctrl-D""" > import time > try: > while 1: > start = time.time() > func(*args) > time.sleep(n - (time.time()-start)) > except KeyboardInterrupt: > pass > > Of course, that wastes a lot of time sleeping. > > But "wasting time" was the stated goal. If there's nothing else the application needs to do, sleep() is perfect. I'm sure you know, but maybe some others don't: sleep() uses essentially no CPU time, so the other applications on the system get all the performance. > As an alternative, you need to look at threads. That's a big topic, you > probably need to read a How To or three on threads. > > Only if there's other things that need doing in the same application. DaveA From __peter__ at web.de Wed Jun 23 16:46:41 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Jun 2010 16:46:41 +0200 Subject: [Tutor] split struggle References: Message-ID: Richard D. Moores wrote: > Please see my Python 3.1 code pasted at > . > > This does what I want, which is to do one of: > 1. print all the elements of the list, lst. > 2. print "Done" when "" is entered. > 3. print the elements of lst whose indexes are entered. > (sorry if all this is obvious) > > Now, the code works, but isn't there a better way to do what I want? > I've been away from Python for a while, and have gotten rusty. Although the code gets slightly more complex having a look at the cmd module may be worthwhile. Once you have set up the bases you can add commands by adding a do_xxx() method assuming 'xxx' is the name of the command. Tab completion works (for commands) and you get a rudimentary help function for free. $ cat indexes.py import cmd class Cmd(cmd.Cmd): prompt = "Enter a command -> " def precmd(self, line): if line.strip().isdigit(): # treat a lone integer as a shortcut # for the 'one' command return "one " + line if not line: return "EOF" return line def do_all(self, line): "print all items" for i, item in enumerate(items): print_item(i) def do_one(self, line): i = int(line) print_item(i) def do_EOF(self, line): print("That's all, folks") return True items = [100,101,102,103] def print_item(i): print(i, "->", items[i]) Cmd().cmdloop("Enter a command or type 'help' for help") $ python3 indexes.py Enter a command or type 'help' for help Enter a command -> help Documented commands (type help ): ======================================== all Undocumented commands: ====================== EOF help one Enter a command -> one 1 1 -> 101 Enter a command -> help all print all items Enter a command -> all 0 -> 100 1 -> 101 2 -> 102 3 -> 103 Enter a command -> 3 3 -> 103 Enter a command -> That's all, folks $ From python at bdurham.com Wed Jun 23 18:10:45 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 23 Jun 2010 12:10:45 -0400 Subject: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives? Message-ID: <1277309445.2173.1381531403@webmail.messagingengine.com> Can someone confirm that Python 2.6 ftplib does *NOT* support Unicode file names? Or must Unicode file names be specially encoded in order to be used with the ftplib module? The following email exchange seems to support my conclusion that the ftplib module only supports ASCII file names. Should ftplib use UTF-8 instead of latin-1 encoding? http://mail.python.org/pipermail/python-dev/2009-January/085408.html Any recommendations on a 3rd party Python module that supports Unicode file names? I've googled this question without success[1], [2]. The official Python documentation does not mention Unicode file names[3]. Thank you, Malcolm [1] ftputil wraps ftplib and inherits ftplib's apparent ASCII only support. [2] Paramiko's SFTP library does support Unicode file names, however I'm looking specifically for ftp (vs. sftp) support relative to our current project. [3] http://docs.python.org/library/ftplib.html From alan.gauld at btinternet.com Wed Jun 23 20:09:38 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Jun 2010 19:09:38 +0100 Subject: [Tutor] Repeat function until... References: <201006232351.26290.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > The easiest way is to just run forever, and stop when the user > interrupts it with ctrl-D (or ctrl-Z on Windows): I think that would be Ctrl-C on both. Ctrl-D/Z is EOF not Interrupt. Certainly on Windows Ctrl-Z won't interrupt a loop. But the principle is good and definitely the easiest option. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zebra05 at gmail.com Wed Jun 23 21:52:37 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Wed, 23 Jun 2010 21:52:37 +0200 Subject: [Tutor] Repeat function until... In-Reply-To: References: <201006232351.26290.steve@pearwood.info> Message-ID: My code has two bugs. If any command other than an int is entered, it falls over ungracefully. Also, if any integers other than 1 or 0 are entered successively it exits the Python interpreter. I thought I would point this out so as not to mislead the OP. On Wed, Jun 23, 2010 at 8:09 PM, Alan Gauld wrote: > > "Steven D'Aprano" wrote > >> The easiest way is to just run forever, and stop when the user interrupts >> it with ctrl-D (or ctrl-Z on Windows): >> > > I think that would be Ctrl-C on both. > Ctrl-D/Z is EOF not Interrupt. Certainly on Windows Ctrl-Z won't interrupt > a loop. > > But the principle is good and definitely the easiest option. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 23 22:13:11 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Jun 2010 06:13:11 +1000 Subject: [Tutor] Repeat function until... In-Reply-To: References: <201006232351.26290.steve@pearwood.info> Message-ID: <201006240613.11642.steve@pearwood.info> On Thu, 24 Jun 2010 04:09:38 am Alan Gauld wrote: > "Steven D'Aprano" wrote > > > The easiest way is to just run forever, and stop when the user > > interrupts it with ctrl-D (or ctrl-Z on Windows): > > I think that would be Ctrl-C on both. > Ctrl-D/Z is EOF not Interrupt. Certainly on Windows Ctrl-Z won't > interrupt a loop. Doh! Thanks for the correction. -- Steven D'Aprano From g.nius.ck at gmail.com Thu Jun 24 04:36:45 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 23 Jun 2010 22:36:45 -0400 Subject: [Tutor] finally Message-ID: In a try except clause, you can end with finally block. I know it runs after the try and except blocks regardless of the outcome, but why use it. Couldn't you just put the code after the try and except block without using a finally block. Does the finally command do something I don't know about. Does it make your program more understandable in some way? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 24 04:59:00 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 23 Jun 2010 19:59:00 -0700 Subject: [Tutor] finally In-Reply-To: References: Message-ID: <4C22C9F4.3080907@gmail.com> On 6/23/2010 7:36 PM, Christopher King wrote: > In a try except clause, you can end with finally block. I know it > runs after the try and except blocks regardless of the outcome, but > why use it. Couldn't you just put the code after the try and except > block without using a finally block. Does the finally command do > something I don't know about. Does it make your program more > understandable in some way? Did you read the manual? "If finally <#finally> is present, it specifies a 'cleanup' handler. The try <#try> clause is executed, including any except <#except> and else <#else> clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally <#finally> clause is executed. If there is a saved exception, it is re-raised at the end of the finally <#finally> clause. If the finally <#finally> clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally <#finally> clause. "When a return , break or continue statement is executed in the try <#try> suite of a try <#try>...finally <#finally> statement, the finally <#finally> clause is also executed 'on the way out.' A continue statement is illegal in the finally <#finally> clause. (The reason is a problem with the current implementation --- this restriction may be lifted in the future)." -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Jun 24 07:31:47 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 23 Jun 2010 22:31:47 -0700 Subject: [Tutor] Use flag to exit? Message-ID: I've read (I can't remember where) that for every prime p there there are positive integers a and b such that p = a + b and such that 2**a*3**b is either 1 greater than or 1 less than another (much larger) prime. I don't know if this has been proven or not, but I've tested it on all primes 3 < p <= 5689. Here's my script that produces a big prime number from a small one (p > 3): . My question is how to best exit when the big prime has been found. I used a flag (see the highlighted lines 34,40,44), but I seem to remember that, though they can work, flags are frowned upon by Pythonistas, and should be used only when absolutely necessary. So, is one necessary in my script? Thanks, Dick Moores From nethirlon at gmail.com Thu Jun 24 08:18:46 2010 From: nethirlon at gmail.com (Nethirlon) Date: Thu, 24 Jun 2010 08:18:46 +0200 Subject: [Tutor] Repeat function until... In-Reply-To: <201006240613.11642.steve@pearwood.info> References: <201006232351.26290.steve@pearwood.info> <201006240613.11642.steve@pearwood.info> Message-ID: On Wed, Jun 23, 2010 at 10:13 PM, Steven D'Aprano wrote: > On Thu, 24 Jun 2010 04:09:38 am Alan Gauld wrote: >> "Steven D'Aprano" wrote >> >> > The easiest way is to just run forever, and stop when the user >> > interrupts it with ctrl-D (or ctrl-Z on Windows): >> >> I think that would be Ctrl-C on both. >> Ctrl-D/Z is EOF not Interrupt. Certainly on Windows Ctrl-Z won't >> interrupt a loop. > > Doh! > > Thanks for the correction. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thank you all for replying to my question. It helped a lot and I have the solution to my problem thanks to you all! Kind regards, Nethirlon From eike.welk at gmx.net Thu Jun 24 08:47:20 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 24 Jun 2010 08:47:20 +0200 Subject: [Tutor] Use flag to exit? In-Reply-To: References: Message-ID: <201006240847.20945.eike.welk@gmx.net> On Thursday June 24 2010 07:31:47 Richard D. Moores wrote: > My question is how to best exit when the big prime has been found. I > used a flag (see the highlighted lines 34,40,44), but I seem to > remember that, though they can work, flags are frowned upon by > Pythonistas, and should be used only when absolutely necessary. So, is > one necessary in my script? I think a good way to exit from deep down in a complicated algorithm is to raise an exception: class FoundPrimeException(Exception): def __init__(self, big_p): Exception.__init__(self) self.prime = big_p Then you put your lines 33 to 43 between a try:... except construction and raise your exception in line 40. In the except ...: block you handle the prime that you have found. Here are my proposed modifications to your lines 33 to 47: try: for b in range(p-1,0,-1): a = p - b one_off_big_p = 2**a*3**b for x in [one_off_big_p - 1, one_off_big_p + 1]: if isPrime(x): raise FoundPrimeException(x) except FoundPrimeException, e: big_p = e.big_p print("The smaller prime", p, "determined this prime, ") print("with", len(str(big_p)), "digits:") print(big_p) print("a and b were", a, b) time1 = time() print("Time was", round((time1-time0),2), "secs") I hope I didn't break your algorithm; I'm typing this directly into the email program. Eike. From benjamin.pritchard at gmail.com Wed Jun 23 17:35:24 2010 From: benjamin.pritchard at gmail.com (Benjamin Pritchard) Date: Wed, 23 Jun 2010 11:35:24 -0400 Subject: [Tutor] unsubscribe Message-ID: unsubscribe From petkovas at dir.bg Wed Jun 23 14:03:06 2010 From: petkovas at dir.bg (petkovas at dir.bg) Date: Wed, 23 Jun 2010 14:03:06 +0200 Subject: [Tutor] TypeError when io.open is used Message-ID: Hello all! I would like to ask you the following: what should i do to be executed my correctly? The error: Traceback : File "insert_into_db_v9.py", line 55, in TypeError: an integer is required The code i use is the following: import psycopg2 import os from os import sep, listdir, path import io libfolder = "C:\\Blender_Library\\BlenderLib\\objectLib\\" #we are in C:\\Blender_Library\\BlenderLib\\objectLib\\ for dir1 in os.listdir(libfolder): print libfolder + dir1 if os.path.isdir(os.path.dirname(libfolder + dir1)): tempdir = libfolder + dir1 tempfiles = os.listdir(tempdir) #we are for example in C:\\Blender_Library\\BlenderLib\\objectLib\\Osaka" for f in tempfiles: if os.path.isdir(libfolder + dir1 + os.sep + f): tempdir1 = libfolder + dir1 + os.sep + f tempfiles1 = os.listdir(tempdir1) #we are for example in C:\\Blender_Library\\BlenderLib\\objectLib\\Faqns\\Osaka" for ff in tempfiles1: print libfolder + dir1 + os.sep + f + os.sep + ff if ff[-5:] == "blend": # !!! that is test data. It must be changed conn=psycopg2.connect("host=localhost dbname=postgres user=postgres password=test") #conn.cursor will return a cursor oject, you can use this cursor to perform queries cursor = conn.cursor() # psycopg2.Binary() escapes all data that needs that data1 = psycopg2.Binary(io.open( tempdir1 + os.sep + ff, 'rb' ).read()) # execute our Query cursor.execute("""UPDATE testtable SET blend = %s) WHERE testtable_n = %s""", data1, str(os.path.splitext(file)[0])) # Save (commit) the changes conn.commit() # We can also close the cursor if we are done with it cursor.close() elif ff[-3:] == "jpg" or ff[-4:] == "jpeg": # !!! that is test data. It must be changed conn=psycopg2.connect("host=localhost dbname=postgres user=postgres password=test") #conn.cursor will return a cursor oject, you can use this cursor to perform queries cursor = conn.cursor() # psycopg2.Binary() escapes all data that needs that data1 = psycopg2.Binary(io.open( tempdir1 + os.sep + ff, 'rb' ).read()) # execute our Query cursor.execute("""UPDATE testtable SET jpeg = %s) WHERE testtable_n = %s""", data1, str(os.path.splitext(file)[0])) # Save (commit) the changes conn.commit() # We can also close the cursor if we are done with it cursor.close() elif ff[-3:] == "txt": # !!! that is test data. It must be changed conn=psycopg2.connect("host=localhost dbname=postgres user=postgres password=test") #conn.cursor will return a cursor oject, you can use this cursor to perform queries cursor = conn.cursor() From alan.gauld at btinternet.com Thu Jun 24 09:11:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jun 2010 08:11:52 +0100 Subject: [Tutor] TypeError when io.open is used References: Message-ID: wrote > The error: > Traceback : > File "insert_into_db_v9.py", line 55, in > TypeError: an integer is required Can you send the full error text please? I'm not sure which is line 55 and Python normally displays the faulty line as part of the error trace. As it is I can't see any reason for it to fail but I'd like to be sure I'm looking at the right place! Also is there any reason why you explicitly call io.open() instead of just using the built-in open() directly? I know they are the same function but its quite unusual to use the io version explicitly... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Thu Jun 24 09:16:05 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 00:16:05 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: <201006240847.20945.eike.welk@gmx.net> References: <201006240847.20945.eike.welk@gmx.net> Message-ID: On Wed, Jun 23, 2010 at 23:47, Eike Welk wrote: > On Thursday June 24 2010 07:31:47 Richard D. Moores wrote: > I hope I didn't break your algorithm; I'm typing this directly into the email > program. I did what you said (), and get "invalid syntax" for the comma in line 40. Taking a stab in the dark I change line 40 as shown in http://tutoree7.pastebin.com/ybJsm3Rj Now I get >>> The prime greater than or equal to 100 is 101 Traceback (most recent call last): File "C:/P31Working/prime_to_biggest_prime_tutor2_Eike2.py", line 40, in except (FoundPrimeException, e): NameError: name 'FoundPrimeException' is not defined >>> Dick From rdmoores at gmail.com Thu Jun 24 10:39:23 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 01:39:23 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: References: Message-ID: On Wed, Jun 23, 2010 at 22:31, Richard D. Moores wrote: > I've read (I can't remember where) that for every prime p there there > are positive integers a and b such that p = a + b and such that > 2**a*3**b is either 1 greater than or 1 less than another (much > larger) prime. I don't know if this has been proven or not, but I've > tested it on all primes 3 < p <= 5689. Here's my script that produces > a big prime number from a small one (p > 3): > . > > My question is how to best exit when the big prime has been found. I > used a flag (see the highlighted lines 34,40,44), but I seem to > remember that, though they can work, flags are frowned upon by > Pythonistas, and should be used only when absolutely necessary. So, is > one necessary in my script? > > Thanks, > > Dick Moores Can't I use sys.exit(). In . For n = 333 I get the output The prime greater than or equal to 333 is 337 The smaller prime 337 determined this much larger prime, which has 121 digits: 12965282936790350290684656658525333839833593063568777527873447337564535715481689470015706033552806 62151567471574769467391 a and b were 231 106 Traceback (most recent call last): File "C:/P31Working/prime_to_biggest_prime_tutor3.py", line 45, in sys.exit() SystemExit How can I prevent Traceback (most recent call last): File "C:/P31Working/prime_to_biggest_prime_tutor3.py", line 45, in sys.exit() SystemExit from printing? Or isn't using sys.exit() a good idea? Dick From eike.welk at gmx.net Thu Jun 24 11:33:57 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 24 Jun 2010 11:33:57 +0200 Subject: [Tutor] Use flag to exit? In-Reply-To: References: <201006240847.20945.eike.welk@gmx.net> Message-ID: <201006241133.57858.eike.welk@gmx.net> On Thursday June 24 2010 09:16:05 Richard D. Moores wrote: > I did what you said (), and get > "invalid syntax" for the comma in line 40. Are you using Python 3? (I'm using Python 2.6) For Python 3 the correct syntax of the except clause is: except FoundPrimeException as e: See: http://docs.python.org/py3k/tutorial/errors.html#handling-exceptions > The prime greater than or equal to 100 is 101 > Traceback (most recent call last): > File "C:/P31Working/prime_to_biggest_prime_tutor2_Eike2.py", line > 40, in > except (FoundPrimeException, e): > NameError: name 'FoundPrimeException' is not defined You have to define the class FoundPrimeException. The definition is in the first part of my email. I think a good place for it is before the function definitions. Eike. From rdmoores at gmail.com Thu Jun 24 12:15:25 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 03:15:25 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: <201006241133.57858.eike.welk@gmx.net> References: <201006240847.20945.eike.welk@gmx.net> <201006241133.57858.eike.welk@gmx.net> Message-ID: On Thu, Jun 24, 2010 at 02:33, Eike Welk wrote: > On Thursday June 24 2010 09:16:05 Richard D. Moores wrote: > >> I did what you said (), and get >> "invalid syntax" for the comma in line 40. > > Are you using Python 3? (I'm using Python 2.6) For Python 3 the correct syntax > of the except clause is: > > except FoundPrimeException as e: > > See: > http://docs.python.org/py3k/tutorial/errors.html#handling-exceptions > >> The prime greater than or equal to 100 is 101 >> Traceback (most recent call last): >> ? File "C:/P31Working/prime_to_biggest_prime_tutor2_Eike2.py", line >> 40, in >> ? ? except (FoundPrimeException, e): >> NameError: name 'FoundPrimeException' is not defined > > You have to define the class FoundPrimeException. The definition is in the > first part of my email. I think a good place for it is before the function > definitions. OK. See . What now? Dick From eike.welk at gmx.net Thu Jun 24 12:36:52 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 24 Jun 2010 12:36:52 +0200 Subject: [Tutor] Use flag to exit? In-Reply-To: References: <201006241133.57858.eike.welk@gmx.net> Message-ID: <201006241236.52698.eike.welk@gmx.net> On Thursday June 24 2010 12:15:25 Richard D. Moores wrote: > OK. See . What now? Ah... my bad. Line 8 must be changed to: self.big_p = big_p Eike. From rdmoores at gmail.com Thu Jun 24 12:51:26 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 03:51:26 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: <201006241236.52698.eike.welk@gmx.net> References: <201006241133.57858.eike.welk@gmx.net> <201006241236.52698.eike.welk@gmx.net> Message-ID: On Thu, Jun 24, 2010 at 03:36, Eike Welk wrote: > On Thursday June 24 2010 12:15:25 Richard D. Moores wrote: >> OK. See . What now? > > Ah... my bad. Line 8 must be changed to: > ? ? ? ?self.big_p = big_p Yes! Perfect! Now, Eike, if I only understand what you wrote. You kindly included an appropriate link to the docs, but... How about using sys.exit() instead? Dick From steve at pearwood.info Thu Jun 24 13:54:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Jun 2010 21:54:23 +1000 Subject: [Tutor] Use flag to exit? In-Reply-To: References: <201006241236.52698.eike.welk@gmx.net> Message-ID: <201006242154.23458.steve@pearwood.info> On Thu, 24 Jun 2010 08:51:26 pm Richard D. Moores wrote: > How about using sys.exit() instead? sys.exit() is almost always evil. Here's the problem: One day, you find a nice library that has some function you need. Perhaps it's even a library you wrote yourself: from library import print_next_prime print_next_prime(5) => prints 7 And it works fine. So you decide to extend your program: from library import print_next_prime print_next_prime(5) print_next_prime(13) => prints 7 And mysteriously it stops working. The second function call never happens, only the first. What's going on? Eventually you work out that the print_next_prime function needlessly calls sys.exit. This being Python, you can fix it: from library import print_next_prime def print_next_prime2(n): try: print_next_prime(n) except SystemExit: pass print_next_prime2(5) print_next_prime2(13) so it's not the end of the world, but you shouldn't have to work around the poor design of the function in the first place. sys.exit is almost never needed. I'm yet to find a program that includes it where the program wouldn't be simpler to use, more flexible, more friendly, and generally more useful, without it. One (rare) exception is, when it is part of the user interface, not the backend. For instance, in a GUI application, you might link the Quit menu command to sys.exit. In Python, you rarely need to explicitly exit because your code will exit when it reaches the end of the file, or on an un-caught exception. -- Steven D'Aprano From eike.welk at gmx.net Thu Jun 24 13:55:38 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 24 Jun 2010 13:55:38 +0200 Subject: [Tutor] Use flag to exit? In-Reply-To: References: <201006241236.52698.eike.welk@gmx.net> Message-ID: <201006241355.39054.eike.welk@gmx.net> On Thursday June 24 2010 12:51:26 Richard D. Moores wrote: > On Thu, Jun 24, 2010 at 03:36, Eike Welk wrote: > > On Thursday June 24 2010 12:15:25 Richard D. Moores wrote: > >> OK. See . What now? > > > > Ah... my bad. Line 8 must be changed to: > > self.big_p = big_p > > Yes! Perfect! Now, Eike, if I only understand what you wrote. You > kindly included an appropriate link to the docs, but... > > How about using sys.exit() instead? From looking at the documentation I think that sys.exit(0) should exit cleanly. Looking at my solution now, I think it is too complicated for your relatively simple use-case. I think a better solution would be to put the nested for loops into a function and use return to exit the computation. I wrote a new untested version here: http://tutoree7.pastebin.com/RL3b2bx6 Eike. From rdmoores at gmail.com Thu Jun 24 14:27:59 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 05:27:59 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: <201006241355.39054.eike.welk@gmx.net> References: <201006241236.52698.eike.welk@gmx.net> <201006241355.39054.eike.welk@gmx.net> Message-ID: On Thu, Jun 24, 2010 at 04:55, Eike Welk wrote: > On Thursday June 24 2010 12:51:26 Richard D. Moores wrote: >> On Thu, Jun 24, 2010 at 03:36, Eike Welk wrote: >> > On Thursday June 24 2010 12:15:25 Richard D. Moores wrote: >> Yes! Perfect! Now, Eike, if I only understand what you wrote. You >> kindly included an appropriate link to the docs, but... >> >> How about using sys.exit() instead? > >From looking at the documentation I think that sys.exit(0) should exit > cleanly. > > > Looking at my solution now, I think it is too complicated for your relatively > simple use-case. I think a better solution would be to put the nested for > loops into a function and use return to exit the computation. > > I wrote a new untested version here: > http://tutoree7.pastebin.com/RL3b2bx6 Of course! Now, without looking at your code, I'll try to do it myself, and then look. Thanks very much, Eike. Dick From hugo.yoshi at gmail.com Thu Jun 24 14:59:09 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 24 Jun 2010 14:59:09 +0200 Subject: [Tutor] Time In-Reply-To: <4C215F44.8030104@ieee.org> References: <4C215F44.8030104@ieee.org> Message-ID: On Wed, Jun 23, 2010 at 3:11 AM, Dave Angel wrote: > > If you're really looking to measure performance, you should use the timeit > module. ?But for simply deciding how much time has elapsed between two > points in your code, you can use the time.time() function. > Another one I think is worth mentioning is the cProfile module. Though timeit or time.time are more useful when you simply want to know how long some task took, when you're optimizing your code and wondering what's taking a lot of time, cProfile will tell you. Hugo From hugo.yoshi at gmail.com Thu Jun 24 15:06:24 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 24 Jun 2010 15:06:24 +0200 Subject: [Tutor] finally In-Reply-To: References: Message-ID: On Thu, Jun 24, 2010 at 4:36 AM, Christopher King wrote: > ?? ?In a try except clause, you can end with finally block. I know it runs > after the try and except blocks regardless of the outcome, but why use it. > Couldn't you just put the code after the try and except block without using > a finally block. Does the finally command do something I don't know about. > Does it make your program more understandable in some way? The thing about the finally block is that it *always* runs. If you just put some code after the try: except: clause, it won't run if a) the exception is not handled in the try: except: block, but higher up in the call stack b) the exception is not handled at all c) the exception handler terminates the program d) the exception handler raises another exception If you need to do some cleanup, putting it in a finally block is the only way to *guarantee* it will run. Hugo From g.nius.ck at gmail.com Thu Jun 24 15:12:57 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 09:12:57 -0400 Subject: [Tutor] finally In-Reply-To: References: Message-ID: you mean it will always run even if the exception is handled? On Thu, Jun 24, 2010 at 9:06 AM, Hugo Arts wrote: > On Thu, Jun 24, 2010 at 4:36 AM, Christopher King > wrote: > > In a try except clause, you can end with finally block. I know it > runs > > after the try and except blocks regardless of the outcome, but why use > it. > > Couldn't you just put the code after the try and except block without > using > > a finally block. Does the finally command do something I don't know > about. > > Does it make your program more understandable in some way? > > The thing about the finally block is that it *always* runs. If you > just put some code after the try: except: clause, it won't run if > > a) the exception is not handled in the try: except: block, but higher > up in the call stack > b) the exception is not handled at all > c) the exception handler terminates the program > d) the exception handler raises another exception > > If you need to do some cleanup, putting it in a finally block is the > only way to *guarantee* it will run. > > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 15:13:20 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 09:13:20 -0400 Subject: [Tutor] finally In-Reply-To: References: Message-ID: i mean isn't handled On Thu, Jun 24, 2010 at 9:12 AM, Christopher King wrote: > you mean it will always run even if the exception is handled? > > > On Thu, Jun 24, 2010 at 9:06 AM, Hugo Arts wrote: > >> On Thu, Jun 24, 2010 at 4:36 AM, Christopher King >> wrote: >> > In a try except clause, you can end with finally block. I know it >> runs >> > after the try and except blocks regardless of the outcome, but why use >> it. >> > Couldn't you just put the code after the try and except block without >> using >> > a finally block. Does the finally command do something I don't know >> about. >> > Does it make your program more understandable in some way? >> >> The thing about the finally block is that it *always* runs. If you >> just put some code after the try: except: clause, it won't run if >> >> a) the exception is not handled in the try: except: block, but higher >> up in the call stack >> b) the exception is not handled at all >> c) the exception handler terminates the program >> d) the exception handler raises another exception >> >> If you need to do some cleanup, putting it in a finally block is the >> only way to *guarantee* it will run. >> >> Hugo >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 15:15:14 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 09:15:14 -0400 Subject: [Tutor] finally In-Reply-To: <4C22C9F4.3080907@gmail.com> References: <4C22C9F4.3080907@gmail.com> Message-ID: what manual? On Wed, Jun 23, 2010 at 10:59 PM, bob gailer wrote: > On 6/23/2010 7:36 PM, Christopher King wrote: > > In a try except clause, you can end with finally block. I know it runs > after the try and except blocks regardless of the outcome, but why use it. > Couldn't you just put the code after the try and except block without using > a finally block. Does the finally command do something I don't know about. > Does it make your program more understandable in some way? > > > Did you read the manual? > > "If finally <#12967e4e8be99cad_finally> is present, it specifies a > ?cleanup? handler. The try <#12967e4e8be99cad_try> clause is executed, > including any except <#12967e4e8be99cad_except> and else<#12967e4e8be99cad_else>clauses. If an exception occurs in any of the clauses and is not handled, > the exception is temporarily saved. The finally<#12967e4e8be99cad_finally>clause is executed. If there is a saved exception, it is re-raised at the > end of the finally <#12967e4e8be99cad_finally> clause. If the finally<#12967e4e8be99cad_finally>clause raises another exception or executes a > return or breakstatement, the saved exception is lost. The exception information is not > available to the program during execution of the finally<#12967e4e8be99cad_finally>clause. > > "When a return , breakor > continue statement is executed in the > try <#12967e4e8be99cad_try> suite of a try <#12967e4e8be99cad_try>... > finally <#12967e4e8be99cad_finally> statement, the finally<#12967e4e8be99cad_finally>clause is also executed ?on the way out.? A > continue statement is illegal in the > finally <#12967e4e8be99cad_finally> clause. (The reason is a problem with > the current implementation ? this restriction may be lifted in the future)." > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 15:38:31 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 09:38:31 -0400 Subject: [Tutor] Time In-Reply-To: References: <4C215F44.8030104@ieee.org> Message-ID: I have a module which measures elapsed time. It can also wait til a certain amount of time has passed till ending. I can send it to you if you like. On Thu, Jun 24, 2010 at 8:59 AM, Hugo Arts wrote: > On Wed, Jun 23, 2010 at 3:11 AM, Dave Angel wrote: > > > > If you're really looking to measure performance, you should use the > timeit > > module. But for simply deciding how much time has elapsed between two > > points in your code, you can use the time.time() function. > > > > Another one I think is worth mentioning is the cProfile module. Though > timeit or time.time are more useful when you simply want to know how > long some task took, when you're optimizing your code and wondering > what's taking a lot of time, cProfile will tell you. > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Jun 24 15:38:56 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 24 Jun 2010 15:38:56 +0200 Subject: [Tutor] finally In-Reply-To: References: Message-ID: On Thu, Jun 24, 2010 at 3:13 PM, Christopher King wrote: > i mean isn't handled > When I said "guaranteed to run," I meant it. finally will *always* run after your try clause, exceptions or not, handled or not. And by manual, he means the python reference manual. He was quoting a part covering the try statement: http://docs.python.org/reference/compound_stmts.html#the-try-statement Hugo From rdmoores at gmail.com Thu Jun 24 16:00:56 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 07:00:56 -0700 Subject: [Tutor] Line wrapping in IDLE possible? Horizontal scroll bar? Message-ID: I use IDLE v3.1.1 occasionally on Vista. There doesn't seem to be a way to configure it to wrap long lines (they do wrap in the IDLE shell). Or is there? Also, when there's an unwrapped long line that extends past the right edge of the window frame, the only way to see the line's tail is to place the caret on the line and use the right arrow key. Is there a way to get a horizontal scroll bar to appear? Thanks, Dick Moores From g.nius.ck at gmail.com Thu Jun 24 16:08:34 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 10:08:34 -0400 Subject: [Tutor] finally In-Reply-To: References: Message-ID: so if you encounter an error that you won't handle, but you still to close files and save data, you could use finally? On Thu, Jun 24, 2010 at 10:05 AM, Christopher King wrote: > let me try it > > On Thu, Jun 24, 2010 at 9:38 AM, Hugo Arts wrote: > >> On Thu, Jun 24, 2010 at 3:13 PM, Christopher King >> wrote: >> > i mean isn't handled >> > >> >> When I said "guaranteed to run," I meant it. finally will *always* run >> after your try clause, exceptions or not, handled or not. >> And by manual, he means the python reference manual. He was quoting a >> part covering the try statement: >> >> http://docs.python.org/reference/compound_stmts.html#the-try-statement >> >> Hugo >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Jun 24 16:14:54 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 07:14:54 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: References: <201006241236.52698.eike.welk@gmx.net> <201006241355.39054.eike.welk@gmx.net> Message-ID: On Thu, Jun 24, 2010 at 05:27, Richard D. Moores wrote: > On Thu, Jun 24, 2010 at 04:55, Eike Welk wrote: >> Looking at my solution now, I think it is too complicated for your relatively >> simple use-case. I think a better solution would be to put the nested for >> loops into a function and use return to exit the computation. >> >> I wrote a new untested version here: >> http://tutoree7.pastebin.com/RL3b2bx6 > > Of course! Now, without looking at your code, I'll try to do it > myself, and then look. > > Thanks very much, Eike. > > Dick Mine is ; yours is . Almost identical! Thanks again, Eike. Dick From g.nius.ck at gmail.com Thu Jun 24 16:18:29 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 24 Jun 2010 10:18:29 -0400 Subject: [Tutor] Line wrapping in IDLE possible? Horizontal scroll bar? In-Reply-To: References: Message-ID: well, if you use a backlash in the middle of a statement, you can continue the statement on the next line like so. >>> for \ i \ in \ ('neat', 'ha') \ : \ print \ i neat ha >>> you can abuse it as much as you like [?] On Thu, Jun 24, 2010 at 10:00 AM, Richard D. Moores wrote: > I use IDLE v3.1.1 occasionally on Vista. There doesn't seem to be a > way to configure it to wrap long lines (they do wrap in the IDLE > shell). Or is there? > > Also, when there's an unwrapped long line that extends past the right > edge of the window frame, the only way to see the line's tail is to > place the caret on the line and use the right arrow key. Is there a > way to get a horizontal scroll bar to appear? > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 1B2.gif Type: image/gif Size: 120 bytes Desc: not available URL: From rdmoores at gmail.com Thu Jun 24 16:24:42 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 07:24:42 -0700 Subject: [Tutor] Line wrapping in IDLE possible? Horizontal scroll bar? In-Reply-To: References: Message-ID: Yes, that's true, but if the line is long because of a long int? On Thu, Jun 24, 2010 at 07:18, Christopher King wrote: > > well, if you use a backlash in the middle of a statement, you can continue the statement on the next line like so. > >>> for \ > ?? ?i \ > ?? ?in \ > ?? ?('neat', 'ha') \ > ?? ?: \ > ?? ?print \ > ?? ?i > neat > ha > >>> > you can abuse it as much as you like > On Thu, Jun 24, 2010 at 10:00 AM, Richard D. Moores wrote: >> >> I use IDLE v3.1.1 occasionally on Vista. There doesn't seem to be a >> way to configure it to wrap long lines (they do wrap in the IDLE >> shell). Or is there? >> >> Also, when there's an unwrapped long line that extends past the right >> edge of the window frame, the only way to see the line's tail is to >> place the caret on the line and use the right arrow key. Is there a >> way to get a horizontal scroll bar to appear? >> >> Thanks, >> >> Dick Moores >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > From wprins at gmail.com Thu Jun 24 16:29:12 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 24 Jun 2010 15:29:12 +0100 Subject: [Tutor] finally In-Reply-To: References: Message-ID: On 24 June 2010 15:08, Christopher King wrote: > so if you encounter an error that you won't handle, but you still to close > files and save data, you could use finally? > More strongly, you *should* use finally, as there's no other way to ensure your cleanup code will run regardless of unpredictable exceptions that may be thrown... Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 16:31:50 2010 From: g.nius.ck at gmail.com (Chris) Date: Thu, 24 Jun 2010 10:31:50 -0400 Subject: [Tutor] Line wrapping in IDLE possible? Horizontal scroll bar? In-Reply-To: References: Message-ID: <4C236C56.4030909@gmail.com> On 06/24/2010 10:24 AM, Richard D. Moores wrote: > Yes, that's true, but if the line is long because of a long int? > > On Thu, Jun 24, 2010 at 07:18, Christopher King wrote: > >> well, if you use a backlash in the middle of a statement, you can continue the statement on the next line like so. >> >>>>> for \ >>>>> >> i \ >> in \ >> ('neat', 'ha') \ >> : \ >> print \ >> i >> neat >> ha >> >>>>> >> you can abuse it as much as you like >> On Thu, Jun 24, 2010 at 10:00 AM, Richard D. Moores wrote: >> >>> I use IDLE v3.1.1 occasionally on Vista. There doesn't seem to be a >>> way to configure it to wrap long lines (they do wrap in the IDLE >>> shell). Or is there? >>> >>> Also, when there's an unwrapped long line that extends past the right >>> edge of the window frame, the only way to see the line's tail is to >>> place the caret on the line and use the right arrow key. Is there a >>> way to get a horizontal scroll bar to appear? >>> >>> Thanks, >>> >>> Dick Moores >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> just give the number its on line like so >>> function('neat', 7085910407358720820797840784720872097287409278407528907047908524087589046980786984380642784907290766890474876480786748728906789042089672687043287422308748902707842048 \ + 4, 'ha') neat 7085910407358720820797840784720872097287409278407528907047908524087589046980786984380642784907290766890474876480786748728906789042089672687043287422308748902707842052 ha >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 16:34:19 2010 From: g.nius.ck at gmail.com (Chris) Date: Thu, 24 Jun 2010 10:34:19 -0400 Subject: [Tutor] finally In-Reply-To: References: Message-ID: <4C236CEB.4030002@gmail.com> On 06/24/2010 10:29 AM, Walter Prins wrote: > On 24 June 2010 15:08, Christopher King @gmail.com > wrote: > > so if you encounter an error that you won't handle, but you still > to close files and save data, you could use finally? > > > More strongly, you *should* use finally, as there's no other way to > ensure your cleanup code will run regardless of unpredictable > exceptions that may be thrown... > > Walter cleanup code means code to close files and save data, right -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Jun 24 16:44:06 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 24 Jun 2010 15:44:06 +0100 Subject: [Tutor] finally In-Reply-To: <4C236CEB.4030002@gmail.com> References: <4C236CEB.4030002@gmail.com> Message-ID: On 24 June 2010 15:34, Chris wrote: > cleanup code means code to close files and save data, right > Possibly yes, although I'm referring generally to freeing any resources (objects, memory, files, whatever) your code has acquired/opened that should be freed whether or not the code succeeds (without throwing an exception) or fails somehow (having thrown an exception.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 16:44:05 2010 From: g.nius.ck at gmail.com (Chris) Date: Thu, 24 Jun 2010 10:44:05 -0400 Subject: [Tutor] finally In-Reply-To: <4C22C9F4.3080907@gmail.com> References: <4C22C9F4.3080907@gmail.com> Message-ID: <4C236F35.30305@gmail.com> On 06/23/2010 10:59 PM, bob gailer wrote: > On 6/23/2010 7:36 PM, Christopher King wrote: >> In a try except clause, you can end with finally block. I know it >> runs after the try and except blocks regardless of the outcome, but >> why use it. Couldn't you just put the code after the try and except >> block without using a finally block. Does the finally command do >> something I don't know about. Does it make your program more >> understandable in some way? > > Did you read the manual? > > "If finally <#finally> is present, it specifies a 'cleanup' handler. > The try <#try> clause is executed, including any except <#except> and > else <#else> clauses. If an exception occurs in any of the clauses and > is not handled, the exception is temporarily saved. The finally > <#finally> clause is executed. If there is a saved exception, it is > re-raised at the end of the finally <#finally> clause. If the finally > <#finally> clause raises another exception or executes a return > or break > statement, the saved exception is lost. The exception information is > not available to the program during execution of the finally > <#finally> clause. > > "When a return , break > or continue > statement is executed in the try <#try> suite of a try > <#try>...finally <#finally> statement, the finally <#finally> clause > is also executed 'on the way out.' A continue > statement is illegal in the finally > <#finally> clause. (The reason is a problem with the current > implementation --- this restriction may be lifted in the future)." > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC for the second quote, it means that the try...finally statement, finally will always execute even if you use return, break, or continue -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jun 24 16:44:43 2010 From: g.nius.ck at gmail.com (Chris) Date: Thu, 24 Jun 2010 10:44:43 -0400 Subject: [Tutor] finally In-Reply-To: References: <4C236CEB.4030002@gmail.com> Message-ID: <4C236F5B.4020208@gmail.com> On 06/24/2010 10:44 AM, Walter Prins wrote: > On 24 June 2010 15:34, Chris @gmail.com > > wrote: > > cleanup code means code to close files and save data, right > > > Possibly yes, although I'm referring generally to freeing any > resources (objects, memory, files, whatever) your code has > acquired/opened that should be freed whether or not the code succeeds > (without throwing an exception) or fails somehow (having thrown an > exception.) > > Walter > ok -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 24 18:21:40 2010 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Jun 2010 09:21:40 -0700 Subject: [Tutor] unsubscribe In-Reply-To: References: Message-ID: <4C238614.2060101@gmail.com> On 6/23/2010 8:35 AM, Benjamin Pritchard wrote: > unsubscribe > You have to do that yourself. The instructions are always included in posts sent from the list: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Thu Jun 24 19:13:04 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jun 2010 18:13:04 +0100 Subject: [Tutor] Use flag to exit? References: Message-ID: "Richard D. Moores" wrote > How can I prevent > > Traceback (most recent call last): > File "C:/P31Working/prime_to_biggest_prime_tutor3.py", line 45, in > > sys.exit() > SystemExit > > from printing? Or isn't using sys.exit() a good idea? Steven has already given you an answer to that although I'd add that I have no problems using sys.exit() in top level code. Just don't use it inside a function. Either raise an exception or return a value. If you are using it at the top level you may be running your code inside an IDE like IDLE or Pythonwin which always catches sys.exit(). That's OK, it's intended to print that message rather than exit so that you can debug the code if necessary, but it won't do it if you run the code from the OS prompt it will just exit silently as expected. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jf_byrnes at comcast.net Thu Jun 24 19:36:16 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 24 Jun 2010 12:36:16 -0500 Subject: [Tutor] os.startfile? Message-ID: <4C239790.1000604@comcast.net> I am trying to run an example program that contains the line os.startfile('socket-nongui.py') which is Windows only. What would be the command to use on Linux? All files are in the same folder. Thanks, Jim From nethirlon at gmail.com Thu Jun 24 19:59:09 2010 From: nethirlon at gmail.com (Nethirlon) Date: Thu, 24 Jun 2010 19:59:09 +0200 Subject: [Tutor] os.startfile? In-Reply-To: <4C239790.1000604@comcast.net> References: <4C239790.1000604@comcast.net> Message-ID: On Thu, Jun 24, 2010 at 7:36 PM, Jim Byrnes wrote: > I am trying to run an example program that contains the line > os.startfile('socket-nongui.py') which is Windows only. ?What would be the > command to use on Linux? ?All files are in the same folder. > > Thanks, ?Jim > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi Jim, Is this perhaps what you are looking for? import os os.system('ls -lt > output.txt') Kind regards, Nethirlon From lie.1296 at gmail.com Thu Jun 24 20:51:13 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 25 Jun 2010 04:51:13 +1000 Subject: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives? In-Reply-To: <1277309445.2173.1381531403@webmail.messagingengine.com> References: <1277309445.2173.1381531403@webmail.messagingengine.com> Message-ID: On 06/24/10 02:10, python at bdurham.com wrote: > Can someone confirm that Python 2.6 ftplib does *NOT* support > Unicode file names? Or must Unicode file names be specially > encoded in order to be used with the ftplib module? > I don't know the specifics about ftplib, however I believe in most file systems, file names are plain byte-strings, i.e. most file systems do not handle encoding, they only deal with plain bytes. From jf_byrnes at comcast.net Thu Jun 24 21:14:57 2010 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 24 Jun 2010 14:14:57 -0500 Subject: [Tutor] os.startfile? In-Reply-To: References: <4C239790.1000604@comcast.net> Message-ID: <4C23AEB1.5090601@comcast.net> Nethirlon wrote: > On Thu, Jun 24, 2010 at 7:36 PM, Jim Byrnes wrote: >> I am trying to run an example program that contains the line >> os.startfile('socket-nongui.py') which is Windows only. What would be the >> command to use on Linux? All files are in the same folder. >> >> Thanks, Jim >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Hi Jim, > > Is this perhaps what you are looking for? > > import os > os.system('ls -lt> output.txt') > > Kind regards, > Nethirlon > I don't think so but it is my fault. When I asked the question I thought I gave enough info but I see now that I didn't. The os.startfile('socket-nongui.py) line was in a gui program that demonstrates how to start and communicate with a non-gui program. It is Windows specific so I looked for but could not find a drop in replacement that works on Linux. Thanks, Jim From rdmoores at gmail.com Thu Jun 24 23:49:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 14:49:03 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: References: Message-ID: On Thu, Jun 24, 2010 at 10:13, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> How can I prevent >> >> Traceback (most recent call last): >> ?File "C:/P31Working/prime_to_biggest_prime_tutor3.py", line 45, in >> >> ? sys.exit() >> SystemExit >> >> from printing? Or isn't using sys.exit() a good idea? > > Steven has already given you an answer to that although > I'd add that I have no problems using sys.exit() in top level code. > Just don't use it inside a function. Either raise an exception > or return a value. > > If you are using it at the top level you may be running your code > inside an IDE like IDLE or Pythonwin which always catches > sys.exit(). That's OK, it's intended to print that message rather > than exit so that you can debug the code if necessary, but it > won't do it if you run the code from the OS prompt it will just > exit silently as expected. Thanks, Alan. And thanks also to Steven. I think I much prefer accomplishing an exit by a function return, as I do in , but if I wanted to use sys.exit() in a script (but not in a function) I run inside IDLE or Wing, how do I suppress the message? I'd just like to get that nailed down. Dick From alan.gauld at btinternet.com Fri Jun 25 02:06:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Jun 2010 01:06:08 +0100 Subject: [Tutor] Use flag to exit? References: Message-ID: "Richard D. Moores" wrote > I think I much prefer accomplishing an exit by a function return, as > I > do in , but if I wanted to > use > sys.exit() in a script (but not in a function) I run inside IDLE or > Wing, how do I suppress the message? I'd just like to get that > nailed > down. You can catch it like any other exception but that's not really the point. IDLE is not intended to run programs it's for developing them. It is set up to catch keyboard interrupts and sys exits deliberately because that's what you want in a development tool. Just run the programs outside IDLE and they won't get caught and you won't get error messages. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 25 02:08:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Jun 2010 01:08:56 +0100 Subject: [Tutor] os.startfile? References: <4C239790.1000604@comcast.net> <4C23AEB1.5090601@comcast.net> Message-ID: "Jim Byrnes" wrote > The os.startfile('socket-nongui.py) line was in a gui program that > demonstrates how to start and communicate with a non-gui program. > It is Windows specific so I looked for but could not find a drop in > replacement that works on Linux. Look at the subprocess module. That is the platform independant way to run external programs and communicate with them. There are lots of examples in the documentation and you can find some basic info in the OS topic of my tutorial (Python v2 only so far for that one) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Jun 25 02:41:07 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Jun 2010 10:41:07 +1000 Subject: [Tutor] finally In-Reply-To: References: Message-ID: <201006251041.07907.steve@pearwood.info> On Thu, 24 Jun 2010 11:06:24 pm Hugo Arts wrote: > If you need to do some cleanup, putting it in a finally block is the > only way to *guarantee* it will run. To be pedantic, the finally clause will always run, *provided* the code in the try block itself exits (either by finishing or by raising an exception). If the try block never exits, the finally block never runs. # Don't try this at home. try: sys.setcheckinterval(sys.maxint) print "Can't stop this!" while 1: pass finally: print "This never prints" The only way to exit the loop is to hit it with a hammer (kill it from outside Python), in which case the finally block never gets to run. -- Steven D'Aprano From steve at pearwood.info Fri Jun 25 02:42:35 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Jun 2010 10:42:35 +1000 Subject: [Tutor] finally In-Reply-To: References: Message-ID: <201006251042.35434.steve@pearwood.info> On Fri, 25 Jun 2010 12:29:12 am Walter Prins wrote: > On 24 June 2010 15:08, Christopher King wrote: > > so if you encounter an error that you won't handle, but you still > > to close files and save data, you could use finally? > > More strongly, you *should* use finally, as there's no other way to > ensure your cleanup code will run regardless of unpredictable > exceptions that may be thrown... Actually, no, having learned `finally`, you should not use it and use `with` instead! (For some definition of "should".) Starting from Python 2.5, Python provides a new, more flexible and powerful mechanism for running cleanup code: the `with` statement. In Python 2.5 you need to import it first: from __future__ import with_statement In Python 2.6 and higher you don't need the import. Then you write something like this: with open('myfile', 'w') as f: data = some_function() f.write(data) and f will be automatically closed at the end of the with block even if some_function raises an exception. Of course, writing your own cleanup code using try...finally will continue to be supported, and it's *not* wrong to use it (especially if you have to support versions of Python prior to 2.5) but the with statement is the preferred way to do it now. See more information about it here: http://effbot.org/zone/python-with-statement.htm -- Steven D'Aprano From steve at pearwood.info Fri Jun 25 02:59:18 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Jun 2010 10:59:18 +1000 Subject: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives? In-Reply-To: References: <1277309445.2173.1381531403@webmail.messagingengine.com> Message-ID: <201006251059.18550.steve@pearwood.info> On Fri, 25 Jun 2010 04:51:13 am Lie Ryan wrote: > On 06/24/10 02:10, python at bdurham.com wrote: > > Can someone confirm that Python 2.6 ftplib does *NOT* support > > Unicode file names? Or must Unicode file names be specially > > encoded in order to be used with the ftplib module? > > I don't know the specifics about ftplib, however I believe in most > file systems, file names are plain byte-strings, i.e. most file > systems do not handle encoding, they only deal with plain bytes. That is completely backwards. Most modern file systems use Unicode, not bytes. Windows file systems use Unicode file names: http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx Likewise the Macintosh HFS+ file system also uses Unicode file names: http://developer.apple.com/mac/library/technotes/tn/tn1150.html So do UDF, ZDF and many others: http://en.wikipedia.org/wiki/Comparison_of_file_systems These days, if you're a developer on a non-Linux PC who doesn't need to worry about legacy file systems, most file systems you come across will be Unicode and not bytes. It's mostly Linux developers who have to deal with byte file names. -- Steven D'Aprano From rdmoores at gmail.com Fri Jun 25 03:35:40 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 24 Jun 2010 18:35:40 -0700 Subject: [Tutor] Use flag to exit? In-Reply-To: References: Message-ID: On Thu, Jun 24, 2010 at 17:06, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> I think I much prefer accomplishing an exit by a function return, as I >> do in , but if I wanted to use >> sys.exit() in a script (but not in a function) I run inside IDLE or >> Wing, how do I suppress the message? I'd just like to get that nailed >> down. > > You can catch it like any other exception but that's not really the point. > IDLE is not intended to run programs it's for developing them. It is set > up to catch keyboard interrupts and sys exits deliberately because > that's what you want in a development tool. Just run the programs > outside IDLE and they won't get caught and you won't get error > messages. But I usually prefer to run the programs I write in an IDE's shell, unless they are GUI's, of course. What are my options for running my scripts outside of an IDE? The Windows' command line is pretty ugly and inconvenient. Copy and pasting is a PITA. And all that changing of directories. I did enjoy using IPython, however. Dick From sander.sweers at gmail.com Fri Jun 25 07:37:25 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 25 Jun 2010 07:37:25 +0200 Subject: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives? In-Reply-To: <201006251059.18550.steve@pearwood.info> References: <1277309445.2173.1381531403@webmail.messagingengine.com> <201006251059.18550.steve@pearwood.info> Message-ID: <1277444246.2960.2.camel@Nokia-N900> ----- Original message ----- > On Fri, 25 Jun 2010 04:51:13 am Lie Ryan wrote: > > On 06/24/10 02:10, python at bdurham.com wrote: > > > Can someone confirm that Python 2.6 ftplib does *NOT* support > > > Unicode file names? Or must Unicode file names be specially > > > encoded in order to be used with the ftplib module? > > > > I don't know the specifics about ftplib, however I believe in most > > file systems, file names are plain byte-strings, i.e. most file > > systems do not handle encoding, they only deal with plain bytes. > > That is completely backwards. Most modern file systems use Unicode, not > bytes. -snip- > These days, if you're a developer on a non-Linux PC who doesn't need to > worry about legacy file systems, most file systems you come across will > be Unicode and not bytes. It's mostly Linux developers who have to deal > with byte file names. Linux filesystems do not store encoding information as part of the filesystem. It does not care if you give it an unicode filename or byte filename to write to disk. It is up to the userland applications to properly make sense of the filename. Greets Sander From alan.gauld at btinternet.com Fri Jun 25 10:33:44 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 25 Jun 2010 08:33:44 +0000 (GMT) Subject: [Tutor] Use flag to exit? In-Reply-To: References: Message-ID: <783485.66107.qm@web86704.mail.ird.yahoo.com> > But I usually prefer to run the programs I write > in an IDE's shell, unless they are GUI's, of course. Why? That seems like a real pain to me! > What are my options for running my > scripts outside of an IDE? Double click them in Windows explorer. Put a shortcut on your desktop. All the usual options for running any kind of application. > The Windows' command line is pretty ugly > and inconvenient. Its not pretty I grant you although you can change the colours and fonts. But its pretty convenient! It just pops up when required and goes away again when the program exits. Whats the issue? > Copy and pasting is a PITA. Why would you want to copy and paste? > all that changing of directories. Why would you need to change directory? Provided your code doesn't rely on being in a particular directory and can get the user to specify the target directory if necessary you can run it from anywhere. Or set up a shortcut that specifies the active directory. I don't understand why you think running outside an IDE would be a problem? Alan G. From emile at fenx.com Fri Jun 25 17:23:53 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 25 Jun 2010 08:23:53 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: <783485.66107.qm@web86704.mail.ird.yahoo.com> References: <783485.66107.qm@web86704.mail.ird.yahoo.com> Message-ID: On 6/25/2010 1:33 AM ALAN GAULD said... >> Copy and pasting is a PITA. > > Why would you want to copy and paste? Because it makes it easy to work on code. My preferred editor (TextPad) allows block selection of indented text such that I can copy and paste functions and methods into the python CLI and work with them there. I find it very easy when developing to keep the CLI open for this purpose and interactively test as I write. Unfortunately, PEP 8 doesn't support this use case as once the blank lines separating methods are pasted in, your class definition is complete. So I either put hash marks in or leave the blank lines out... Emile From steve at alchemy.com Fri Jun 25 18:08:16 2010 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 25 Jun 2010 09:08:16 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> Message-ID: <4C24D470.2010207@alchemy.com> On 25-Jun-10 08:23, Emile van Sebille wrote: > On 6/25/2010 1:33 AM ALAN GAULD said... >>> Copy and pasting is a PITA. >> >> Why would you want to copy and paste? > > Because it makes it easy to work on code. My preferred editor (TextPad) > allows block selection of indented text such that I can copy and paste > functions and methods into the python CLI and work with them there. I If what you're trying to do is a PITA, that should raise two questions: First, is it because the tools you're using are ill-suited to the task at hand? There may be better tools (a text editor which allows you to select a range and execute it via some shell command, an IDE which allows you to run selected code fragments, whatever). Second, is it because the way you're solving the problem isn't the right approach, which is why the tools, assuming they've been thought through and used by enough people before you, don't support that particular use case? Stepping back and questioning your assumptions and approach is often healthy to do. Maybe structuring your code so that a python interpreter can just "import" your module and call into it easily? Or maybe using a unit testing framework which lets you invoke individual test cases in which you can experiment without cutting and pasting? Or maybe putting experimental code in a "if __name__ == '__main__'" block in your module after defining classes and functions which can be triggered just by clicking on the source file? > find it very easy when developing to keep the CLI open for this purpose > and interactively test as I write. Unfortunately, PEP 8 doesn't support > this use case as once the blank lines separating methods are pasted in, > your class definition is complete. So I either put hash marks in or > leave the blank lines out... yeah, that's admittedly a problem which highlights the different needs of an interactive environment which needs to know when you're finished defining a block without being able to see a static source file, in a language without explicit syntax (such as a closing brace or "end" keyword). Again, it feels like you're having to go to inconvenient measures to strain to use a particular solution (cut and paste) when you might be better served to learn to solve your problem in a different way altogether. But what you're doing is still possible, of course. If your choice of tools is otherwise exactly what you want to stick with, this is simply the price you need to pay for that. If the tradeoff is still worth it for you, then stick with it. --steve From emile at fenx.com Fri Jun 25 18:48:27 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 25 Jun 2010 09:48:27 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: <4C24D470.2010207@alchemy.com> References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> Message-ID: On 6/25/2010 9:08 AM Steve Willoughby said... > On 25-Jun-10 08:23, Emile van Sebille wrote: >> On 6/25/2010 1:33 AM ALAN GAULD said... >>>> Copy and pasting is a PITA. >>> >>> Why would you want to copy and paste? >> >> Because it makes it easy to work on code. My preferred editor (TextPad) >> allows block selection of indented text such that I can copy and paste >> functions and methods into the python CLI and work with them there. I > > If what you're trying to do is a PITA, that should raise two questions: > Points taken, but understand that the OP termed it a PITA, from which Alan asked why cut 'n paste. I don't find it a PITA at all and am quite comfortable with my approach (editor choice being a religious issue after all). My gripe is only that complying with PEP 8 is not possible. Regards, Emile From rdmoores at gmail.com Fri Jun 25 19:02:18 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 25 Jun 2010 10:02:18 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> Message-ID: On Fri, Jun 25, 2010 at 09:48, Emile van Sebille wrote: > On 6/25/2010 9:08 AM Steve Willoughby said... >> >> On 25-Jun-10 08:23, Emile van Sebille wrote: >>> >>> On 6/25/2010 1:33 AM ALAN GAULD said... >>>>> >>>>> Copy and pasting is a PITA. >>>> >>>> Why would you want to copy and paste? >>> >>> Because it makes it easy to work on code. My preferred editor (TextPad) >>> allows block selection of indented text such that I can copy and paste >>> functions and methods into the python CLI and work with them there. I >> >> If what you're trying to do is a PITA, that should raise two questions: >> > > Points taken, but understand that the OP termed it a PITA, from which Alan > asked why cut 'n paste. ?I don't find it a PITA at all and am quite > comfortable with my approach (editor choice being a religious issue after > all). ?My gripe is only that complying with PEP 8 is not possible. I'm the OP. What I called a PITA is copy and pasting using the Windows command line. Dick From randykao at gmail.com Sat Jun 26 00:46:17 2010 From: randykao at gmail.com (Randy Kao) Date: Fri, 25 Jun 2010 15:46:17 -0700 Subject: [Tutor] Running external commands from Python Message-ID: Hi all, I'm a newbie to Python (switching from Perl) and had a question about the best way to run external commands in Python. In doing some reading I'm confused about which is the best way to accomplish this. With Perl, the way I went about running commands was by opening a filehandle and parsing / manipulating the data. i.e. open(XYZ, "ls -la *"); In trying to do this in Python, I think I've read a couple ways to do this. through: os.popen, os.popen2, os.popen3, os.system, commands.getoutput() I might not be understanding when to use which of these correctly and was hoping for some feedback from this more experienced group. Thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Jun 26 01:39:53 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 25 Jun 2010 18:39:53 -0500 Subject: [Tutor] Running external commands from Python In-Reply-To: References: Message-ID: <30E26746-F583-4973-84C7-FF57E5B16C25@gmail.com> Subprocess module is the preferred strategy when You want to communicate with the command you're running. If not, you can use os.system. Sent from my iPhone On Jun 25, 2010, at 5:46 PM, Randy Kao wrote: > Hi all, > > I'm a newbie to Python (switching from Perl) and had a question about the best way to run external commands in Python. > > In doing some reading I'm confused about which is the best way to accomplish this. > > With Perl, the way I went about running commands was by opening a filehandle and parsing / manipulating the data. > > i.e. open(XYZ, "ls -la *"); > > In trying to do this in Python, I think I've read a couple ways to do this. > > through: os.popen, os.popen2, os.popen3, os.system, commands.getoutput() > > I might not be understanding when to use which of these correctly and was hoping for some feedback from this more experienced group. > > Thanks in advance! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sat Jun 26 02:16:16 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Jun 2010 10:16:16 +1000 Subject: [Tutor] Running external commands from Python In-Reply-To: References: Message-ID: <201006261016.17016.steve@pearwood.info> On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote: > Hi all, > > I'm a newbie to Python (switching from Perl) and had a question about > the best way to run external commands in Python. [...] > through: os.popen, os.popen2, os.popen3, os.system, > commands.getoutput() os.system is the oldest way, and it's pretty much obsolete. Only use it for quick-and-dirty scripts when you're too lazy to do the right thing and don't care who knows it. It doesn't capture either stdin or stdout, only the return value. os.popen, popen2 and popen3 are probably closer to what you're used to in Perl. They basically differ in how many file handles they return: popen returns the external command's stdout as a file handle. popen2 returns (stdin, stdout) popen3 returns (stdin, stdout, stderr) The commands module is meant as an easier to use front end to the popen* functions, for times where popen* are too much and system is too little. If all you want is the output (stdout + stderr) of an external command: import commands output = commands.getoutput('ls -l foo*') will do the trick. -- Steven D'Aprano From smokefloat at gmail.com Sat Jun 26 02:48:18 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 25 Jun 2010 20:48:18 -0400 Subject: [Tutor] Running external commands from Python In-Reply-To: <201006261016.17016.steve@pearwood.info> References: <201006261016.17016.steve@pearwood.info> Message-ID: On Fri, Jun 25, 2010 at 8:16 PM, Steven D'Aprano wrote: > On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote: >> Hi all, >> >> I'm a newbie to Python (switching from Perl) and had a question about >> the best way to run external commands in Python. > [...] >> through: os.popen, os.popen2, os.popen3, os.system, >> commands.getoutput() > > > os.system is the oldest way, and it's pretty much obsolete. Not to hijack this thread, but why would accessing, what I(newbie ++1) know as the direct interface from python to the machine you're on, be obsolete? Isn't this the direct way to access your machine through the python 'application', if I'm using this term right? Only use it > for quick-and-dirty scripts when you're too lazy to do the right thing > and don't care who knows it. It doesn't capture either stdin or stdout, > only the return value. > > os.popen, popen2 and popen3 are probably closer to what you're used to > in Perl. They basically differ in how many file handles they return: > > popen returns the external command's stdout as a file handle. > popen2 returns (stdin, stdout) > popen3 returns (stdin, stdout, stderr) > > The commands module is meant as an easier to use front end to the popen* > functions, for times where popen* are too much and system is too > little. If all you want is the output (stdout + stderr) of an external > command: > > import commands > output = commands.getoutput('ls -l foo*') > > will do the trick. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Sat Jun 26 03:34:40 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 25 Jun 2010 20:34:40 -0500 Subject: [Tutor] Running external commands from Python In-Reply-To: References: <201006261016.17016.steve@pearwood.info> Message-ID: On Fri, Jun 25, 2010 at 7:48 PM, David Hutto wrote: > On Fri, Jun 25, 2010 at 8:16 PM, Steven D'Aprano wrote: >> On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote: >>> Hi all, >>> >>> I'm a newbie to Python (switching from Perl) and had a question about >>> the best way to run external commands in Python. >> [...] >>> through: os.popen, os.popen2, os.popen3, os.system, >>> commands.getoutput() >> >> >> os.system is the oldest way, and it's pretty much obsolete. > > > Not to hijack ?this thread, but why would accessing, what I(newbie > ++1) know as the direct interface from python to the machine you're > on, be obsolete? Isn't this the direct way to access your machine > through the python 'application', if I'm using this term right? > He means that in most cases what you want to do is probably capture the stdin & out. it's not obsolete, it's just not that common of a case. I'm not sure why he used that term. Most people tend to use popen because it's more useful. However, os.popen _is_ obsolete, or at least discouraged; the correct module to use is the subprocess module, as I mentioned earlier. From randykao at gmail.com Sat Jun 26 03:37:02 2010 From: randykao at gmail.com (Randy Kao) Date: Fri, 25 Jun 2010 18:37:02 -0700 Subject: [Tutor] Running external commands from Python In-Reply-To: <201006261016.17016.steve@pearwood.info> References: <201006261016.17016.steve@pearwood.info> Message-ID: Thanks for the great and quick feedback from everyone! That definitely clears things up. -Randy On Fri, Jun 25, 2010 at 5:16 PM, Steven D'Aprano wrote: > On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote: > > Hi all, > > > > I'm a newbie to Python (switching from Perl) and had a question about > > the best way to run external commands in Python. > [...] > > through: os.popen, os.popen2, os.popen3, os.system, > > commands.getoutput() > > > os.system is the oldest way, and it's pretty much obsolete. Only use it > for quick-and-dirty scripts when you're too lazy to do the right thing > and don't care who knows it. It doesn't capture either stdin or stdout, > only the return value. > > os.popen, popen2 and popen3 are probably closer to what you're used to > in Perl. They basically differ in how many file handles they return: > > popen returns the external command's stdout as a file handle. > popen2 returns (stdin, stdout) > popen3 returns (stdin, stdout, stderr) > > The commands module is meant as an easier to use front end to the popen* > functions, for times where popen* are too much and system is too > little. If all you want is the output (stdout + stderr) of an external > command: > > import commands > output = commands.getoutput('ls -l foo*') > > will do the trick. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Jun 26 03:43:49 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 25 Jun 2010 21:43:49 -0400 Subject: [Tutor] Running external commands from Python In-Reply-To: References: <201006261016.17016.steve@pearwood.info> Message-ID: On Fri, Jun 25, 2010 at 9:37 PM, Randy Kao wrote: > Thanks for the great and quick feedback from everyone! > That definitely clears things up. > -Randy > On Fri, Jun 25, 2010 at 5:16 PM, Steven D'Aprano > wrote: >> >> On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote: >> > Hi all, >> > >> > I'm a newbie to Python (switching from Perl) and had a question about >> > the best way to run external commands in Python. >> [...] >> > through: os.popen, os.popen2, os.popen3, os.system, >> > commands.getoutput() >> >> >> os.system is the oldest way, and it's pretty much obsolete. Only use it >> for quick-and-dirty scripts when you're too lazy to do the right thing >> and don't care who knows it. It doesn't capture either stdin or stdout, >> only the return value. >> >> os.popen, popen2 and popen3 are probably closer to what you're used to >> in Perl. They basically differ in how many file handles they return: >> >> popen returns the external command's stdout as a file handle. >> popen2 returns (stdin, stdout) >> popen3 returns (stdin, stdout, stderr) >> >> The commands module is meant as an easier to use front end to the popen* >> functions, for times where popen* are too much and system is too >> little. If all you want is the output (stdout + stderr) of an external >> command: >> >> import commands >> output = commands.getoutput('ls -l foo*') >> >> will do the trick. >> >> >> -- >> Steven D'Aprano >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > And I was like...me too. From rabidpoobear at gmail.com Sat Jun 26 03:50:16 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 25 Jun 2010 20:50:16 -0500 Subject: [Tutor] Running external commands from Python In-Reply-To: References: <201006261016.17016.steve@pearwood.info> Message-ID: On Fri, Jun 25, 2010 at 8:43 PM, David Hutto wrote: > On Fri, Jun 25, 2010 at 9:37 PM, Randy Kao wrote: >> Thanks for the great and quick feedback from everyone! >> That definitely clears things up. >> -Randy > > And I was like...me too. Just to clarify, it looks like subprocess is intended to replace ALL of the previously-mentioned commands, even os.system. So in a sense they are all obsolete. Please see http://docs.python.org/library/subprocess.html for more information. Also, this list is awesome. Make much use of it. There haven't been enough posts lately! -Luke From davea at ieee.org Sat Jun 26 08:08:18 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Jun 2010 02:08:18 -0400 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> Message-ID: <4C259952.9060702@ieee.org> Richard D. Moores wrote: > On Fri, Jun 25, 2010 at 09:48, Emile van Sebille wrote: > >> On 6/25/2010 9:08 AM Steve Willoughby said... >> >>> On 25-Jun-10 08:23, Emile van Sebille wrote: >>> >>>> On 6/25/2010 1:33 AM ALAN GAULD said... >>>> >>>>>> Copy and pasting is a PITA. >>>>>> >>>>> Why would you want to copy and paste? >>>>> >>>> Because it makes it easy to work on code. My preferred editor (TextPad) >>>> allows block selection of indented text such that I can copy and paste >>>> functions and methods into the python CLI and work with them there. I >>>> >>> If what you're trying to do is a PITA, that should raise two questions: >>> >>> >> Points taken, but understand that the OP termed it a PITA, from which Alan >> asked why cut 'n paste. I don't find it a PITA at all and am quite >> comfortable with my approach (editor choice being a religious issue after >> all). My gripe is only that complying with PEP 8 is not possible. >> > > I'm the OP. What I called a PITA is copy and pasting using the Windows > command line. > > Dick > > Do you activate Quick-Edit mode in your DOS box? Once you have that on, it's not much of a pain to copy and paste, as long as what you're copying fits a rectangle. DaveA From rdmoores at gmail.com Sat Jun 26 08:27:55 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 25 Jun 2010 23:27:55 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: <4C259952.9060702@ieee.org> References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> Message-ID: On Fri, Jun 25, 2010 at 23:08, Dave Angel wrote: > Do you activate Quick-Edit mode in your DOS box? ?Once you have that on, > it's not much of a pain to copy and paste, as long as what you're copying > fits a rectangle. Yes, it's on. I agree that copying is easy, but if I can't use Ctrl+V, pasting is a pain. Tell me your secret. Dick From davea at ieee.org Sat Jun 26 08:42:26 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Jun 2010 02:42:26 -0400 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> Message-ID: <4C25A152.7050801@ieee.org> Richard D. Moores wrote: > On Fri, Jun 25, 2010 at 23:08, Dave Angel wrote: > >> Do you activate Quick-Edit mode in your DOS box? Once you have that on, >> it's not much of a pain to copy and paste, as long as what you're copying >> fits a rectangle. >> > > Yes, it's on. I agree that copying is easy, but if I can't use Ctrl+V, > pasting is a pain. Tell me your secret. > > Dick > > If you right-click on a DOS box without anything selected, then it pastes. (Asssuming quickedit mode) For example, you run a command that displays a string, and you want to use that string as your next command: left-drag over the desired text. Right click to copy to clipboard Right click again to paste into current cursor position DaveA From rdmoores at gmail.com Sat Jun 26 09:00:16 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 00:00:16 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors Message-ID: Sorry about the OT, but I'm really nervous about the possibility of screwing up my laptop by upgrading the OS from Vista to 7, and can't think of a better place than Tutors to ask for advice. I bought this Toshiba Satellite last October. It came with the right to receive the upgrade CD for Windows 7 when it became available. I think I finally got the disk in February, but by that time I'd gotten used to Vista, and Vista was then, as now, in SP2 (64-bit). By that time a generally computer-savvy friend (but who runs linux) was telling me to not do the upgrade because I'd end up with problems with 7 and also with a lot of the software I had already installed. Then recently I've talked to a couple of guys (separately) in 2 Office Depots near Seattle who both told me that the Vista -> 7 upgrade should go without any trouble at all. That I should do the upgrade, then immediately download and install all the updates for 7 that MS has issued. Both used used to do such upgrades for customers for a fee ($40), but not anymore. So they didn't have anything to sell me -- I think they were being honest about their experience. Has anyone here done the upgrade I'm considering, or know of anyone who has? Any advice or anecdotes for me? Thanks, Dick Moores From rdmoores at gmail.com Sat Jun 26 09:04:15 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 00:04:15 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: <4C25A152.7050801@ieee.org> References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> <4C25A152.7050801@ieee.org> Message-ID: On Fri, Jun 25, 2010 at 23:42, Dave Angel wrote: > Richard D. Moores wrote: >> >> On Fri, Jun 25, 2010 at 23:08, Dave Angel wrote: >> >>> >>> Do you activate Quick-Edit mode in your DOS box? ?Once you have that on, >>> it's not much of a pain to copy and paste, as long as what you're copying >>> fits a rectangle. >>> >> >> Yes, it's on. I agree that copying is easy, but if I can't use Ctrl+V, >> pasting is a pain. Tell me your secret. >> >> Dick >> >> > > If you right-click on a DOS box without anything selected, then it pastes. > ?(Asssuming quickedit mode) > > For example, you run a command that displays a string, and you want to use > that string as your next command: > > left-drag over the desired text. > Right click to copy to clipboard > Right click again to paste into current cursor position Hey, terrific! Thanks, Dave! I didn't see any help available. Where'd you learn this? Dick From anand.shashwat at gmail.com Sat Jun 26 09:27:27 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 26 Jun 2010 12:57:27 +0530 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: Message-ID: I am not a window user myself but all my friends who upgraded are quite happy about it. AFAIK Vista was a failure but 7 is good, so it is worth upgrading. On Sat, Jun 26, 2010 at 12:30 PM, Richard D. Moores wrote: > Sorry about the OT, but I'm really nervous about the possibility of > screwing up my laptop by upgrading the OS from Vista to 7, and can't > think of a better place than Tutors to ask for advice. > > I bought this Toshiba Satellite last October. It came with the right > to receive the upgrade CD for Windows 7 when it became available. I > think I finally got the disk in February, but by that time I'd gotten > used to Vista, and Vista was then, as now, in SP2 (64-bit). By that > time a generally computer-savvy friend (but who runs linux) was > telling me to not do the upgrade because I'd end up with problems with > 7 and also with a lot of the software I had already installed. > > Then recently I've talked to a couple of guys (separately) in 2 Office > Depots near Seattle who both told me that the Vista -> 7 upgrade > should go without any trouble at all. That I should do the upgrade, > then immediately download and install all the updates for 7 that MS > has issued. Both used used to do such upgrades for customers for a fee > ($40), but not anymore. So they didn't have anything to sell me -- I > think they were being honest about their experience. > > Has anyone here done the upgrade I'm considering, or know of anyone > who has? Any advice or anecdotes for me? > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 26 10:21:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jun 2010 09:21:20 +0100 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> <4C25A152.7050801@ieee.org> Message-ID: "Richard D. Moores" wrote >> left-drag over the desired text. >> Right click to copy to clipboard >> Right click again to paste into current cursor position > > Hey, terrific! Thanks, Dave! I didn't see any help available. > Where'd > you learn this? There is a fair amount of help in Wiindows Help. Start->Help and search for CMD The other way to paste is via the top left menu, Edit->Paste which is what I tend to use. Alan G. From rdmoores at gmail.com Sat Jun 26 10:26:39 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 01:26:39 -0700 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> <4C25A152.7050801@ieee.org> Message-ID: On Sat, Jun 26, 2010 at 01:21, Alan Gauld wrote: > > "Richard D. Moores" wrote >>> >>> left-drag over the desired text. >>> Right click to copy to clipboard >>> Right click again to paste into current cursor position >> >> Hey, terrific! Thanks, Dave! I didn't see any help available. Where'd >> you learn this? > > There is a fair amount of help in Wiindows Help. > > Start->Help and search for CMD OK. I'll take a look. > The other way to paste is via the top left menu, Edit->Paste > which is what I tend to use. I knew about that. In fact, it's what I was calling a PITA. :) Dick From alan.gauld at btinternet.com Sat Jun 26 10:30:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jun 2010 09:30:27 +0100 Subject: [Tutor] need computer advice from wise Tutors References: Message-ID: "Richard D. Moores" wrote > Sorry about the OT, but I'm really nervous about the possibility of > screwing up my laptop by upgrading the OS from Vista to 7, and can't > think of a better place than Tutors to ask for advice. Going from Vista to Windows 7 is a relatively painless process - unlike going from XP to 7. (Microsoft have scored a huge own goal with missing out this upgrade path IMHO!) And 7 is a vast improvement over Vista, which is appallingly bad, again IMHO! However, to quote the old adage - "If it ain't broke, don't fix it". So what is the problem that you think the upgrade will fix? Alan G. Still on XP because nothing is broke... From amarantos at live.com.au Sat Jun 26 06:41:30 2010 From: amarantos at live.com.au (F C) Date: Sat, 26 Jun 2010 15:11:30 +1030 Subject: [Tutor] Creating A Simple Blog System Using Python Programming Message-ID: Hi there, - I have recently decided to learn Python. - It is my first programming language. - I am new to programming. - I know XHTML and CSS, and a few lines of PHP. - I only started learning a couple of days ago. What I want to do is create a simple blog system. Where I can - create posts, edit them and post them online Thus far, people have pointed me to frameworks. >From what I see, the framework does the work for you... I want to code the blog from scratch...after all - I want to learn the language - I don't want something to do the work for me. I truly do not know where to start, because most of the tutorials are segmented, and I don't know how to structure the program, let alone what commands to include. I would appreciate it if someone could give me some structure advice on how to tackle this. Many thanks to the person(s) who can help. _________________________________________________________________ If It Exists, You'll Find it on SEEK. Australia's #1 job site http://clk.atdmt.com/NMN/go/157639755/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 26 10:35:14 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jun 2010 09:35:14 +0100 Subject: [Tutor] Running external commands from Python References: Message-ID: "Randy Kao" wrote > In trying to do this in Python, I think I've read a couple ways to > do this. > > through: os.popen, os.popen2, os.popen3, os.system, > commands.getoutput() > This is historically one of the things that Python has had trouble with. The things you list have all been introduced over the years to "improve" how it works. The current "official" method is to use the subprocess module which replaces all of the above. But it does so by adding some complexity and to really master it requires a fair bit of study and experimentation. The good news is that the complexity offers a very rich set of tools that can do pretty much anything tyou could imagine in the way of working with external programs. The "Working with the OS" topic in my tutorioal(V2 only) has some basic examples of both the older techniques and the subprocess method. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mhw at doctors.net.uk Sat Jun 26 10:39:29 2010 From: mhw at doctors.net.uk (mhw at doctors.net.uk) Date: Sat, 26 Jun 2010 08:39:29 +0000 Subject: [Tutor] Getting an object's attributes Message-ID: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> Dear Tutors, I have an object to which I dynamically add attributes. My question is how I can inspect and display them at run-time? Class a(): pass Obj1 = a() Obj1.name = "Bob" Obj1.age = 45 dir(a) returns a tuple which contains name and age, but also other things (includings methods, etc.) I could filter this tuple (checking for callable(), etc.) but I just wondered if there was an existing way of getting just name and age. Thanks, Matt Sent from my BlackBerry? wireless device From evert.rol at gmail.com Sat Jun 26 11:13:16 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sat, 26 Jun 2010 11:13:16 +0200 Subject: [Tutor] Getting an object's attributes In-Reply-To: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> References: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> Message-ID: > I have an object to which I dynamically add attributes. My question is how I can inspect and display them at run-time? > > Class a(): > pass > > Obj1 = a() > > Obj1.name = "Bob" > Obj1.age = 45 First off, a few suggestions: - you probably mean 'class', not 'Class' (sorry, but it's just that correct actual code helps: copy-paste from the Python prompt when you can. If you have a text-editor in your mail program that capitalises things, be careful when pasting code). - use capitalisation (or CamelCase) for class names, lowercase for instances: class A, obj1 = A(). This is the usual Python convention. - I would use new-style classes, ie, inherit from object: >>> class A(object): ... pass ... >>> obj1 = A() > dir(a) returns a tuple which contains name and age, but also other things (includings methods, etc.) I could filter this tuple (checking for callable(), etc.) but I just wondered if there was an existing way of getting just name and age. Normally, you know which attributes you want to access, so you wouldn't have this problem. Better yet, you wrap things in a try-except clause and see if that works: >>> try: ... obj1.name ... except AttributeError: ... print "not there" ... not there But for this case, when using new-style classes, obj1.__dict__ can help you (or obj1.__dict__.keys() ). >>> obj1.name = "Bob" >>> obj1.age = 45 >>> obj1.__dict__ {'age': 45, 'name': 'Bob'} Or, perhaps somewhat silly: set(dir(obj1)) - set(dir(A)). >>> set(dir(obj1)) - set(dir(A)) set(['age', 'name']) but I wouldn't recommend that. See eg http://docs.python.org/library/stdtypes.html#special-attributes From steve at pearwood.info Sat Jun 26 12:10:33 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Jun 2010 20:10:33 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: Message-ID: <201006262010.34337.steve@pearwood.info> On Sat, 26 Jun 2010 05:00:16 pm Richard D. Moores wrote: > Sorry about the OT, but I'm really nervous about the possibility of > screwing up my laptop by upgrading the OS from Vista to 7, and can't > think of a better place than Tutors to ask for advice. Because of course knowing Python makes you an expert on Windows :) [...] > Then recently I've talked to a couple of guys (separately) in 2 > Office Depots near Seattle who both told me that the Vista -> 7 > upgrade should go without any trouble at all. That I should do the > upgrade, then immediately download and install all the updates for 7 > that MS has issued. Both used used to do such upgrades for customers > for a fee ($40), but not anymore. Why did they stop? Could it be because the upgrade is sometimes difficult and requires huge amount of manual effort to get it working, far more than $40 will cover? Cynical? Who, me? -- Steven D'Aprano From steve at pearwood.info Sat Jun 26 12:17:48 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Jun 2010 20:17:48 +1000 Subject: [Tutor] Getting an object's attributes In-Reply-To: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> References: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> Message-ID: <201006262017.49072.steve@pearwood.info> On Sat, 26 Jun 2010 06:39:29 pm mhw at doctors.net.uk wrote: > Dear Tutors, > > I have an object to which I dynamically add attributes. My question > is how I can inspect and display them at run-time? > > Class a(): > pass > > Obj1 = a() > > Obj1.name = "Bob" > Obj1.age = 45 > > dir(a) returns a tuple which contains name and age, but also other > things (includings methods, etc.) I could filter this tuple (checking > for callable(), etc.) but I just wondered if there was an existing > way of getting just name and age. If you know they are called name and age, just access them like you did above: Obj1.name Obj1.age If you don't know they are called name and age, then how do you expect Python to know which of the many attributes and methods are the ones you want? Before you start writing your own filters, you should check out the inspect module, which already has most of that functionality ready-made. There's no general way to ask "which attributes were added dynamically?" because all of them are. The difference is that some of them are added dynamically when the class is created, some are added dynamically when the instance is initialised, and some are added dynamically later. But they're all added dynamically. Python doesn't track when attributes are added because, in general, it's an unimportant difference. -- Steven D'Aprano From rdmoores at gmail.com Sat Jun 26 12:53:57 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 03:53:57 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006262010.34337.steve@pearwood.info> References: <201006262010.34337.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 03:10, Steven D'Aprano wrote: > On Sat, 26 Jun 2010 05:00:16 pm Richard D. Moores wrote: >> Sorry about the OT, but I'm really nervous about the possibility of >> screwing up my laptop by upgrading the OS from Vista to 7, and can't >> think of a better place than Tutors to ask for advice. > > Because of course knowing Python makes you an expert on Windows :) > > > [...] >> Then recently I've talked to a couple of guys (separately) in 2 >> Office Depots near Seattle who both told me that the Vista -> 7 >> upgrade should go without any trouble at all. That I should do the >> upgrade, then immediately download and install all the updates for 7 >> that MS has issued. Both used used to do such upgrades for customers >> for a fee ($40), but not anymore. > > Why did they stop? Could it be because the upgrade is sometimes > difficult and requires huge amount of manual effort to get it working, > far more than $40 will cover? Do you know that it does? Please tell me what you know. > > Cynical? Who, me? > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From payal-python at scriptkitchen.com Sat Jun 26 14:17:45 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sat, 26 Jun 2010 05:17:45 -0700 Subject: [Tutor] class questions Message-ID: <20100626121745.GA6916@scriptkitchen.com> Hi, Some questions about which I am a bit confused. 1. I know there is a difference between mro of classic and new style classes. but I do not get why we need the new mro, the old one is easy to predict and understand? 2. A friend of mine told me that in C++ abstract classes are classes which can not be instatiated. Is she right, do we have them in python, if yes can someone give a simple example? 3. In http://www.alan-g.me.uk/tutor/index.htm , Alan has given an example in "User Defined Exceptions", >>> class BrokenError(Exception): pass Even after reading the section a few times over, I fail to get utility of such a class. Can someone please explain with better example? Alan can you please cleanup that section, maybe make it broader and put the stuff about "SystemExit" elsewhere. Thanks a lot in advance. With warm regards, -Payal -- From steve at pearwood.info Sat Jun 26 14:39:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Jun 2010 22:39:54 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> Message-ID: <201006262239.54757.steve@pearwood.info> On Sat, 26 Jun 2010 08:53:57 pm you wrote: > > Why did they stop? Could it be because the upgrade is sometimes > > difficult and requires huge amount of manual effort to get it > > working, far more than $40 will cover? > > Do you know that it does? Please tell me what you know. I have no idea. That's why I asked: > > Cynical? Who, me? -- Steven D'Aprano From davea at ieee.org Sat Jun 26 14:59:01 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Jun 2010 08:59:01 -0400 Subject: [Tutor] Use flag to exit? (OT - PEP 8 Gripe) In-Reply-To: References: <783485.66107.qm@web86704.mail.ird.yahoo.com> <4C24D470.2010207@alchemy.com> <4C259952.9060702@ieee.org> <4C25A152.7050801@ieee.org> Message-ID: <4C25F995.4090408@ieee.org> Richard D. Moores wrote: > On Fri, Jun 25, 2010 at 23:42, Dave Angel wrote: > >> Richard D. Moores wrote: >> >>> On Fri, Jun 25, 2010 at 23:08, Dave Angel wrote: >>> >>> >>>> Do you activate Quick-Edit mode in your DOS box? Once you have that on, >>>> it's not much of a pain to copy and paste, as long as what you're copying >>>> fits a rectangle. >>>> >>>> >>> Yes, it's on. I agree that copying is easy, but if I can't use Ctrl+V, >>> pasting is a pain. Tell me your secret. >>> >>> Dick >>> >>> >>> >> If you right-click on a DOS box without anything selected, then it pastes. >> (Asssuming quickedit mode) >> >> For example, you run a command that displays a string, and you want to use >> that string as your next command: >> >> left-drag over the desired text. >> Right click to copy to clipboard >> Right click again to paste into current cursor position >> > > Hey, terrific! Thanks, Dave! I didn't see any help available. Where'd > you learn this? > > Dick > > I really don't recall where I learned it, but I do remember approximately when. It was about 1994, with Windows NT version 3.5 DaveA From steve at pearwood.info Sat Jun 26 15:07:17 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Jun 2010 23:07:17 +1000 Subject: [Tutor] class questions In-Reply-To: <20100626121745.GA6916@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> Message-ID: <201006262307.17364.steve@pearwood.info> On Sat, 26 Jun 2010 10:17:45 pm Payal wrote: > Hi, > Some questions about which I am a bit confused. > > 1. I know there is a difference between mro of classic and new style > classes. but I do not get why we need the new mro, the old one is > easy to predict and understand? The old MRO (Method Resolution Order) is broken for classes using multiple inheritance with a diamond shape inheritance diagram. Not a little bit broken, but horribly, horribly broken. If you have something like this class hierarchy: class A: pass class B(A): pass class C(A): pass class D(B, C): pass (only with actual methods, of course) then inheritance with old-style classes cannot work correctly in some circumstances. Fortunately this sort of inheritance diagram: A / \ B C \ / D is rare for old-style classes. But for new-style classes, *all* multiple inheritance is diamond-shaped, because all classes inherit back to object at the top of the diagram: object / \ list str \ / myclass So in order to allow people to inherit from built-ins, we had a choice: (1) Keep the old MRO and a bug which used to be rare would become common; (2) Keep the old MRO but prohibit multiple inheritance and mixins (which would mean breaking a lot of existing code); or (3) Change the MRO to one which doesn't have the bug. The Python developers choose 3. Well, actually, that's not quite true: nobody noticed that the MRO was broken until *after* new-style classes were added in version 2.2, and so the new MRO was added in version 2.3. http://www.python.org/download/releases/2.3/mro/ > 2. A friend of mine told me that in C++ abstract classes are classes > which can not be instatiated. Is she right, do we have them in > python, if yes can someone give a simple example? Python doesn't have a special "abstract class" type, but it is easy to make one with just two lines of boilerplate: class AbstractThing: def __init__(self): # Next two lines are boilerplate. if type(self) is Abstract: raise TypeError("abstract class, you must subclass this") # init code for non-abstract Thing classes goes here > 3. In http://www.alan-g.me.uk/tutor/index.htm , Alan has given an > example in "User Defined Exceptions", > > >>> class BrokenError(Exception): pass > > Even after reading the section a few times over, I fail to get > utility of such a class. Can someone please explain with better > example? Alan can you please cleanup that section, maybe make it > broader and put the stuff about "SystemExit" elsewhere. The utility of user-defined exceptions is simply to allow your code to distinguish between *your* exceptions and other exceptions. Different people have different policies. Some people prefer this: def func(x): if x <= 0: raise ValueError('x must be positive') return sqrt(x) + x**2 Other people prefer this: class DomainError(ValueError): """Used for mathematics domain errors.""" pass def func(x): if x <= 0: raise DomainError('x must be positive') return math.sqrt(x) + math.asin(x**2) Then when you catch an error: try: print func(y) except DomainError: # only catches my own error except ValueError: # catches any other ValueError But both solutions are equally good. Normally you don't want fifty different exception classes in a module, nor do you want every exception to be the same generic class. How finely you divide the error classes is up to you. -- Steven D'Aprano From waynejwerner at gmail.com Sat Jun 26 15:27:38 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 26 Jun 2010 08:27:38 -0500 Subject: [Tutor] need computer advice from wise Tutors In-Reply-To: References: Message-ID: On Sat, Jun 26, 2010 at 3:30 AM, Alan Gauld wrote: > "Richard D. Moores" wrote > > However, to quote the old adage - "If it ain't broke, don't fix it". > So what is the problem that you think the upgrade will fix? > The problem? He has Vista installed... (rimshot) ;) -Wayne, Also on XP (and Ubuntu...) -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Jun 26 15:49:52 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 26 Jun 2010 08:49:52 -0500 Subject: [Tutor] Creating A Simple Blog System Using Python Programming In-Reply-To: References: Message-ID: On Fri, Jun 25, 2010 at 11:41 PM, F C wrote: > Hi there, > > - I have recently decided to learn Python. > - It is my first programming language. > - I am new to programming. > - I know XHTML and CSS, and a few lines of PHP. > - I only started learning a couple of days ago. > Well congratulations on starting what many of us feel is a wonderful journey! And probably most of us feel is an excellent choice for starting out. > What I want to do is create a simple blog system. > Where I can > - create posts, edit them and post them online > An ambitious goal... And a fairly achievable one (though of course you still have plenty to learn at this point. I'd guess most of us who have been programming in Python for a few years could probably knock something out in a day or two, but I wouldn't expect results near that quick as you'll have to learn both programming concepts and a language. But Python excels at being a simple language to learn so you can ignore more of the "advanced" programming topics until you're ready) > > Thus far, people have pointed me to frameworks. > From what I see, the framework does the work for you... > I want to code the blog from scratch...after all - I want to learn the > language - I don't want something to do the work for me. > > I truly do not know where to start, because most of the tutorials are > segmented, and I don't know how to structure the > program, let alone what commands to include. > > I would appreciate it if someone could give me some structure advice on how > to tackle this. > Well, here's what I would do: 1) Build a *simple* web form - an entry for a title, a text area for the text of the post, and a submit/save button. You can add features later as you feel you need them (like a login window), but for now simple is better. 2) Write a program that connects to a database (SQLite is included in most Python installs) and allows you to insert and retrieve posts. You'll need to learn some SQL syntax for this. 3) Hook the two together. 4) Enjoy the satisfaction of "completing" your first project. I've really simplified the tasks here - you'll have to get a web host that gives you access to python (or host it yourself), learn how to work with Python+HTML (it's not that difficult, but you'll be learning several concepts at once which adds some to the complexity), learn the SQL language in addition to Python... and whatever else happens to pop up. The important thing is to be able to look at the problem and break it up into chunks. If you ask yourself these two questions: "What do I need next?" "What can I do *now* to accomplish that?" you'll find yourself moving rapidly towards finishing your project. That's how I came up with those tasks - "What do I need next?" "Well, I can't post a blog without somewhere to enter the post." - so that's the first task. What's next? Well, I have to have a way to save the blog posts. Ooh, a database is ideal for collecting data so I can easily retrieve it. So I'll need to be able to connect to the DB somehow. Once you get more familiar with programming and concepts, you'll start to be able to break problems up into much more manageable chunks, and you'll start to see where you can logically break your programs up into different modules and functions - pieces of code that you can reuse as part of a larger program. Anyhow, good luck, and HTH! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sat Jun 26 18:20:20 2010 From: python at bdurham.com (python at bdurham.com) Date: Sat, 26 Jun 2010 12:20:20 -0400 Subject: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives? In-Reply-To: <1277309445.2173.1381531403@webmail.messagingengine.com> References: <1277309445.2173.1381531403@webmail.messagingengine.com> Message-ID: <1277569220.26165.1382020875@webmail.messagingengine.com> Updating this thread for users searching the archives. Additional commentary can be found in this thread I started on Stackoverflow.com. http://stackoverflow.com/questions/3120295/confirm-that-python-2-6-ftplib-does-not-support-unicode-file-names-alternatives Gabriel Genellina added the following comment on Python-list: According to RFC 2640, you should use UTF-8 instead. http://www.faqs.org/rfcs/rfc2640.html The server software must be able to convert from file system encoding to utf-8 and viceversa; check its configuration. The stackoverflow thread mentioned above also contains a workaround/ugly-hack if you need to use Unicode path/file names with ftplib and/or a file server that does not support Unicode path/file names. Malcolm From payal-python at scriptkitchen.com Sat Jun 26 19:05:16 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sat, 26 Jun 2010 10:05:16 -0700 Subject: [Tutor] class questions In-Reply-To: <201006262307.17364.steve@pearwood.info> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> Message-ID: <20100626170516.GA9617@scriptkitchen.com> Thanks a lot for the quick answer. Still some doubts below. On Sat, Jun 26, 2010 at 11:07:17PM +1000, Steven D'Aprano wrote: > The old MRO (Method Resolution Order) is broken for classes using > multiple inheritance with a diamond shape inheritance diagram. Not a > little bit broken, but horribly, horribly broken. > > If you have something like this class hierarchy: [...] > (only with actual methods, of course) then inheritance with old-style > classes cannot work correctly in some circumstances. Fortunately this Can you give any simple example where this simple mro will work incorrectly? i read, http://www.python.org/download/releases/2.3/mro/ butdid not get where mro will fail (ofcourse if python implemented it corrrectly). > is rare for old-style classes. But for new-style classes, *all* multiple > inheritance is diamond-shaped, because all classes inherit back to > object at the top of the diagram: still not getting , how do the new style classes solve the problem (if there was any). > Python doesn't have a special "abstract class" type, but it is easy to > make one with just two lines of boilerplate: [...] Sorry, I am not getting it. I get, NameError: global name 'Abstract' is not defined Was that a working code? (cos' I do not know what you mean by boilerplate) > class DomainError(ValueError): > """Used for mathematics domain errors.""" > pass Can we say that our own exception classes have only maybe a doc-string and pass, nothing more? Thanks a lot again. With warm regards, -Payal -- From vceder at canterburyschool.org Sat Jun 26 19:13:46 2010 From: vceder at canterburyschool.org (Vern Ceder) Date: Sat, 26 Jun 2010 13:13:46 -0400 Subject: [Tutor] Creating A Simple Blog System Using Python Programming In-Reply-To: References: Message-ID: <4C26354A.1090705@canterburyschool.org> F C wrote: > Hi there, > > - I have recently decided to learn Python. > - It is my first programming language. > - I am new to programming. > - I know XHTML and CSS, and a few lines of PHP. > - I only started learning a couple of days ago. > > What I want to do is create a simple blog system. > Where I can > - create posts, edit them and post them online > > Thus far, people have pointed me to frameworks. > From what I see, the framework does the work for you... > I want to code the blog from scratch...after all - I want to learn the > language - I don't want something to do the work for me. Managing the details of a framework could distract you from the basics of learning Python, IMHO, but they do make a lot things much easier. As it happens, I use a similar example (a message wall) in my book, The Quick Python Book, 2nd ed. (see link in my sig). While I can't reproduce that chapter here, I can tell you that you want to use the wsgiref server included in the Python standard library, and you should read through the online docs and examples for the wsgiref module on the python.org site. Then for storage of your posts, you might just want to use text files at first, and then consider picking up sqlite3 or another database later on. Cheers, Vern > > I truly do not know where to start, because most of the tutorials are > segmented, and I don't know how to structure the > program, let alone what commands to include. > > I would appreciate it if someone could give me some structure advice on > how to tackle this. > > Many thanks to the person(s) who can help. > ------------------------------------------------------------------------ > Australia's #1 job site If It Exists, You'll Find it on SEEK > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW From zebra05 at gmail.com Sat Jun 26 20:55:13 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Sat, 26 Jun 2010 20:55:13 +0200 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006262239.54757.steve@pearwood.info> References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: Richard, I think you may go ahead without trepidation. I am not a Windows fan at all, I prefer Ubuntu. But I started using Win. 7 at work about a month ago, and I have to say it hasn't given me cause to grumble. Of course, a month is hardly sufficient time to have a strong opinion, but I can tell you that it works just fine. On Sat, Jun 26, 2010 at 2:39 PM, Steven D'Aprano wrote: > On Sat, 26 Jun 2010 08:53:57 pm you wrote: > > > Why did they stop? Could it be because the upgrade is sometimes > > > difficult and requires huge amount of manual effort to get it > > > working, far more than $40 will cover? > > > > Do you know that it does? Please tell me what you know. > > I have no idea. That's why I asked: > > > > Cynical? Who, me? > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sat Jun 26 22:31:26 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 13:31:26 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 11:55, Sithembewena Lloyd Dube wrote: > Richard, I think you may go ahead without trepidation. I am not a Windows > fan at all, I prefer Ubuntu. But I started using Win. 7 at work about a > month ago, and I have to say it hasn't given me cause to grumble. > > Of course, a month is hardly sufficient time to have a strong opinion, but I > can tell you that it works just fine. Thanks, but I'm not worried about Win 7 working well when perfectly installed. I'm concerned that if I upgrade to 7 from Vista using the upgrade disk I have, that THAT 7 on my laptop will end up with problems caused by the install. Dick From zebra05 at gmail.com Sat Jun 26 22:39:26 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Sat, 26 Jun 2010 22:39:26 +0200 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: Hi Dick, In that case, perhaps you could externally back up all your important stuff and then format your hard disk. That way, any drivers etc intended for Windows Vista will be wiped off, and you can then perform a clean installation from your disk. Now, as far as upgrade disks go, I do not know whether it will work as a "clean installation" disk, or whether it is only meant for use on an existing windows installation (hence the name "upgrade"). You might want to check that out first. Let us know how it goes. On Sat, Jun 26, 2010 at 10:31 PM, Richard D. Moores wrote: > On Sat, Jun 26, 2010 at 11:55, Sithembewena Lloyd Dube > wrote: > > Richard, I think you may go ahead without trepidation. I am not a Windows > > fan at all, I prefer Ubuntu. But I started using Win. 7 at work about a > > month ago, and I have to say it hasn't given me cause to grumble. > > > > Of course, a month is hardly sufficient time to have a strong opinion, > but I > > can tell you that it works just fine. > > Thanks, but I'm not worried about Win 7 working well when perfectly > installed. I'm concerned that if I upgrade to 7 from Vista using the > upgrade disk I have, that THAT 7 on my laptop will end up with > problems caused by the install. > > Dick > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Sat Jun 26 22:41:59 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 26 Jun 2010 22:41:59 +0200 Subject: [Tutor] class questions In-Reply-To: <20100626170516.GA9617@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> Message-ID: <201006262241.59867.eike.welk@gmx.net> Hello Payal! On Saturday June 26 2010 19:05:16 Payal wrote: > Can we say that our own exception classes have only maybe a doc-string > and pass, nothing more? No, you let the exception transport the information that you need for handling the error. This is an exception that I use to transport user visible error messages in a compiler, that I write as a hobby: class UserException(Exception): '''Exception that transports user visible error messages.''' def __init__(self, message, loc=None, errno=None): Exception.__init__(self) self.msg = message self.loc = loc self.errno = errno def __str__(self): if self.errno is None: num_str = '' else: num_str = '(#%s) ' % str(self.errno) return 'Error! ' + num_str + self.msg + '\n' + str(self.loc) + '\n' def __repr__(self): return self.__class__.__name__ + str((self.msg, self.loc, self.errno)) It contains: self.msg : The error message self.loc : An object encoding the location of the error in the program's text. Together with the file name and the text. self.errno : An integer to identify the error, for the test framework. That said; the expression's type and the error message are often sufficient to handle the error. Eike. From eduardo.susan at gmail.com Sat Jun 26 23:20:29 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Sat, 26 Jun 2010 15:20:29 -0600 Subject: [Tutor] Advice on math Message-ID: Hello, I've enjoying learning python for the first few years, and appreciate all the help I have received from this list. I had some interest in programming and am very glad to have made python my choice of programming language. Since I didn't go to college for computer studies, I feel my math is kind of rusty in some areas, and looks like improving/regaining math skills would help a lot in programming, logic, algorithms, etc. Right now I think I need a better understanding of logarithm, arrays (matrixes), and even probability. What links would you all recommend that would be useful for me to learn these things in a newbie-friendly way? With thankfulness, Eduardo www.expresssignproducts.com www.express-sign-supply.com From anand.shashwat at gmail.com Sat Jun 26 23:26:04 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 27 Jun 2010 02:56:04 +0530 Subject: [Tutor] Advice on math In-Reply-To: References: Message-ID: On Sun, Jun 27, 2010 at 2:50 AM, Eduardo Vieira wrote: > Hello, I've enjoying learning python for the first few years, and > appreciate all the help I have received from this list. I had some > interest in programming and am very glad to have made python my choice > of programming language. Since I didn't go to college for computer > studies, I feel my math is kind of rusty in some areas, and looks like > improving/regaining math skills would help a lot in programming, > logic, algorithms, etc. > Right now I think I need a better understanding of logarithm, arrays > (matrixes), and even probability. What links would you all recommend > that would be useful for me to learn these things in a newbie-friendly > way? > > > If you want to code+learn, nothing beats ProjectEuler ( http://projecteuler.net/ ). However I assume you have basic understanding of maths. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sat Jun 26 23:30:34 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 14:30:34 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 13:39, Sithembewena Lloyd Dube wrote: > Hi Dick, > > In that case, perhaps you could externally back up all your important stuff > and then format your hard disk. That way, any drivers etc intended for > Windows Vista will be wiped off, and you can then perform a clean > installation from your disk. Now, as far as upgrade disks go, I do not know > whether it will work as a "clean installation" disk, or whether it is only > meant for use on an existing windows installation (hence the name > "upgrade"). You might want to check that out first. I don't believe the disk I have will enable a clean installation. I found a relevant thread in the WindowsSecrets Lounge: , which seems to have some good info and advice. > Let us know how it goes. OK. Dick From alan.gauld at btinternet.com Sat Jun 26 23:48:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jun 2010 22:48:18 +0100 Subject: [Tutor] Advice on math References: Message-ID: "Eduardo Vieira" wrote > Right now I think I need a better understanding of logarithm, arrays > (matrixes), and even probability. What links would you all recommend > that would be useful for me to learn these things in a > newbie-friendly > way? Wikipedia? Pretty good on most things math and science bawsed. Just stop reading when it gets too deep - as it invariably will! :-) Alan G. From marc.tompkins at gmail.com Sun Jun 27 00:04:11 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 26 Jun 2010 15:04:11 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 2:30 PM, Richard D. Moores wrote: > On Sat, Jun 26, 2010 at 13:39, Sithembewena Lloyd Dube > wrote: > > Hi Dick, > > > > In that case, perhaps you could externally back up all your important > stuff > > and then format your hard disk. That way, any drivers etc intended for > > Windows Vista will be wiped off, and you can then perform a clean > > installation from your disk. Now, as far as upgrade disks go, I do not > know > > whether it will work as a "clean installation" disk, or whether it is > only > > meant for use on an existing windows installation (hence the name > > "upgrade"). You might want to check that out first. > > I don't believe the disk I have will enable a clean installation. > I'm pretty sure it will: http://www.winsupersite.com/win7/clean_install_upgrade_media.asp http://www.mydigitallife.info/2009/10/27/clean-install-windows-7-with-upgrade-media-and-product-key-on-formatted-or-empty-blank-hard-drive/ The upshot of both those articles is: boot from the upgrade disk as if it were a normal Full Install disk; when it asks for the Windows key, leave it blank. Don't enter the key until after the installation is complete, when you want to activate. Since you CAN use that disk as a clean install, I definitely recommend that you DO. When I upgraded my laptop to Windows 7, I bought myself a new 500GB hard drive for the purpose. $60 and five minutes with a small screwdriver brought me a huge dividend in peace of mind. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhw at doctors.net.uk Sun Jun 27 00:03:29 2010 From: mhw at doctors.net.uk (mhw at doctors.net.uk) Date: Sat, 26 Jun 2010 22:03:29 +0000 Subject: [Tutor] Getting an object's attributes In-Reply-To: References: <328569863-1277541605-cardhu_decombobulator_blackberry.rim.net-917512924-@bda188.bisx.produk.on.blackberry> Message-ID: <646217356-1277589845-cardhu_decombobulator_blackberry.rim.net-1873317269-@bda188.bisx.produk.on.blackberry> Apol. For TP: This is perfect - thanks. Matt Sent from my BlackBerry? wireless device -----Original Message----- From: Evert Rol Date: Sat, 26 Jun 2010 11:13:16 To: Cc: Python tutor Subject: Re: [Tutor] Getting an object's attributes > I have an object to which I dynamically add attributes. My question is how I can inspect and display them at run-time? > > Class a(): > pass > > Obj1 = a() > > Obj1.name = "Bob" > Obj1.age = 45 First off, a few suggestions: - you probably mean 'class', not 'Class' (sorry, but it's just that correct actual code helps: copy-paste from the Python prompt when you can. If you have a text-editor in your mail program that capitalises things, be careful when pasting code). - use capitalisation (or CamelCase) for class names, lowercase for instances: class A, obj1 = A(). This is the usual Python convention. - I would use new-style classes, ie, inherit from object: >>> class A(object): ... pass ... >>> obj1 = A() > dir(a) returns a tuple which contains name and age, but also other things (includings methods, etc.) I could filter this tuple (checking for callable(), etc.) but I just wondered if there was an existing way of getting just name and age. Normally, you know which attributes you want to access, so you wouldn't have this problem. Better yet, you wrap things in a try-except clause and see if that works: >>> try: ... obj1.name ... except AttributeError: ... print "not there" ... not there But for this case, when using new-style classes, obj1.__dict__ can help you (or obj1.__dict__.keys() ). >>> obj1.name = "Bob" >>> obj1.age = 45 >>> obj1.__dict__ {'age': 45, 'name': 'Bob'} Or, perhaps somewhat silly: set(dir(obj1)) - set(dir(A)). >>> set(dir(obj1)) - set(dir(A)) set(['age', 'name']) but I wouldn't recommend that. See eg http://docs.python.org/library/stdtypes.html#special-attributes From g.nius.ck at gmail.com Sun Jun 27 01:38:05 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 26 Jun 2010 19:38:05 -0400 Subject: [Tutor] class questions In-Reply-To: <20100626121745.GA6916@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> Message-ID: Well the application of defining ones own error is in a module. For example, if I make a banking account module, I might define a WithdrawError if there is a place where a error might occur. That way if client code tries to withdraw too much, you can have a very descriptive error making it easier to understand. On Sat, Jun 26, 2010 at 8:17 AM, Payal wrote: > Hi, > Some questions about which I am a bit confused. > > 1. I know there is a difference between mro of classic and new style > classes. but I do not get why we need the new mro, the old one is easy > to predict and understand? > > 2. A friend of mine told me that in C++ abstract classes are classes > which can not be instatiated. Is she right, do we have them in python, > if yes can someone give a simple example? > > 3. In http://www.alan-g.me.uk/tutor/index.htm , Alan has given an > example in "User Defined Exceptions", > >>> class BrokenError(Exception): pass > > Even after reading the section a few times over, I fail to get utility > of such a class. Can someone please explain with better example? > Alan can you please cleanup that section, maybe make it broader and put > the stuff about "SystemExit" elsewhere. > > Thanks a lot in advance. > > With warm regards, > -Payal > -- > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Sun Jun 27 01:43:29 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 26 Jun 2010 19:43:29 -0400 Subject: [Tutor] class questions In-Reply-To: <20100626121745.GA6916@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> Message-ID: only new classes can have properties, a major tool On Sat, Jun 26, 2010 at 8:17 AM, Payal wrote: > Hi, > Some questions about which I am a bit confused. > > 1. I know there is a difference between mro of classic and new style > classes. but I do not get why we need the new mro, the old one is easy > to predict and understand? > > 2. A friend of mine told me that in C++ abstract classes are classes > which can not be instatiated. Is she right, do we have them in python, > if yes can someone give a simple example? > > 3. In http://www.alan-g.me.uk/tutor/index.htm , Alan has given an > example in "User Defined Exceptions", > >>> class BrokenError(Exception): pass > > Even after reading the section a few times over, I fail to get utility > of such a class. Can someone please explain with better example? > Alan can you please cleanup that section, maybe make it broader and put > the stuff about "SystemExit" elsewhere. > > Thanks a lot in advance. > > With warm regards, > -Payal > -- > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Sun Jun 27 01:45:40 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 26 Jun 2010 19:45:40 -0400 Subject: [Tutor] finally In-Reply-To: <201006270943.01243.steve@pearwood.info> References: <201006251042.35434.steve@pearwood.info> <201006270943.01243.steve@pearwood.info> Message-ID: sorry, my reply to all button goofed up On Sat, Jun 26, 2010 at 7:43 PM, Steven D'Aprano wrote: > Hi Christopher, > > Are you aware you have written directly to me instead of the tutor > mailing list? It's normally considered rude to do so, unless your > message truly is meant to be private. > > > On Sun, 27 Jun 2010 09:24:22 am you wrote: > > what about more complex cleanup code, like saving data or showing a > > error message > > how would the with statement coop with that > > Exactly the same as simple cleanup code. Just be careful not to rely on > things which may not have happened inside the try block. E.g. this > won't work: > > x = something() > try: > y = x - 8 > z = 100/y > finally: > write_data_file(x, y, z) > > This will fail if something() returns 8, because z won't be defined, and > your cleanup block itself will raise a NameError exception. > > > -- > Steven D'Aprano > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 27 01:46:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Jun 2010 09:46:08 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262239.54757.steve@pearwood.info> Message-ID: <201006270946.08643.steve@pearwood.info> On Sun, 27 Jun 2010 04:55:13 am Sithembewena Lloyd Dube wrote: > Richard, I think you may go ahead without trepidation. I am not a > Windows fan at all, I prefer Ubuntu. But I started using Win. 7 at > work about a month ago, and I have to say it hasn't given me cause to > grumble. I don't think Richard is asking whether Windows 7 is worth using. I think he's asking, is it painful to upgrade from Vista to Windows 7. > Of course, a month is hardly sufficient time to have a strong > opinion, but I can tell you that it works just fine. Apart from: having no default email client (what sort of two-bit operating system doesn't have an email client in 2010?); the automatic upgrades that run silently in the background with no easy way to turn them on or off (always fun when your Internet download cap is completely used up TWO DAYS into the month -- especially when you don't know because you can't read the email from your ISP due to not having an email client, and you can't download one because all the available bandwidth is being consumed by the updates); the gratuitous UI changes (am I missing something, or does Internet Explorer no longer have a menubar?); the use of third-party applications like Adobe Acrobat Reader which have become overloaded with *stupid* security vulnerabilities *by design* (years after Microsoft themselves got burnt, time and time again, by allowing the web-browser and mail client to execute random code found on the internet, somebody at Adobe apparently thought it would be a good idea for the PDF reader to do the same thing *facepalms*); and consequently the proliferation of adware and spyware (even the "legitimate" anti-malware companies fill your browser with ad-laden toolbars and try terrifying the user with "your computer is unprotected" warnings -- no wonder the average user can't tell the difference between legitimate anti-malware and trojan horses). On the other hand, it is quite pretty. (Yes, I am speaking from experience. Everything I have mentioned I have seen with my own eyes.) -- Steven D'Aprano From g.nius.ck at gmail.com Sun Jun 27 01:56:25 2010 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 26 Jun 2010 19:56:25 -0400 Subject: [Tutor] socket Message-ID: I'm wondering how to allow one process to communicate with another process. In other words, I want to connect two computers. I've looked up socket but the explanations are too complex. I think I need a 2-way conversation with a expert to understand it. Or even better, point me to a easier module. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 27 02:09:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Jun 2010 10:09:38 +1000 Subject: [Tutor] class questions In-Reply-To: <20100626170516.GA9617@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> Message-ID: <201006271009.38469.steve@pearwood.info> On Sun, 27 Jun 2010 03:05:16 am Payal wrote: > Thanks a lot for the quick answer. Still some doubts below. > > On Sat, Jun 26, 2010 at 11:07:17PM +1000, Steven D'Aprano wrote: > > The old MRO (Method Resolution Order) is broken for classes using > > multiple inheritance with a diamond shape inheritance diagram. Not > > a little bit broken, but horribly, horribly broken. > > > > If you have something like this class hierarchy: > > [...] > > > (only with actual methods, of course) then inheritance with > > old-style classes cannot work correctly in some circumstances. > > Fortunately this > > Can you give any simple example where this simple mro will work > incorrectly? Probably not... it's quite complicated, which is why it's rare. I'll have a think about it and see what I can come up with. > i read, > http://www.python.org/download/releases/2.3/mro/ > butdid not get where mro will fail (ofcourse if python implemented it > corrrectly). I think you have misunderstood, which is probably my fault. It's not that the implementation of the classic MRO was buggy, but that the MRO *itself* does not work as wanted. That's why the fix wasn't "just fix the code", but "change the MRO". > > is rare for old-style classes. But for new-style classes, *all* > > multiple inheritance is diamond-shaped, because all classes inherit > > back to object at the top of the diagram: > > still not getting , how do the new style classes solve the problem > (if there was any). By changing the MRO, new-style classes avoid the problem completely. I know it's hard to understand without seeing an example, sorry. > > Python doesn't have a special "abstract class" type, but it is easy > > to make one with just two lines of boilerplate: > > [...] > > Sorry, I am not getting it. I get, > NameError: global name 'Abstract' is not defined Oops! That was my fault. I changed the name of the class from Abstract to AbstractThing but only changed it in one place. Oh, and I had another bug in it too. Here's the code corrected, and tested this time: class AbstractThing(object): ? ? def __init__(self): ? ? ? ? # Next two lines are boilerplate. ? ? ? ? if type(self) is AbstractThing: ? ? ? ? ? ? raise TypeError("abstract class, you must subclass this") ? ? ? ? # init code for non-abstract Thing classes goes here class MyThing(AbstractThing): pass x = MyThing() # works y = AbstractThing() # fails > Was that a working code? (cos' I do not know what you mean by > boilerplate) "Boilerplate" means the sort of boring code that doesn't actually solve your problem, but just sets things up for the rest of your code to solve your problem. Boilerplate is usually bad because you have to repeat it over and over again, e.g. declarations in languages like Pascal, C or Java. The amount of boilerplate sometimes exceeds the amount of code actually doing something! If you have a class with twenty methods that all start like this: def method(self, other): if other is None: other = something_else # more code here you'll quickly get bored and frustrated writing the if clause. Especially when later on you realise that you mean something_different instead of something_else, and now you have to go back and change it in twenty places instead of one. *That's* boilerplate. > > class DomainError(ValueError): > > """Used for mathematics domain errors.""" > > pass > > Can we say that our own exception classes have only maybe a > doc-string and pass, nothing more? Technically speaking, if you have a doc string, you don't need the pass :) This is a common design pattern. It is creating a new exception that is exactly the same as ValueError but with a different name. But that's not all you can do -- you can add as much, or as little, functionality to the exception subclass as you like. -- Steven D'Aprano From rdmoores at gmail.com Sun Jun 27 03:35:00 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 26 Jun 2010 18:35:00 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262010.34337.steve@pearwood.info> <201006262239.54757.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 15:04, Marc Tompkins wrote: > On Sat, Jun 26, 2010 at 2:30 PM, Richard D. Moores > wrote: >> >> On Sat, Jun 26, 2010 at 13:39, Sithembewena Lloyd Dube >> wrote: >> > Hi Dick, >> > >> > In that case, perhaps you could externally back up all your important >> > stuff >> > and then format your hard disk. That way, any drivers etc intended for >> > Windows Vista will be wiped off, and you can then perform a clean >> > installation from your disk. Now, as far as upgrade disks go, I do not >> > know >> > whether it will work as a "clean installation" disk, or whether it is >> > only >> > meant for use on an existing windows installation (hence the name >> > "upgrade"). You might want to check that out first. >> >> I don't believe the disk I have will enable a clean installation. > > I'm pretty sure it will: > http://www.winsupersite.com/win7/clean_install_upgrade_media.asp > http://www.mydigitallife.info/2009/10/27/clean-install-windows-7-with-upgrade-media-and-product-key-on-formatted-or-empty-blank-hard-drive/ > > The upshot of both those articles is: boot from the upgrade disk as if it > were a normal Full Install disk; when it asks for the Windows key, leave it > blank.? Don't enter the key until after the installation is complete, when > you want to activate. > > Since you CAN use that disk as a clean install, I definitely recommend that > you DO.? When I upgraded my laptop to Windows 7, I bought myself a new 500GB > hard drive for the purpose.? $60 and five minutes with a small screwdriver > brought me a huge dividend in peace of mind. I have to get some sleep right now, but I'll give your suggestion serious consideration when I get up. Thanks very much, Marc. Dick From marc.tompkins at gmail.com Sun Jun 27 09:21:57 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 27 Jun 2010 00:21:57 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006270946.08643.steve@pearwood.info> References: <201006262239.54757.steve@pearwood.info> <201006270946.08643.steve@pearwood.info> Message-ID: On Sat, Jun 26, 2010 at 4:46 PM, Steven D'Aprano wrote: > Apart from: > The OP was asking about upgrading from Vista to 7, so let me answer your objections here... having no default email client (what sort of two-bit operating system > doesn't have an email client in 2010?); > Jesus, you _miss_ Outlook Express? Seriously: the new default is webmail. Like it, don't like it, but it's really not as if you can't get your mail. > the automatic upgrades that run silently in the background with no easy > way to turn them on or off Just like XP and Vista, you're asked during installation whether you want to allow or disallow automatic updates. If you breeze past that question, then - just like in XP and Vista - you can right-click on the little icon that appears in your system tray (oops, I mean "notification area.") True, Windows 7 is proactive about hiding stuff in the tray... but it does still appear there. A more legitimate gripe is that, after downloading those updates, Windows insists on applying them when you shut down the computer. If you're in a hurry, that can be a PITA. > (always fun when your Internet download cap > is completely used up TWO DAYS into the month -- especially when you > don't know because you can't read the email from your ISP due to not > having an email client, To paraphrase, "what sort of two-bit ISP doesn't have a webmail site in 2010?" the gratuitous UI changes (am I missing something, or does Internet > Explorer no longer have a menubar?); > That's IE, not Windows. Windows 7 comes with IE 8; Vista came with IE 7; XP came with IE 6. I don't care for the look myself, but then I never use IE if I can avoid it (Firefox for mail and searching, 'cause I love me some plugins; Chrome for everything else, 'cause it's fast as hell. IE when I'm on a client machine and there's nothing better.) IE 8 is being rolled out to all versions of Windows in any case, so that's not a reason not to upgrade - unless you were planning to turn off Windows Update in Vista, which is a bad idea for security reasons... the use of third-party applications like Adobe Acrobat Reader which have > become overloaded with *stupid* security vulnerabilities *by design* > (years after Microsoft themselves got burnt, time and time again, by > allowing the web-browser and mail client to execute random code found > on the internet, somebody at Adobe apparently thought it would be a > good idea for the PDF reader to do the same thing *facepalms*); and > Microsoft doesn't provide a PDF reader of its own - I'm not sure, but I suspect that's for legal reasons - so whatever PDF reader you use, it HAS to be third-party. Why Adobe? Probably because it's called "_Adobe_ Acrobat?" Now, I hate Adobe products for the same reasons you mentioned, so I use and recommend the free Foxit Reader (www.foxitsoftware.com). But that was the same under XP and Vista. > consequently the proliferation of adware and spyware (even > the "legitimate" anti-malware companies fill your browser with ad-laden > toolbars and try terrifying the user with "your computer is > unprotected" warnings -- no wonder the average user can't tell the > difference between legitimate anti-malware and trojan horses). > Again, not new in 7 - and, as a matter of fact, possibly somewhat better than in Vista. > On the other hand, it is quite pretty. > Screw pretty. Pretty don't pay the rent. First thing I do on any machine I get my hands on is turn off the $%^&* Aero Glass - why would I take that kind of performance hit for the dubious pleasure of a translucent titlebar? But guess what? MS introduced that piece of idiotism in - wait for it - Vista. My reasons FOR upgrading: - Better UAC. UAC is never going to feel natural to users (like me - I freely admit it) who came up from DOS, and are stuck in a single-user mindset. Users raised on *nixes, on the other hand, find UAC to be a laughable baby step on the way to a real least-privilege security model. That said, 7 does a much more natural job (than Vista) of asking for elevation only when needed, and staying out of the way most of the rest of the time. - Faster sleep/hibernation and wakeup. I have no idea what they did under the covers, but on my laptop under Vista 64-bit, it took a minute or so to hibernate, and 30 seconds or so to wake up. 7 takes 30 seconds or so to hibernate, and 15 seconds to wake up. Not astronomical, but coupled with the next point, it's HUGE. - Better wireless networking. Coming out of sleep or hibernation, it used to take up to a minute and a half to connect to a known wireless network (in other words, a network I'd previously connected to and saved settings for.) Now, I'm generally connected even before I can see the desktop - 3 to 5 seconds, maybe. I carry my laptop everywhere, and connect to wireless networks at my clients (and Starbucks!) all day long, so this is a MAJOR deal for me. - Seriously improved multi-monitor support. I've loved using dual monitors since XP, but it's always been a pain. Windows would arbitrarily decide that the external monitor was primary, or refuse to connect, or insist on duplicating the desktop on both monitors even though I told it to extend... In 7, it just works. I plug into external monitors at home and in several clients' offices, and 7 remembers the settings for each location (at home the second monitor is 1024x768, sitting to the left and an inch lower; at CCMG it's 1400xsomething, to the right and up a couple of inches, etc.) If I plug in the external monitor before I wake up my computer, I don't even have to press any keys to make it work. (If I forget, it's Fn-F4 on my machine; might be something else on a different keyboard.) (Mac people, I'm sure you'll say that Apple has been getting this right for years. All I know is, Microsoft didn't until now.) There are some downsides: the afore-mentioned insistence on applying updates at shutdown (one reason why I don't shut down very often); legacy HP drivers have been removed from the distribution disk (this one's a biggie for me, 'cause I do lots of installs, and I like to use the LaserJet 4 or 5 drivers for Brother and Xerox printers); some other things that will no doubt come to mind. Would I pay to upgrade an older machine from Vista to 7? No; I'd just wait till it was time to replace it, and see what comes with the new one. Would I upgrade a relatively new machine if I had a free upgrade disk? In a red-hot minute. (But, as previously stated, I wouldn't do an in-place upgrade.) By the way - I love me some Ubuntu, and I dual-boot to it. Unfortunately, however, for me Linux is like pretty: it don't pay the rent. My clients use Windows, and (most of them) expensive vertical software that runs on Windows, and MS Office. So I use Windows most of the time. And I can honestly say that, if ya gotta use Windows, 7 (64-bit!) is your best bet. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Sun Jun 27 09:53:43 2010 From: modulok at gmail.com (Modulok) Date: Sun, 27 Jun 2010 01:53:43 -0600 Subject: [Tutor] Advice on math In-Reply-To: References: Message-ID: >> Hello, I've enjoying learning python for the first few years, and >> appreciate all the help I have received from this list. I had some >> interest in programming and am very glad to have made python my choice >> of programming language. Since I didn't go to college for computer >> studies, I feel my math is kind of rusty in some areas, and looks like >> improving/regaining math skills would help a lot in programming, >> logic, algorithms, etc. >> Right now I think I need a better understanding of logarithm, arrays >> (matrixes), and even probability. What links would you all recommend >> that would be useful for me to learn these things in a newbie-friendly >> way? >> >> >> > If you want to code+learn, nothing beats ProjectEuler ( > http://projecteuler.net/ ). However I assume you have basic understanding of > maths. Not to hijack the thread, but that's awesome! Only when you solve the problems and then read the forum thread, do you realize how crude your own solutions are, compared to some very clever fellows. Far better than a crossword to keep things stimulated. -Modulok- From hugo.yoshi at gmail.com Sun Jun 27 13:27:37 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Jun 2010 13:27:37 +0200 Subject: [Tutor] class questions In-Reply-To: <201006271009.38469.steve@pearwood.info> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> Message-ID: On Sun, Jun 27, 2010 at 2:09 AM, Steven D'Aprano wrote: > On Sun, 27 Jun 2010 03:05:16 am Payal wrote: >> >> Can you give any simple example where this simple mro will work >> incorrectly? > > Probably not... it's quite complicated, which is why it's rare. I'll > have a think about it and see what I can come up with. > Here's my attempt. Consider this simple Diamond hierarchy: class A: def x(self): return "in A" class B(A): pass class C(A): def x(self): return "in C" class D(B, C): pass A / \ / \ B C \ / \ / D Now, with this diagram the following code probably doesn't do what you expect: >>> obj = D() >>> obj.x() 'in A' D inherits from C, which overrides the x method. But this is seemingly completely ignored by python, which produces the A.x method! So why does this happen? well, the old MRO uses a simple depth-first, left-to-right search. This means that to find a method, python first looks into the leftmost parent, then its leftmost parent, et cetera et cetera. For our diamond, that means this MRO: D, B, A, C, A so, when you try to access D.x, it will look first in D (not found), B (not found), then A, producing the A.x method. And this probably isn't what you want (we inherited from C for a reason, you know). For new style classes, the MRO is actually D, B, C, A. That produces the correct results. The algorithm is a little complicated, and if you would like to know, the link you posted earlier has all the details. Hugo From payal-python at scriptkitchen.com Sun Jun 27 16:13:52 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 27 Jun 2010 07:13:52 -0700 Subject: [Tutor] class questions In-Reply-To: References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> Message-ID: <20100627141352.GA20643@scriptkitchen.com> Hi Hugo, On Sun, Jun 27, 2010 at 01:27:37PM +0200, Hugo Arts wrote: > Here's my attempt. Consider this simple Diamond hierarchy: [...] > Now, with this diagram the following code probably doesn't do what you expect: Actually, it does what is expected. The old mro specifically says, bottom-top, left-right. So we expected D-B-A-C-A. Steven says in some cases even this simple logic of bottom-top, left-right search will not work. As he says, a simple example of it failing is diffclt to write, so meanwhile I will take his word for it. Thanks for the help. With warm regards, -Payal -- From payal-python at scriptkitchen.com Sun Jun 27 16:19:01 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 27 Jun 2010 07:19:01 -0700 Subject: [Tutor] class questions In-Reply-To: <201006271009.38469.steve@pearwood.info> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> Message-ID: <20100627141901.GB20643@scriptkitchen.com> Hi Steven, Thanks a lot for patiently explaining the concepts. I uderstood most of it. With warm regards, -Payal -- On Sun, Jun 27, 2010 at 10:09:38AM +1000, Steven D'Aprano wrote: > Probably not... it's quite complicated, which is why it's rare. I'll > have a think about it and see what I can come up with. From alan.gauld at btinternet.com Sun Jun 27 16:26:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Jun 2010 15:26:19 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006262239.54757.steve@pearwood.info> <201006270946.08643.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > having no default email client (what sort of two-bit operating > system > doesn't have an email client in 2010?); To be fair to MS - and it pains me to do so - they have been beat up so much by the lawyers that its hardlly surprising. After all they have been forced to remove the browser from the OS in Europe (and elsewhere?). Why not the email client too? After all, Linux doesn't tecchnically have a mail client (unless you count command line mail), it's the distros that add that. > the automatic upgrades that run silently in the background with no > easy > way to turn them on or off Yes I really hate that! > the gratuitous UI changes (am I missing something, or does Internet > Explorer no longer have a menubar?); None of the new MS applications do, the menu bar has been merged into the new look toolbar. Thus making something small and unobtrusive large and extremely obtrusive and requiring a relearning of the whole command structure! I really don't like the new MS UI thing, even after 6 montrhs of use it still drives me nuts! (I use Win7 on my laptop at work) > the use of third-party applications like Adobe Acrobat Reader which > have > become overloaded with *stupid* security vulnerabilities *by design* But that applies to all OS that Reader runs on doesn't it? Can't blame Windows 7 for that. > consequently the proliferation of adware and spyware (even Yep, agree with this too. > On the other hand, it is quite pretty. Hmm, I'm stlll not sure about that... But then, I srtill run Windows XP in Classic mode with Windows95 style menu and start button etc. Alan G. From payal-python at scriptkitchen.com Sun Jun 27 16:39:28 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 27 Jun 2010 07:39:28 -0700 Subject: [Tutor] class questions In-Reply-To: <201006262241.59867.eike.welk@gmx.net> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006262241.59867.eike.welk@gmx.net> Message-ID: <20100627143928.GC20643@scriptkitchen.com> Thanks a lot Eike for the code snippet. I got the idea now. With warm regards, -Payal -- On Sat, Jun 26, 2010 at 10:41:59PM +0200, Eike Welk wrote: > Hello Payal! > > On Saturday June 26 2010 19:05:16 Payal wrote: > > Can we say that our own exception classes have only maybe a doc-string > > and pass, nothing more? > > No, you let the exception transport the information that you need for handling > the error. This is an exception that I use to transport user visible error > messages in a compiler, that I write as a hobby: > > > class UserException(Exception): > '''Exception that transports user visible error messages.''' > def __init__(self, message, loc=None, errno=None): > Exception.__init__(self) > self.msg = message > self.loc = loc > self.errno = errno > > def __str__(self): > if self.errno is None: > num_str = '' > else: > num_str = '(#%s) ' % str(self.errno) > return 'Error! ' + num_str + self.msg + '\n' + str(self.loc) + '\n' > > def __repr__(self): > return self.__class__.__name__ + str((self.msg, self.loc, > self.errno)) > > It contains: > self.msg : The error message > self.loc : An object encoding the location of the error in the program's > text. Together with the file name and the text. > self.errno : An integer to identify the error, for the test framework. > > That said; the expression's type and the error message are often sufficient to > handle the error. > > > Eike. From alan.gauld at btinternet.com Sun Jun 27 16:41:12 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Jun 2010 15:41:12 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006262239.54757.steve@pearwood.info><201006270946.08643.steve@pearwood.info> Message-ID: "Marc Tompkins" wrote > having no default email client (what sort of two-bit operating > system >> doesn't have an email client in 2010?); >> > Jesus, you _miss_ Outlook Express? Seriously: the new default is > webmail. > Like it, don't like it, but it's really not as if you can't get your > mail. I will miss OE. I actually quite like it, its simple but has all the bits I need for both email and newrgroups. I tried thunderbird and use it on my Linux box but on windows I usually revert to OE. And its lots better than webmail which is only useful for occasional browsing. But I get around 200 plus emails a day (and sometimes the same again in news messages) and trying to manage that on webmail is a nightmare - and you can't read it while offline. I really need an offline mail client. > Just like XP and Vista, you're asked during installation whether you > want to > allow or disallow automatic updates. If you breeze past that > question, then > - just like in XP and Vista - you can right-click on the little icon > that > appears in your system tray (oops, I mean "notification area.") OOh. I've never noticed the icon - what does it look like? I didn't do the install so had no say in the decision for work, but for my home PC I'd much rather decide if/when I do "upgrades" - I've had too mamy Windows upgrades kill my PC to the point of needing rebuiilds! > To paraphrase, "what sort of two-bit ISP doesn't have a webmail site > in > 2010?" But webmail is no good if you've used up your bandwidth. A background client might just have received the warning before the quota went bang... > - Better wireless networking. Coming out of sleep or hibernation, > it used > to take up to a minute and a half to connect to a known wireless > network I'll need to check that - I've just gotten used to going for a coffee when I boot up - it usually takes me around 5 minutes for everything to get started so I've never noticed the WiFi changes. > - Seriously improved multi-monitor support. I've loved using dual > monitors I only user this when doing powerpoint presentations but I'll need to take a closer look. Thanks for sharing your comments, even if this thread is seriously off topic! Alan G. From alan.gauld at btinternet.com Sun Jun 27 16:46:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Jun 2010 15:46:20 +0100 Subject: [Tutor] socket References: Message-ID: "Christopher King" wrote > process. In other words, I want to connect two computers. I've > looked up > socket but the explanations are too complex. I think I need a 2-way > conversation with a expert to understand it. Or even better, point > me to a > easier module. You can read the networking topic in my tutorial;(V2 only) and see a simple explanation with examples. It might be helpful to read the previous two topics as well as a general background to communicating between processes. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kwehaibi at yahoo.com Sun Jun 27 18:15:53 2010 From: kwehaibi at yahoo.com (Khawla Al-Wehaibi) Date: Sun, 27 Jun 2010 16:15:53 +0000 (GMT) Subject: [Tutor] retrieve URLs and text from web pages Message-ID: <85912.16789.qm@web23606.mail.ird.yahoo.com> Hi, I?m new to programming. I?m currently learning python to write a web crawler to extract all text from a web page, in addition to, crawling to further URLs and collecting the text there. The idea is to place all the extracted text in a .txt file with each word in a single line. So the text has to be tokenized. All punctuation marks, duplicate words and non-stop words have to be removed. The program should crawl the web to a certain depth and collect the URLs and text from each depth (level). I decided to choose a depth of 3. I divided the code to two parts. Part one to collect the URLs and part two to extract the text. Here is my problem: 1.??? The program is extremely slow. 2.??? I'm not sure if it functions properly. 3.??? Is there a better way to extract text? 4.??? Are there any available modules to help clean the text i.e. removing duplicates, non-stop words ... 5.??? Any suggestions or feedback is appreciated. (Please Note: the majority of the code (the first part) is written by ?James Mills?. I found the code online and it looks helpful so I used it. I just modified it and added my code to it) Thanks, Kal import sys import urllib2 import urlparse from BeautifulSoup import BeautifulSoup,NavigableString __version__ = "0.1" __copyright__ = "CopyRight (C) 2008 by James Mills" __license__ = "GPL" __author__ = "James Mills" __author_email__ = "James Mills, James dot Mills st dotred dot com dot au" USAGE = "%prog [options] " VERSION = "%prog v" + __version__ AGENT = "%s/%s" % (__name__, __version__) def encodeHTML(s=""): ??? """encodeHTML(s) -> str ??? Encode HTML special characters from their ASCII form to ??? HTML entities. ??? """ ??? return s.replace("&", "&") \ ??????????? .replace("<", "<") \ ??????????? .replace(">", ">") \ ??????????? .replace("\"", """) \ ??????????? .replace("'", "'") \ ??????????? .replace("--", "&mdash") class Fetcher(object): ??? def __init__(self, url): ??????? self.url = url ??????? self.urls = [] ??? def __contains__(self, x): ??????? return x in self.urls ??? def __getitem__(self, x): ??????? return self.urls[x] ??? def _addHeaders(self, request): ??????? request.add_header("User-Agent", AGENT) ??? def open(self): ??????? url = self.url ??????? #print "\nFollowing %s" % url ??????? try: ??????????? request = urllib2.Request(url) ??????????? handle = urllib2.build_opener() ??????? except IOError: ??????????? return None ??????? return (request, handle) ??? def fetch(self): ??????? request, handle = self.open() ??????? self._addHeaders(request) ??????? if handle: ??????????? soup = BeautifulSoup() ??????????? try: ??????????????? content = unicode(handle.open(request).read(), errors="ignore") ??????????????? soup.feed(content) ??????????????? #soup = BeautifulSoup(content) ??????????????? tags = soup('a') ??????????? except urllib2.HTTPError, error: ??????????????? if error.code == 404: ??????????????????? print >> sys.stderr, "ERROR: %s -> %s" % (error, error.url) ??????????????? else: ??????????????????? print >> sys.stderr, "ERROR: %s" % error ??????????????? tags = [] ??????????? except urllib2.URLError, error: ??????????????? print >> sys.stderr, "ERROR: %s" % error ??????????????? tags = [] ??????????? for tag in tags: ??????????????? try: ??????????????????? href = tag["href"] ??????????????????? if href is not None: ??????????????????????? url = urlparse.urljoin(self.url, encodeHTML(href)) ??????????????????????? if url not in self: ??????????????????????????? #print " Found: %s" % url ??????????????????????????? self.urls.append(url) ??????????????? except KeyError: ??????????????????? pass ################################################################################ # I created 3 lists (root, level2 and level3).???????????????????????????????? # # Each list saves the URLs of that level i.e. depth. I choose to create 3????? # # lists so I can have the flexibility of testing the text in each level. Also, # # the 3 lists can be easily combined into one list.??????????????????????????? # ################################################################################ # Level1: root = Fetcher('http://www.wantasimplewebsite.co.uk/index.html') root.fetch() for url in root: ??? if url not in root: # Avoid duplicate links ?????? root.append(url) ?????? print "\nRoot URLs are:" for i, url in enumerate(root): ?? print "%d. %s" % (i+1, url) # Level2: level2 = [] for url in root: # Traverse every element(i.e URL) in root and fetch the URLs from it ??? temp = Fetcher(url) ??? temp.fetch() ??? for url in temp: ??????? if url not in level2: # Avoid duplicate links ?????????? level2.append(url)?????? ?? print "\nLevel2 URLs are:" for i, url in enumerate(level2): ?? print "%d. %s" % (i+1, url) ? # Level3: level3 = [] for url in level2: # Traverse every element(i.e URL) in level2 and fetch the URLs from it ??? temp = Fetcher(url) ??? temp.fetch() ??? for url in temp: ??????? if url not in level3: # Avoid duplicate links ?????????? level3.append(url) print "\nLevel3 URLs are:" for i, url in enumerate(level3): ?? print "%d. %s" % (i+1, url) # 1. Traverse every link in the lists and extract its web page content. # 2. Tokenize Text. # 3. Remove stop-words (i.e. and, but, to...) # 4. Remove duplicates # 5. What about stemming? # 6. Check the spelling. # 7. Save the result in a file html = urllib2.urlopen('http://www.wantasimplewebsite.co.uk/index.html').read() soup = BeautifulSoup(html) def printText(tags): ??? for tag in tags: ??? ??? if tag.__class__ == NavigableString: ??? ??? ??? print tag, ??? ??? else: ??? ??? ??? printText(tag) printText(soup.findAll("body")) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Jun 27 18:32:40 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Jun 2010 18:32:40 +0200 Subject: [Tutor] class questions In-Reply-To: <20100627141352.GA20643@scriptkitchen.com> References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> <20100627141352.GA20643@scriptkitchen.com> Message-ID: On Sun, Jun 27, 2010 at 4:13 PM, Payal wrote: > Hi Hugo, > > On Sun, Jun 27, 2010 at 01:27:37PM +0200, Hugo Arts wrote: >> Here's my attempt. Consider this simple Diamond hierarchy: > [...] >> Now, with this diagram the following code probably doesn't do what you expect: > > Actually, it does what is expected. The old mro specifically says, > bottom-top, left-right. So we expected D-B-A-C-A. > Steven says in some cases even this simple logic of bottom-top, > left-right search will not work. As he says, a simple example of it > failing is diffclt to write, so meanwhile I will take his word for it. > The problem of the MRO isn't that it doesn't work, it's that it causes behavior that is unintuitive. In my example, We would expect D.x to be equal to C.x (since D inherits from C, and C overrides the x method). However, this is not the case. This is what the problem is with the old MRO system, not so much that it doesn't work at all, but the results aren't consistent with what you'd expect from multiple inheritance. I just found this link, where Guido explains why he changed the MRO system for new-style classes. He uses the same example I do. http://www.python.org/download/releases/2.2.2/descrintro/#mro Hugo From payal-python at scriptkitchen.com Sun Jun 27 18:47:24 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 27 Jun 2010 09:47:24 -0700 Subject: [Tutor] capturing error msg in exception Message-ID: <20100627164724.GA22292@scriptkitchen.com> Hi, Again a few queries regarding exceptions, a. What is the difference between, except ZeroDivisionError as e: print 'Msg : ' , e except ZeroDivisionError ,e: print 'Msg : ' , e Both show, Msg : integer division or modulo by zero b. What is portable and correct way of writing, except (NameError, ZeroDivisionError) as e: print 'Msg : ' , e c. What is the correct Python of writing, except as e: print 'Msg : ' , e # Capturing all exceptions Thanks a lot for the help in advance. With warm regards, -Payal -- p.s. I am always confused where does one put the "?" when I am framing the questions like I have done above (a, b and c)? This is completely OT query for native english speaking people :-) From anand.shashwat at gmail.com Sun Jun 27 18:47:40 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 27 Jun 2010 22:17:40 +0530 Subject: [Tutor] class questions In-Reply-To: References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> <20100627141352.GA20643@scriptkitchen.com> Message-ID: > The problem of the MRO isn't that it doesn't work, it's that it causes > behavior that is unintuitive. In my example, We would expect D.x to be > equal to C.x (since D inherits from C, and C overrides the x method). > However, this is not the case. This is what the problem is with the > old MRO system, not so much that it doesn't work at all, but the > results aren't consistent with what you'd expect from multiple > inheritance. > > I tried your example in python2.6 >>> class A: ... def x(self): return "in A" ... >>> class B(A): pass ... >>> class C(A): ... def x(self): return "in C" ... >>> class D(B, C): pass ... >>> o = D() >>> o.x() 'in A' If MRO was in python2.3, the output of o.x() should be 'in C'. It works fine on 3.2alpha though. > I just found this link, where Guido explains why he changed the MRO > system for new-style classes. He uses the same example I do. > > http://www.python.org/download/releases/2.2.2/descrintro/#mro > > This was the only useful link I found upon googling. Thanks for your effort though. -------------- next part -------------- An HTML attachment was scrubbed... URL: From payal-python at scriptkitchen.com Sun Jun 27 18:57:52 2010 From: payal-python at scriptkitchen.com (Payal) Date: Sun, 27 Jun 2010 09:57:52 -0700 Subject: [Tutor] statements vs. expression and types Message-ID: <20100627165752.GB22292@scriptkitchen.com> Hello, Please forgive for such a silly questions. I have never taken a course on computers so am rough with some of basic technical terminology. a. I read in a book that "lambdas are expressions ... so they can go where functions are not allowed". What are expressions and what are statements? A simple example of both in Python will suffice. b. I read on web that Python has in new releases done "unifications of types and classes". I know what classes are, what are types in simple language. Again please excuse for simple questions and thanks a lot in advance. With warm regards, -Payal -- From rdmoores at gmail.com Sun Jun 27 19:07:47 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 27 Jun 2010 10:07:47 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262239.54757.steve@pearwood.info> <201006270946.08643.steve@pearwood.info> Message-ID: On Sun, Jun 27, 2010 at 07:41, Alan Gauld wrote: > "Marc Tompkins" wrote > I will miss OE. I actually quite like it, its simple but has all the bits > I need for both email and newrgroups. I tried thunderbird and use it > on my Linux box but on windows I usually revert to OE. > > And its lots better than webmail which is only useful for occasional > browsing. But I get around 200 plus emails a day (and sometimes the > same again in news messages) and trying to manage that on webmail > is a nightmare - and you can't read it while offline. I really need an > offline mail client. I get 200-300 emails per weekday, and Gmail handles them with aplomb. I have over 300 labels (it's now, finally, possible to nest them). (Tip: use [(From:address) OR (From:me AND ((To: OR Cc:)address))] -- delete the square brackets -- in the "Has the words" textbox when making a filter that will apply to all mail from yourself to: or cc'd to an address OR from an address). Labels can be nested and color coded. Be sure to check out the numerous other features, including the ones on the "Labs" tab. BTW I used Eudora for a decade, and also OE because I had to teach it to my wife. A "feature" very important to me is that with Gmail, my mail is just always THERE, with no need to download it -- and often INSTANTLY there because there are so many other Gmail users. I'll stop my praise of Gmail here because this is an OT of an OT thread :) . Dick From adam.jtm30 at gmail.com Sun Jun 27 19:12:39 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 27 Jun 2010 18:12:39 +0100 Subject: [Tutor] capturing error msg in exception In-Reply-To: <20100627164724.GA22292@scriptkitchen.com> References: <20100627164724.GA22292@scriptkitchen.com> Message-ID: On 27 June 2010 17:47, Payal wrote: > Hi, > Again a few queries regarding exceptions, > > a. What is the difference between, > > except ZeroDivisionError as e: print 'Msg : ' , e > except ZeroDivisionError ,e: print 'Msg : ' , e > > Both show, > Msg : integer division or modulo by zero > > b. What is portable and correct way of writing, > > except (NameError, ZeroDivisionError) as e: print 'Msg : ' , e > > c. What is the correct Python of writing, > except as e: print 'Msg : ' , e # Capturing all exceptions > > Thanks a lot for the help in advance. > With warm regards, > -Payal > -- > > p.s. I am always confused where does one put the "?" when I am framing the > questions like I have done above (a, b and c)? > This is completely OT query for native english speaking people :-) > > I think the 'as' syntax is only available in Python 3.x Question marks go at the end of the sentence where you would normally put a full stop if it wasn't a question. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sun Jun 27 19:22:23 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 27 Jun 2010 10:22:23 -0700 Subject: [Tutor] capturing error msg in exception In-Reply-To: References: <20100627164724.GA22292@scriptkitchen.com> Message-ID: <4C2788CF.105@alchemy.com> On 27-Jun-10 10:12, Adam Bark wrote: > On 27 June 2010 17:47, Payal c. What is the correct Python of writing, > except as e: print 'Msg : ' , e # Capturing all exceptions Since exceptions are (should be?) subclasses of Exception, you can do: except Exception as e: > I think the 'as' syntax is only available in Python 3.x It's in Python 2 as well. At least I see it in 2.6.4, probably earlier too (but I'm not sure ATM how early it showed up). From adam.jtm30 at gmail.com Sun Jun 27 19:29:41 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 27 Jun 2010 18:29:41 +0100 Subject: [Tutor] capturing error msg in exception In-Reply-To: <4C2788CF.105@alchemy.com> References: <20100627164724.GA22292@scriptkitchen.com> <4C2788CF.105@alchemy.com> Message-ID: On 27 June 2010 18:22, Steve Willoughby wrote: > On 27-Jun-10 10:12, Adam Bark wrote: > >> On 27 June 2010 17:47, Payal > > > c. What is the correct Python of writing, >> except as e: print 'Msg : ' , e # Capturing all exceptions >> > > Since exceptions are (should be?) subclasses of Exception, you can do: > > except Exception as e: > > > I think the 'as' syntax is only available in Python 3.x >> > > It's in Python 2 as well. At least I see it in 2.6.4, probably earlier too > (but I'm not sure ATM how early it showed up). > > Ah yeah sorry I got confused, it's the comma version that is gone from 3.x isn't it? I assume that means 'as' is the preferred syntax. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Sun Jun 27 19:57:43 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 27 Jun 2010 10:57:43 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006262239.54757.steve@pearwood.info> <201006270946.08643.steve@pearwood.info> Message-ID: On Sun, Jun 27, 2010 at 7:41 AM, Alan Gauld wrote: > "Marc Tompkins" wrote > > having no default email client (what sort of two-bit operating system >> >>> doesn't have an email client in 2010?); >>> >>> Jesus, you _miss_ Outlook Express? Seriously: the new default is >> webmail. >> Like it, don't like it, but it's really not as if you can't get your mail. >> > > I will miss OE. I actually quite like it, its simple but has all the bits > I need for both email and newrgroups. I tried thunderbird and use it > on my Linux box but on windows I usually revert to OE. > I always hated OE, but I suppose it does have its uses. Backing up OE was always problematic... > And its lots better than webmail which is only useful for occasional > browsing. But I get around 200 plus emails a day (and sometimes the > same again in news messages) and trying to manage that on webmail > is a nightmare - and you can't read it while offline. I really need an > offline mail client. As Richard mentioned and I will second, GMail handles that volume easily; Gears enables offline reading, and if you've drunk the Kool-Aid like I have, integration with Android is seamless. Also it's instantly portable from machine to machine. In any case, I only meant to whole-heartedly endorse upgrading from Vista to 7, and dismiss the loss of OE as a reason not to. Embracing the GMail way appears to be another one of those dreaded religious topics - I certainly can feel myself morphing into a ranting fanatic... > Just like XP and Vista, you're asked during installation whether you want >> to >> allow or disallow automatic updates. If you breeze past that question, >> then >> - just like in XP and Vista - you can right-click on the little icon that >> appears in your system tray (oops, I mean "notification area.") >> > > OOh. I've never noticed the icon - what does it look like? I didn't > do the install so had no say in the decision for work, but for my > home PC I'd much rather decide if/when I do "upgrades" - I've had > too mamy Windows upgrades kill my PC to the point of needing > rebuiilds! It looks like a rectangular pane of glass (a Window, maybe?) with an orange halo orbiting it. I don't see it on my machine at the moment (because I - wait for it - turned off automatic updates when I installed), so I'm a little fuzzy on whether it's a left-click, double-click, or right-click that gets you the option to turn off the auto updates. Regardless, here's a more direct way: Control Panel\System and Security\Windows Update\Change settings - Better wireless networking. Coming out of sleep or hibernation, it used > to take up to a minute and a half to connect to a known wireless network > I'll need to check that - I've just gotten used to going for a coffee when I > boot up - it usually takes me around 5 minutes for everything to get > started so I've never noticed the WiFi changes. I was driving on the freeway a while back, talking to my sister on the phone (hands-free!) when she mentioned that her computer was giving her trouble. I exited and pulled into a Starbucks I'd used before (so my machine already knew "attwifi7" or whatever it is). I opened my laptop, signed in, and used Chrome to sign into the AT&T captive portal; within less than a minute of my butt hitting the banquette I was in Copilot. She and I commiserated about the good old days when at least I could have ordered my coffee before I had to get down to work... 8-) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Jun 27 21:30:46 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Jun 2010 21:30:46 +0200 Subject: [Tutor] class questions In-Reply-To: References: <20100626121745.GA6916@scriptkitchen.com> <201006262307.17364.steve@pearwood.info> <20100626170516.GA9617@scriptkitchen.com> <201006271009.38469.steve@pearwood.info> <20100627141352.GA20643@scriptkitchen.com> Message-ID: On Sun, Jun 27, 2010 at 6:47 PM, Shashwat Anand wrote: > >> >> The problem of the MRO isn't that it doesn't work, it's that it causes >> behavior that is unintuitive. In my example, We would expect D.x to be >> equal to C.x (since D inherits from C, and C overrides the x method). >> However, this is not the case. This is what the problem is with the >> old MRO system, not so much that it doesn't work at all, but the >> results aren't consistent with what you'd expect from multiple >> inheritance. >> > > I tried your example in python2.6 >>>> class A: > ... ? ?def x(self): return "in A" > ... >>>> class B(A): pass > ... >>>> class C(A): > ... ? ?def x(self): return "in C" > ... >>>> class D(B, C): pass > ... >>>> o = D() >>>> o.x() > 'in A' > If MRO was in python2.3, the output of o.x() should be 'in C'. It works fine > on 3.2alpha though. > You forgot that the example as is still uses the old MRO, even in 2.3. This is because these classes are still classic-style classes. To use the new MRO you will have to use new-style classes (A must inherit from object). In 3.x it will of course work fine, since everything without explicit inheritance inherits from object. Hugo From hugo.yoshi at gmail.com Sun Jun 27 21:42:53 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Jun 2010 21:42:53 +0200 Subject: [Tutor] statements vs. expression and types In-Reply-To: <20100627165752.GB22292@scriptkitchen.com> References: <20100627165752.GB22292@scriptkitchen.com> Message-ID: On Sun, Jun 27, 2010 at 6:57 PM, Payal wrote: > Hello, > Please forgive for such a silly questions. I have never taken a course on > computers so am rough with some of basic technical terminology. > > a. I read in a book that "lambdas are expressions ... so they can go > where functions are not allowed". What are expressions and what are > statements? A simple example of both in Python will suffice. > an expression is anything that yields a value. Simple expressions are 1 1 + 1 a [1, 2, 3] True and False lambda: 5 but anything that has a value is an expression. Expressions can be on the right side of an assignment statement. A statement is kind of the opposite. It does not have a value. Examples of statements: return 5 def x(): pass if True: sys.exit() while x < 4: pass > b. I read on web that Python has in new releases done "unifications of > types and classes". I know what classes are, what are types in simple > language. > a 'type,' in python before 2.2, was simply any of the builtin types, that is, int, str, list, dict, and so on. The unification that happened in 2.2 means that there are no more differences between a builtin 'type' and a user-defined 'class.' Nowadays a type is just any instance of the type class. Hugo From petkovas at dir.bg Mon Jun 28 00:20:01 2010 From: petkovas at dir.bg (petkovas at dir.bg) Date: Mon, 28 Jun 2010 00:20:01 +0200 Subject: [Tutor] TypeError when io.open is used Message-ID: > Can you send the full error text please? I'm not sure which > is line 55 and Python normally displays the faulty line as > part of the error trace. > > As it is I can't see any reason for it to fail but I'd like to > be sure I'm looking at the right place! > > Also is there any reason why you explicitly call io.open() > instead of just using the built-in open() directly? I know > they are the same function but its quite unusual to use > the io version explicitly... > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ The full error message is: Traceback : File "insert_into_db_v9.py", line 55, in WHERE testtable_n = %s""", data1, str(os.path.splitext(file)[0])) TypeError: an integer is required And i would want to add that str() is not the problem. I have tried without it and the problem persisted. I have tried the following, too: from pg8000 import DBAPI import os import os.path import sys # !!! that is test data. It must be changed conn=DBAPI.connect(host="localhost", database="postgres", user="postgres", password="test") #conn.cursor will return a cursor oject, you can use this cursor to perform queries cursor = conn.cursor() file = open( "C:\\Blender_Library\\BlenderLib\\objectLib\\Faqns\\Osaka2\\faqns_osaka_2.jpg", "rb" ) data1 = DBAPI.Binary(file.read()) data2 = 'faqns_osaka_2' # execute our Query cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2) sys.stdout.flush() # Save (commit) the changes conn.commit() # We can also close the cursor if we are done with it cursor.close() The problem this time was: Traceback : File "insertdb_pg8000.py", line 19, in cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2) File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn TypeError: execute() takes at most 3 arguments (4 given) From marc.tompkins at gmail.com Mon Jun 28 00:56:23 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 27 Jun 2010 15:56:23 -0700 Subject: [Tutor] TypeError when io.open is used In-Reply-To: References: Message-ID: On Sun, Jun 27, 2010 at 3:20 PM, wrote: > I have tried the following, too: > > from pg8000 import DBAPI > import os > import os.path > import sys > > # !!! that is test data. It must be changed > conn=DBAPI.connect(host="localhost", database="postgres", user="postgres", > password="test") > > #conn.cursor will return a cursor oject, you can use this cursor to perform > queries > cursor = conn.cursor() > > file = open( > "C:\\Blender_Library\\BlenderLib\\objectLib\\Faqns\\Osaka2\\faqns_osaka_2.jpg", > "rb" ) > data1 = DBAPI.Binary(file.read()) > data2 = 'faqns_osaka_2' > > # execute our Query > cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", > data1, data2) > sys.stdout.flush() > > # Save (commit) the changes > conn.commit() > > # We can also close the cursor if we are done with it > cursor.close() > > The problem this time was: > Traceback : > File "insertdb_pg8000.py", line 19, in > cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n = > %s", data1, data2) > File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn > TypeError: execute() takes at most 3 arguments (4 given) > > I don't have any insight into your other piece of code, but here I think you just need another set of parentheses - so that the string interpolation is done first, and the result of it becomes the argument to cursor.execute(). I can't really test it at the moment, but try changing it to: cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2) ) Either that, or break it into two lines: myQuery = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2 cursor.execute(myQuery) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jun 28 01:25:57 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Jun 2010 09:25:57 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: Message-ID: <201006280925.57933.steve@pearwood.info> On Mon, 28 Jun 2010 03:07:47 am Richard D. Moores wrote: > A "feature" very important to me > is that with Gmail, my mail is just always THERE, with no need to > download it You see your email without downloading it? You don't understand how the Internet works, do you? *wry grin* -- Steven D'Aprano From steve at pearwood.info Mon Jun 28 01:27:45 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Jun 2010 09:27:45 +1000 Subject: [Tutor] capturing error msg in exception In-Reply-To: References: <20100627164724.GA22292@scriptkitchen.com> Message-ID: <201006280927.45911.steve@pearwood.info> On Mon, 28 Jun 2010 03:12:39 am Adam Bark wrote: > I think the 'as' syntax is only available in Python 3.x You think wrong. It is available from Python 2.6 onwards. > Question marks go at the end of the sentence where you would normally > put a full stop if it wasn't a question. That's a terribly unhelpful answer given the context of Payal's question. I'm sure he knows the grammatical rules for questions in ordinary English sentences, but he's asking specifically about a particular form of sentence where you have a question consisting of two or more alternatives or examples separated as paragraphs: [example] Hello, which is better, a lambda: (1) lambda x: x+1 or a function definition: (2) def f(x): return x+1? [end example] It is very reasonable to ask where to put the question mark in examples like this. Unfortunately there is no good answer. If you put it on the same line as the second example, as shown, certainly isn't correct because it makes the question mark part of the example. It's *especially* dangerous in a programming context, because it leads to a syntax error. Putting it on a line on it's own after the example looks silly. Re-writing the question to avoid the problem is often awkward, but can be done: [rewritten example] Hello, which of these two are better? (1) lambda x: x+1 (2) def f(x): return x+1 [end rewritten example] Since there is no One Right Answer, you can do whichever seems best in context. -- Steven D'Aprano From steve at pearwood.info Mon Jun 28 01:51:50 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Jun 2010 09:51:50 +1000 Subject: [Tutor] TypeError when io.open is used In-Reply-To: References: Message-ID: <201006280951.51033.steve@pearwood.info> On Mon, 28 Jun 2010 08:20:01 am petkovas at dir.bg wrote: > The full error message is: > > Traceback : > File "insert_into_db_v9.py", line 55, in > WHERE testtable_n = %s""", data1, > str(os.path.splitext(file)[0])) > TypeError: an integer is required Unfortunately this isn't helpful, because we're only seeing part of the offending line of code. This is because Python tracebacks only show the *physical* line which fails, but a logical line of code can be split over more than one physical line. E.g. if I have a module like this: # test.py x = 23 y = 23-x z = (42/ y) and then import it: >>> import test Traceback (most recent call last): File "", line 1, in File "test.py", line 5, in y) ZeroDivisionError: integer division or modulo by zero it only shows me the last part of the expression (42/y). So you will need to look at your source code and manually copy and paste the rest of the logical line, that is, the line or lines immediately before line 55. > And i would want to add that str() is not the problem. I have tried > without it and the problem persisted. The call to str() is totally pointless, since os.path.splitext(file)[0] is already a string. [...] > file = open( > "C:\\Blender_Library\\BlenderLib\\objectLib\\Faqns\\Osaka2\\faqns_osa >ka_2.jpg", "rb" ) Windows accepts forwards slashes for pathnames too, so the above can more simply be written: "C:/Blender_Library/BlenderLib/objectLib/Faqns/Osaka2/faqns_osaka_2.jpg" with less chance of error. > The problem this time was: > Traceback : > File "insertdb_pg8000.py", line 19, in > cursor.execute("UPDATE testtable SET jpeg = %s WHERE > testtable_n = %s", data1, data2) > File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn > TypeError: execute() takes at most 3 arguments (4 given) I'm afraid this is an example of a *slightly* misleading error message in Python. the cursor.execute method takes at most three arguments: # Something like this. class Cursor: def execute(self, a, b): pass *but* one of those arguments, self, is automatically filled in by Python. So when you call execute, you can only supply TWO arguments: cursor.execute(a, b) If you provide three: cmd = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s" cursor.execute(cmd, data1, data2) then Python fills in self and gives an error message that execute takes only three arguments, not four. So you need to read the documentation for execute to find out what arguments it takes, because you can't pass all three of cmd, data1 and data2. -- Steven D'Aprano From rdmoores at gmail.com Mon Jun 28 02:52:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 27 Jun 2010 17:52:03 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006280925.57933.steve@pearwood.info> References: <201006280925.57933.steve@pearwood.info> Message-ID: On Sun, Jun 27, 2010 at 16:25, Steven D'Aprano wrote: > On Mon, 28 Jun 2010 03:07:47 am Richard D. Moores wrote: >> A "feature" very important to me >> is that with Gmail, my mail is just always THERE, with no need to >> download it > > You see your email without downloading it? You don't understand how the > Internet works, do you? I do, and I also know that you know what I meant. Dick From petkovas at dir.bg Mon Jun 28 02:53:20 2010 From: petkovas at dir.bg (petkovas at dir.bg) Date: Mon, 28 Jun 2010 02:53:20 +0200 Subject: [Tutor] TypeError when io.open is used Message-ID: On Sun, 27 Jun 2010 15:56:23 -0700 Marc Tompkins wrote: On Sun, Jun 27, 2010 at 3:20 PM, wrote: I don't have any insight into your other piece of code, but here I think you just need another set of parentheses - so that the string interpolation is done first, and the result of it becomes the argument to cursor.execute(). I can't really test it at the moment, but try changing it to: cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2) ) Either that, or break it into two lines: myQuery = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2 cursor.execute(myQuery) -- www.fsrtechnologies.com Thank you for the suggestion that i should enforce the parantheses. At least that changed the error. Unfortunately that is wierd one, too: Traceback : File "insertdb_pg8000.py", line 20, in cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, data2) ) File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn File "build\bdist.win32\egg\pg8000\dbapi.py", line 314, in execute File "build\bdist.win32\egg\pg8000\dbapi.py", line 319, in _execute File "build\bdist.win32\egg\pg8000\interface.py", line 303, in execute File "build\bdist.win32\egg\pg8000\interface.py", line 108, in _init_ File "build\bdist.win32\egg\pg8000\protocol.py", line 913, in _fn File "build\bdist.win32\egg\pg8000\protocol.py", line 1048, in parse UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 49: ordinal not in range() I mean, as far as i know, for binary files i do not need to set encoding when i open them. PS: sorry for the direct E-Mail to Marc. From marc.tompkins at gmail.com Mon Jun 28 03:09:41 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 27 Jun 2010 18:09:41 -0700 Subject: [Tutor] TypeError when io.open is used In-Reply-To: References: Message-ID: On Sun, Jun 27, 2010 at 5:13 PM, wrote: > On Sun, 27 Jun 2010 15:56:23 -0700 > Marc Tompkins wrote: > >> On Sun, Jun 27, 2010 at 3:20 PM, wrote: >> >> I don't have any insight into your other piece of code, but here I think >> you >> just need another set of parentheses - so that the string interpolation is >> done first, and the result of it becomes the argument to cursor.execute(). >> I can't really test it at the moment, but try changing it to: >> cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", >> data1, data2) ) >> >> Either that, or break it into two lines: >> >> myQuery = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1, >> data2 >> cursor.execute(myQuery) >> >> -- >> www.fsrtechnologies.com >> > > Thank you for the suggestion that i should enforce the parantheses. At > least that changed the error. Unfortunately that is wierd one, too: > > Traceback : > File "insertdb_pg8000.py", line 20, in > > cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = > %s", data1, data2) ) > File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn > File "build\bdist.win32\egg\pg8000\dbapi.py", line 314, in execute > File "build\bdist.win32\egg\pg8000\dbapi.py", line 319, in _execute > File "build\bdist.win32\egg\pg8000\interface.py", line 303, in execute > File "build\bdist.win32\egg\pg8000\interface.py", line 108, in _init_ > File "build\bdist.win32\egg\pg8000\protocol.py", line 913, in _fn > File "build\bdist.win32\egg\pg8000\protocol.py", line 1048, in parse > UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 49: > ordinal not in range() > > I mean, as far as i know, for binary files i do not need to set encoding > when i open them. > OK - when I answered before, I was only looking at the error message and the actual line of code that generated it; I hadn't really looked at what you're trying to do. Now that I've stepped back a bit, here's what I think you're trying to achieve: - open the file "faqns_osaka_2.jpg" - read its contents - write the contents to a BLOB field (or whatever the Postgres equivalent is - anyway, a field that can hold an arbitrary chunk of data) - write the name 'faqns_osaka_2' to a label field. Unfortunately, you're trying to build the SQL command to do that using string interpolation (the %s notation.) So your program gets as far as reading the contents of the file, and then tries to decode them into a string - and that's why you get this error. Be happy you got the error - if it had succeeded, the resulting binary data would have been unreadable as an image, and you wouldn't have known why. I'm certain that there are proper ways to pass chunks of binary data for insertion into BLOB fields - people must do this every day - but I don't actually know them. Here's a possibility: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-7-sect-11.html Or try searching for "python postgres blob". -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Mon Jun 28 10:04:31 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 28 Jun 2010 09:04:31 +0100 Subject: [Tutor] capturing error msg in exception In-Reply-To: <201006280927.45911.steve@pearwood.info> References: <20100627164724.GA22292@scriptkitchen.com> <201006280927.45911.steve@pearwood.info> Message-ID: On 28 June 2010 00:27, Steven D'Aprano wrote: > On Mon, 28 Jun 2010 03:12:39 am Adam Bark wrote: > > > I think the 'as' syntax is only available in Python 3.x > > You think wrong. It is available from Python 2.6 onwards. > I know, I corrected myself after Steve Willoughby pointed it out. > > > > Question marks go at the end of the sentence where you would normally > > put a full stop if it wasn't a question. > > That's a terribly unhelpful answer given the context of Payal's > question. I'm sure he knows the grammatical rules for questions in > ordinary English sentences, but he's asking specifically about a > particular form of sentence where you have a question consisting of two > or more alternatives or examples separated as paragraphs: > > Well it was a terribly unclear question, I just answered what I thought he was asking. > [example] > Hello, which is better, a lambda: > > (1) lambda x: x+1 > > or a function definition: > > (2) def f(x): > return x+1? > [end example] > > It is very reasonable to ask where to put the question mark in examples > like this. Unfortunately there is no good answer. If you put it on the > same line as the second example, as shown, certainly isn't correct > because it makes the question mark part of the example. It's > *especially* dangerous in a programming context, because it leads to a > syntax error. > > Putting it on a line on it's own after the example looks silly. > Re-writing the question to avoid the problem is often awkward, but can > be done: > > [rewritten example] > Hello, which of these two are better? > > (1) lambda x: x+1 > > (2) def f(x): > return x+1 > [end rewritten example] > > Since there is no One Right Answer, you can do whichever seems best in > context. > I'm sure this "work it out yourself" answer is much more helpful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jun 28 12:39:58 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Jun 2010 20:39:58 +1000 Subject: [Tutor] capturing error msg in exception In-Reply-To: References: <20100627164724.GA22292@scriptkitchen.com> <201006280927.45911.steve@pearwood.info> Message-ID: <201006282039.59085.steve@pearwood.info> On Mon, 28 Jun 2010 06:04:31 pm Adam Bark wrote: > I'm sure this "work it out yourself" answer is much more helpful. Unfortunately, the only correct answer is that there is no One True Answer. A bit like life, really. -- Steven D'Aprano From adam.jtm30 at gmail.com Mon Jun 28 18:15:00 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 28 Jun 2010 17:15:00 +0100 Subject: [Tutor] What is super for? Message-ID: I can't figure out how super(C, self).__init__() is any better than C.__init__(self), is there a preference? Does super do something special? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Mon Jun 28 18:18:11 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 28 Jun 2010 17:18:11 +0100 Subject: [Tutor] What is super for? In-Reply-To: References: Message-ID: On 28 June 2010 17:15, Adam Bark wrote: > I can't figure out how super(C, self).__init__() is any better than > C.__init__(self), is there a preference? Does super do something special? > > Thanks. > Whoops I should really think about these things for a minute first, you don't have to know the superclass in advance is presumably the idea? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 28 19:36:17 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Jun 2010 18:36:17 +0100 Subject: [Tutor] What is super for? References: Message-ID: "Adam Bark" wrote >> I can't figure out how super(C, self).__init__() is any better than >> C.__init__(self), is there a preference? Does super do something >> special? > > Whoops I should really think about these things for a minute first, > you > don't have to know the superclass in advance is presumably the idea? That's normally the idea behind super(eg in Smalltalk). Unfortunately the Python version kind of negates that with the need for the class in the super() call. I think Python v3 has improved this but I admit is still use the parent.method(self...) style. To me it is just more obvious and less error prone. Alan G. From g.nius.ck at gmail.com Mon Jun 28 22:36:39 2010 From: g.nius.ck at gmail.com (Chris) Date: Mon, 28 Jun 2010 16:36:39 -0400 Subject: [Tutor] Fwd: HELP! Message-ID: <4C2907D7.6010302@gmail.com> My friend jacob had a question. I can't really answer it, but you guys can. Send you replies to him not me. Oh, and jacob, I'm forwarding you message to the Python Mailing list. -------- Original Message -------- Delivered-To: g.nius.ck at gmail.com Received: by 10.216.7.204 with SMTP id 54cs12253wep; Fri, 25 Jun 2010 05:15:53 -0700 (PDT) Return-Path: Received-SPF: pass (google.com: domain of benderjacob44 at gmail.com designates 10.231.166.146 as permitted sender) client-ip=10.231.166.146; Authentication-Results: mr.google.com; spf=pass (google.com: domain of benderjacob44 at gmail.com designates 10.231.166.146 as permitted sender) smtp.mail=benderjacob44 at gmail.com; dkim=pass header.i=benderjacob44 at gmail.com Received: from mr.google.com ([10.231.166.146]) by 10.231.166.146 with SMTP id m18mr672493iby.109.1277468152247 (num_hops = 1); Fri, 25 Jun 2010 05:15:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=domainkey-signature:mime-version:received:received:date:message-id :subject:from:to:content-type; bh=fkkLSup/Zm9O5pNVp/JD3Z8YGVub7MdiKrBLK15hCss=; b=RPMHV1heyBvD25Ds95k3tdMD25KKr4fszAGSkoIoRhRNC43pOpx08JXSaHBmuO9lLK AXh56ZUgujS2c7MZR7LonTbHf2lmH+n4iS4j9zDWnhRVQYZp0PLzXNiy6rsmm9BZ8Ssx 4MuLHSQu5ycP7RzyC1UKLo++EvMHNRXzIbJqQ= DomainKey-Signature: a=rsa-sha1; c=nofws; d=gmail.com; s=gamma; h=mime-version:date:message-id:subject:from:to:content-type; b=pEuD6hxgEDoy+BypQZeQyfam769gn9/T5P0/kTVorTYbDZX7OU+bkODyEleXmmXUQC PxuzC0rVUbzqDhswUQKv0W890MXtEBXCLMucrl8SqzlUo2Do2LuxeE9x7k7xhm6J9fSr 3pa/VxDGgj0WH9Gelflxw9XjgSPd8mVRkbuK4= MIME-Version: 1.0 Received: by 10.231.166.146 with SMTP id m18mr672493iby.109.1277468152240; Fri, 25 Jun 2010 05:15:52 -0700 (PDT) Received: by 10.231.191.71 with HTTP; Fri, 25 Jun 2010 05:15:52 -0700 (PDT) Date: Fri, 25 Jun 2010 08:15:52 -0400 Message-ID: Subject: HELP! From: Jacob Bender To: Chris Content-Type: multipart/alternative; boundary=001636e0b4036d19880489d9bb56 Chris, I tried the py2exe thing again, but things are getting confusing... It tells me to enter this line to run a setup that will make it a .exe. "C: \Tutorial>python setup.py install" Now, the REALLY BIG problem with this line is that the, I guess you could say action, of install always comes back with an invalid token error. This is straight from the website. Now, that was in different programs and on the command line. If you write it in the setup.py, it comes back with a syntax error after the install... Please help Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Jun 28 23:17:39 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 28 Jun 2010 22:17:39 +0100 Subject: [Tutor] Fwd: HELP! In-Reply-To: <4C2907D7.6010302@gmail.com> References: <4C2907D7.6010302@gmail.com> Message-ID: On 28 June 2010 21:36, Chris wrote: > My friend jacob had a question. I can't really answer it, but you guys > can. Send you replies to him not me. Oh, and jacob, I'm forwarding you > message to the Python Mailing list. > > Hi Chris/Jacob, I'm not sure if it's just me, but I'd have been slightly more interested in helping and have found it a bit more polite if your friend came to this list direct with his problem, rather than you basically appearing to be palming off a support request for something that you started onto strangers on the Python language tutoring list. (This isn't exactly a python language problem either.) That said: Jacob can you please post *exactly* what you enter, and what output you get? (Copy and paste please, don't paraphrase/second guess what we might want to know.) Suffice it to say that you're likely somehow entering the command incorrectly. (I can only speculate at this point that you're incorrectly including part of the command prompt in your command, and/or possibly inserting spaces (or omitting them) where needed. ) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Jun 28 23:20:34 2010 From: g.nius.ck at gmail.com (Chris) Date: Mon, 28 Jun 2010 17:20:34 -0400 Subject: [Tutor] Fwd: HELP! In-Reply-To: References: <4C2907D7.6010302@gmail.com> Message-ID: <4C291222.1040703@gmail.com> On 06/28/2010 05:17 PM, Walter Prins wrote: > On 28 June 2010 21:36, Chris @gmail.com > > wrote: > > My friend jacob had a question. I can't really answer it, but you > guys can. Send you replies to him not me. Oh, and jacob, I'm > forwarding you message to the Python Mailing list. > > Hi Chris/Jacob, > > I'm not sure if it's just me, but I'd have been slightly more > interested in helping and have found it a bit more polite if your > friend came to this list direct with his problem, rather than you > basically appearing to be palming off a support request for something > that you started onto strangers on the Python language tutoring list. > (This isn't exactly a python language problem either.) > > That said: Jacob can you please post *exactly* what you enter, and > what output you get? (Copy and paste please, don't paraphrase/second > guess what we might want to know.) Suffice it to say that you're > likely somehow entering the command incorrectly. (I can only > speculate at this point that you're incorrectly including part of the > command prompt in your command, and/or possibly inserting spaces (or > omitting them) where needed. ) > > Regards > > Walter Well I was just showing him the list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lang at tharin.com Tue Jun 29 00:06:56 2010 From: lang at tharin.com (Lang Hurst) Date: Mon, 28 Jun 2010 15:06:56 -0700 Subject: [Tutor] Fwd: HELP! In-Reply-To: <4C2907D7.6010302@gmail.com> References: <4C2907D7.6010302@gmail.com> Message-ID: <4C291D00.3010109@tharin.com> On 06/28/2010 01:36 PM, Chris wrote: > My friend jacob had a question. I can't really answer it, but you guys > can. Send you replies to him not me. Oh, and jacob, I'm forwarding you > message to the Python Mailing list. > > > > Chris, > I tried the py2exe thing again, but things are getting confusing... It > tells me to enter this line to run a setup that will make it a .exe. > "C: \Tutorial>python setup.py install" > Now, the REALLY BIG problem with this line is that the, I guess you > could say action, of install always comes back with an invalid token > error. This is straight from the website. > Now, that was in different programs and on the command line. If you > write it in the setup.py, it comes back with a syntax error after the > install... Please help For what it's worth, py2exe never really worked for me the one time I was trying to bundle up a program. I ended up using pyinstaller ( http://www.pyinstaller.org/ ) and it worked pretty much without a hitch. Good luck, and next time don't be scared to ask yourself. I don't think this is a python problem, so I doubt this list is the correct place... -Lang > Jake > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- There are no stupid questions, just stupid people. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Jun 29 02:28:39 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Jun 2010 10:28:39 +1000 Subject: [Tutor] What is super for? In-Reply-To: References: Message-ID: <201006291028.40139.steve@pearwood.info> On Tue, 29 Jun 2010 02:15:00 am Adam Bark wrote: > I can't figure out how super(C, self).__init__() is any better than > C.__init__(self), is there a preference? Does super do something > special? You've written that slightly wrong. You write the name of the *parent* class in the direct call to the method, and the name of the *current* class in the call to super: class MyClass(C): def __init__(self): super(MyClass, self).__init__() # or C.__init__(self) super() does a lot, but remember it only works with new-style classes. Consider a class with multiple inheritance: class MyClass(C, D): def f(self, *args): do_something() # now need to inherit behaviour from the super-classes The question is, how do we write method f()? def f(self, *args): do_something() C.f(self, *args) D.f(self, *args) But that's not right, because C might not have method f. Or D might not have it. Or they might both have it. Or neither C nor D have the method, and *both* inherit it from the same parent class higher up the hierarchy, B. If you manually call C.f and D.f, you end up calling B.f *twice*. Oops. Even if C and D don't share the same parent class, they might inherit from a chain of classes, any of which defines f. Working out which method f to call can be complicated. super() handles all that complication for you. You just write: def f(self, *args): do_something() super(MyClass, self).f(*args) and it works out which parent classes to call in which order. Now, right about now you're probably thinking that since you don't use multiple inheritance, you don't care about super. Fair enough. But consider somebody who imports your class to inherit from them. They might be using multiple inheritance, or they might not be. If you use super(), then your class will work correctly for them regardless of whether they have multiple or single inheritance. But if you call the parent class manually, your class will *only* work with single inheritance. You can find lots more about super and multiple inheritance on the web, both for and against. Mostly against in the Python world. I have read them, so you don't have to, and my summary is: * Don't use multiple inheritance. * If you have to use multiple inheritance, make sure you *really* have to. * Whether you use multiple inheritance or not, use super() so that those brave or foolish souls who do can inherit from you. * Use super() consistently, and document that you use it as part of your class' external interface. * Never call super() with anything but the exact arguments you received, unless you're a guru. There is a provocative article called "Python's Super Considered Harmful". Despite the title, if you read the whole article you discover that the author doesn't actually recommend *against* super at all. http://fuhm.net/super-harmful/ This thread on the Python-Dev mailing list discusses the above article: http://mail.python.org/pipermail/python-dev/2005-January/050656.html And here are some links from Michele Simionato on why mixins and multiple inheritance should be avoided unless you really, really need it, and how to avoid needing it: http://www.artima.com/weblogs/viewpost.jsp?thread=246341 http://www.artima.com/weblogs/viewpost.jsp?thread=246483 http://www.artima.com/forums/flat.jsp?forum=106&thread=237121 http://www.artima.com/forums/flat.jsp?forum=106&thread=246488 -- Steven D'Aprano From steve at pearwood.info Tue Jun 29 02:32:06 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Jun 2010 10:32:06 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> Message-ID: <201006291032.06481.steve@pearwood.info> On Mon, 28 Jun 2010 10:52:03 am Richard D. Moores wrote: > On Sun, Jun 27, 2010 at 16:25, Steven D'Aprano wrote: > > On Mon, 28 Jun 2010 03:07:47 am Richard D. Moores wrote: > >> A "feature" very important to me > >> is that with Gmail, my mail is just always THERE, with no need to > >> download it > > > > You see your email without downloading it? You don't understand how > > the Internet works, do you? > > I do, and I also know that you know what I meant. No, I'm afraid that I don't. You log into Gmail and your browser downloads the Gmail page; you click on an email, and your browser downloads the contents of the email in order to display it. I'm afraid I have no idea what you mean by not downloading your email. Perhaps you should try reading a 50MB email over dial-up to drive home the fact that you *are* downloading? The difference is that, with Gmail (or Hotmail, or Yahoo mail), you have to download it each time you read the email instead of just once. Particularly as this is a programming mailing list, I think it is very important to remember that fetching information over the Internet *is* downloading, and not just gloss over it as some sort of magic. There are Python libraries specifically for dealing with all this, and apart from the ability to execute Javascript, Python can do pretty much everything your browser does. There are two sorts of people in the world: those who think that (e.g.) watching a streaming video in your browser over the Internet is fundamentally different from "downloading", and those who know that the only difference is that with streaming, the browser deletes the video after you've watched it. I would think that, as programmers, we should be in the second group rather than the first. -- Steven D'Aprano From smokefloat at gmail.com Tue Jun 29 03:18:26 2010 From: smokefloat at gmail.com (David Hutto) Date: Mon, 28 Jun 2010 21:18:26 -0400 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006291032.06481.steve@pearwood.info> References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On Mon, Jun 28, 2010 at 8:32 PM, Steven D'Aprano wrote: > On Mon, 28 Jun 2010 10:52:03 am Richard D. Moores wrote: >> On Sun, Jun 27, 2010 at 16:25, Steven D'Aprano > wrote: >> > On Mon, 28 Jun 2010 03:07:47 am Richard D. Moores wrote: >> >> A "feature" very important to me >> >> is that with Gmail, my mail is just always THERE, with no need to >> >> download it >> > >> > You see your email without downloading it? You don't understand how >> > the Internet works, do you? >> >> I do, and I also know that you know what I meant. > > No, I'm afraid that I don't. You log into Gmail and your browser > downloads the Gmail page; you click on an email, and your browser > downloads the contents of the email in order to display it. I'm afraid > I have no idea what you mean by not downloading your email. Perhaps you > should try reading a 50MB email over dial-up to drive home the fact > that you *are* downloading? > > The difference is that, with Gmail (or Hotmail, or Yahoo mail), you have > to download it each time you read the email instead of just once. > > Particularly as this is a programming mailing list, I think it is very > important to remember that fetching information over the Internet *is* > downloading, and not just gloss over it as some sort of magic. There > are Python libraries specifically for dealing with all this, and apart > from the ability to execute Javascript, Python can do pretty much > everything your browser does. > > There are two sorts of people in the world: those who think that (e.g.) > watching a streaming video in your browser over the Internet is > fundamentally different from "downloading", and those who know that the > only difference is that with streaming, the browser deletes the video > after you've watched it. But this only matters if a)you're paying for it, not the boss b) that there are unlimited plans available for a single monthly price, or c) you have an 'egotistical'(meaning a professional ego/rep to maintain) perspective on minimizing your code. I would think that, as programmers, we should > be in the second group rather than the first. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Tue Jun 29 04:13:20 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 28 Jun 2010 19:13:20 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <201006291032.06481.steve@pearwood.info> References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On Mon, Jun 28, 2010 at 17:32, Steven D'Aprano wrote: > On Mon, 28 Jun 2010 10:52:03 am Richard D. Moores wrote: >> On Sun, Jun 27, 2010 at 16:25, Steven D'Aprano > wrote: >> > On Mon, 28 Jun 2010 03:07:47 am Richard D. Moores wrote: >> >> A "feature" very important to me >> >> is that with Gmail, my mail is just always THERE, with no need to >> >> download it >> > >> > You see your email without downloading it? You don't understand how >> > the Internet works, do you? >> >> I do, and I also know that you know what I meant. > > No, I'm afraid that I don't. I think you should have. > You log into Gmail and your browser downloads the Gmail page; Yes, of course. But I'm always logged into Gmail. With Eudora I would have to manually *download* new email to see what was new (as I recall, there was a way to set Eudora to check for new mail at an interval I could set -- but I often found this an annoying interruption); with Gmail this is done for me (with no annoyance). That's what I meant by "my mail is just always THERE", and because you know the difference between OE and Gmail you knew what I meant, even if I may have expressed it incorrectly. I really don't need your lecture on this. I'm sure there's plenty for me to learn from you, but not this. > you click on an email, and your browser > downloads the contents of the email in order to display it. Of course. Just like anything else which has to get from a Gmail server to me. If text, that's a small fraction of a second for me. So small that it appears to be instantaneous. If there are images, it's still a small fraction of a second, and images are usually there by the time I can scroll down to them. > I'm afraid > I have no idea what you mean by not downloading your email. Perhaps you > should try reading a 50MB email over dial-up to drive home the fact > that you *are* downloading? Sure, but I have broadband access, as do many. My fault for not mentioning this -- but you should not pretend to not have inferred that I did have such access. > The difference is that, with Gmail (or Hotmail, or Yahoo mail), you have > to download it each time you read the email instead of just once. Not a problem. See above. > Particularly as this is a programming mailing list, I think it is very > important to remember that fetching information over the Internet *is* > downloading, and not just gloss over it as some sort of magic. There > are Python libraries specifically for dealing with all this, and apart > from the ability to execute Javascript, Python can do pretty much > everything your browser does. NOW you're talking about stuff I'd like to learn here. > There are two sorts of people in the world: those who think that (e.g.) > watching a streaming video in your browser over the Internet is > fundamentally different from "downloading", and those who know that the > only difference is that with streaming, the browser deletes the video > after you've watched it. I would think that, as programmers, we should > be in the second group rather than the first. Hear, hear! But also to not be so quick when classifying others. Dick From oberoc at gmail.com Tue Jun 29 04:34:26 2010 From: oberoc at gmail.com (Tino Dai) Date: Mon, 28 Jun 2010 22:34:26 -0400 Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: <85912.16789.qm@web23606.mail.ird.yahoo.com> References: <85912.16789.qm@web23606.mail.ird.yahoo.com> Message-ID: On Sun, Jun 27, 2010 at 12:15 PM, Khawla Al-Wehaibi wrote: > Hi, > > I?m new to programming. I?m currently learning python to write a web > crawler to extract all text from a web page, in addition to, crawling to > further URLs and collecting the text there. The idea is to place all the > extracted text in a .txt file with each word in a single line. So the text > has to be tokenized. All punctuation marks, duplicate words and non-stop > words have to be removed. > Welcome to Python! What you are doing is best done in a multi step process so that you can understand everything that you are doing. To really leverage Python, there are a couple of things that you need to read right off the bat. http://docs.python.org/library/stdtypes.html (Stuff about strings). In Python, everything is an object so everything will have methods or functions related to it. For instance, the String object has a find method that will return position of the string. Pretty handy if you ask me. Also, I would read up on sets for python. That will reduce the size of your code significantly. > > The program should crawl the web to a certain depth and collect the URLs > and text from each depth (level). I decided to choose a depth of 3. I > divided the code to two parts. Part one to collect the URLs and part two to > extract the text. Here is my problem: > > 1. The program is extremely slow. > The best way to go about this is to use a profiler: http://docs.python.org/library/profile.html 2. I'm not sure if it functions properly. > To debug your code, you may want to read up on the python debugger. http://docs.python.org/library/pdb.html 3. Is there a better way to extract text? > See the strings and the lists. I think that you will be pleasantly surprised > 4. Are there any available modules to help clean the text i.e. removing > duplicates, non-stop words ... > Read up on sets and the string functions/method. They are your friend > 5. Any suggestions or feedback is appreciated. > > -Tino PS: Please don't send html ladden emails, it makes it harder to work with. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 29 09:48:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Jun 2010 08:48:26 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006280925.57933.steve@pearwood.info><201006291032.06481.steve@pearwood.info> Message-ID: "David Hutto" wrote > > fundamentally different from "downloading", and those who know > > that the > > only difference is that with streaming, the browser deletes the > > video > > But this only matters if a)you're paying for it, not the boss b) > that > there are unlimited plans available for a single monthly price, or > c) > you have an 'egotistical'(meaning a professional ego/rep to > maintain) > perspective on minimizing your code. Or if the network is shared with other users or other applications since heavy downloads slow down access for every network user. And if your neighbour is downloading a lot of video you will notice the effect on your network speed. Remember that network speeds have become the biggest single factor in determining application performance nowadays - it used to be memory and disk speed - so we as programmers need to be very conscious of the impact of gratuitous downloads and consider caching strategies etc. We can't do a lot about other people streaming videos other than minimise our network requirements. But we should at least be conscious of how network habits affect other users. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jun 29 10:06:46 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Jun 2010 09:06:46 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: "Richard D. Moores" wrote >> You log into Gmail and your browser downloads the Gmail page; > > Yes, of course. But I'm always logged into Gmail. But it is stiill continually downloading. The same applies to a desktop client, if you leave it running it can continually poll the server, just like gmail. > With Eudora I would have to manually *download* new email > to see what was new (as I recall, there was a way to set > Eudora to check for new mail at an interval I could set But nobody with an always-on conection would sensibly do that, the tool polls the server - in my case every 15 minutes, but it could be more often; at work its every minute. > That's what I meant by "my mail is just always THERE", and because > you > know the difference between OE and Gmail you knew what I meant, But its exactly wrong because in gmail your mail is never there. It has to be fetched each and every time you read it. In OE/Eudora/TB it is really there on your PC. You can read it even when offline. Web mail is fantastically inefficient and a huge waste of bandwidth. One of the big problems with the move towards "Cloud Computing" is the massive amount of extra bandwidth required - who is going to pay for it? The telcos can't affiord to keep on giving unlimited bits to everyone, there will need to be new charging models introduced to make the whole thing viable. This is a very big and important issue and as Steven says we as programmers need to understand the wider implications of the programming solutions we build. > Of course. Just like anything else which has to get from a Gmail > server to me. If text, that's a small fraction of a second for me. > So > small that it appears to be instantaneous. If there are images, > it's > still a small fraction of a second, and images are usually there by > the time I can scroll down to them. You must have very fast broadband! Images general take several seconds over my 2M (nominally 8M) connection (on a good day, often it slows to under 1M if the neighbours are watching IP TV...) > Sure, but I have broadband access, as do many. But that is still a shared resource and even if you have high speed ADSL+ (20M+) it is still a performance bottleneck that you need to be conscious of. I know this discussion started as a flippant comment but it does bring to light some very serious challenges for programmers. We all need to be aware of the bottlenecks ion our designs and currently network bandwidth (and latency but that's another debate) is the biggest bottleneck for many applications. (And its nice to see an OT thread come back on topic! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jun 29 10:22:44 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Jun 2010 09:22:44 +0100 Subject: [Tutor] What is super for? References: <201006291028.40139.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Even if C and D don't share the same parent class, they might > inherit > from a chain of classes, any of which defines f. Working out which > method f to call can be complicated. > > super() handles all that complication for you. You just write: Yes, I do use super for multiple inheritance. But I don't use MI all that often in Python! > them, so you don't have to, and my summary is: > > * Don't use multiple inheritance. This depends on the language. I started my OO programming using Lisp Flavours in the 1980's and it was all about MI. You created classes by mixing in different abstract classes (Mixins). Every object used MI extensively. But Flavors was designed for that and had many control mechanisms to fine tune the MRO. When I first moved to C++ I took my Flavors style with me and tried to use it - it was a nightmare because C++ had a fixed MRO that resulted in multiple calls to methods etc. I very quickly changed my OO Design style! Python is more like C++ than Flavors so in this context Steven's advise is sound, only use MI if its really needed. And to some extent thats true of single inheritance too - it should be to support an "is-a" relationship, not just an implementation shortcut. > And here are some links from Michele Simionato on why mixins and > multiple inheritance should be avoided unless you really, really > need > it, and how to avoid needing it: Again, I add the caveat that if the language supports it, and the paradigm is common its not that bad. But most OO languages don't support it very well! Also MI from concrete classes rather than abstracts makes the problems much, much worse. A mixin class should be abstract. And finally I'll say I'd much rather have the option of MI than not. In those cases where you really need it is vastly preferable to mass delegation - easier to write and easier to maintain. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Tue Jun 29 11:16:01 2010 From: wprins at gmail.com (Walter Prins) Date: Tue, 29 Jun 2010 10:16:01 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: At the risk of adding more fuel to the fire, I'll simply note that a) I sometimes use Gmail while we visit folks in South Africa who are still on 56k dial-up. Initial log-in can be a bit slow, but generally you'd be surprised at how efficient/quick it is w.r.t bandwidth. (As an aside, with the amount of mail I receive on a daily basis, using a conventional "download then read" client on a 56k dial up link would be totally impractical for me, while by contrast the web-interface allows me to actually keep on top of my mailbox in a reasonable manner.) b) Gmail does a lot of in-browser caching, so re-opening a mail you already opened recently does not instigate another network round trip. You can test this by viewing a bunch of emails, then setting your browser into "Work offline" mode. You'll see that Gmail will happily re-open emails you've already opened without requiring a re-fetch. c) As the web matures the trend towards web-applications being able to store data locally and run off-line should increase, further improving bandwidth efficiency on the one hand and end-user experience on the other. (See fore example this presentation on HTML 5: http://slides.html5rocks.com/#slide1 ) c) Stating the obvious but you can turn downloading of images off by default in your browser, which will of course further reduce the actual bandwidth usage by essentially reducing your web browsing to a text-only stream (which of course to boot will be compressed between web server and web browser.) d) Using Gmail means you don't waste bandwidth unneccesarily downloading mails with big attachments (PDF files, Word files) unless you actually want to, and also prevents you from having to download hundreds of spam messages and/or your entire inbox before viewing specific emails, which can eat large amounts of bandwidth. (There is of course IMAP as well...) e) Actually having access to your email from places you wouldn't normally have access to it (on holiday, at conference) is a benefit you don't neccesarily have with a conventional client. (You'll only have it if the client is on your laptop and you have your laptop with you and you can connect it to a network allowing internet access. ) As for me, I use gmail but with Thunderbird as mail client on my desktop. In this way I have the best of both worlds. When at home I'll download my mail as normal, when abroad I have an interface accessible from anywhere with internet access. I absolutely agree about programmers having to be aware of the bandwidth costs involved with every operation they do, as bandwidth isn't free. However, the internet is after all, a network, and the argumentation ostensibly against web based services (especially potentially relatively low bandwidth ones like gmail) on the basis that they consume network bandwidth per-se, seemed a little OTT to me. YMMV. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Tue Jun 29 11:31:32 2010 From: smokefloat at gmail.com (David Hutto) Date: Tue, 29 Jun 2010 05:31:32 -0400 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On Tue, Jun 29, 2010 at 3:48 AM, Alan Gauld wrote: > > "David Hutto" wrote > >> > fundamentally different from "downloading", and those who know > that >> > the >> > only difference is that with streaming, the browser deletes the > video >> >> But this only matters if a)you're paying for it, not the boss b) that >> there are unlimited plans available for a single monthly price, or c) >> you have an 'egotistical'(meaning a professional ego/rep to maintain) >> perspective on minimizing your code. > > Or if the network is shared with other users or other applications > since heavy downloads slow down access for every network user. > And if your neighbour is downloading a lot of video you will notice > the effect on your network speed. So, the bandwidth supplied(better question for my own ISP) is like a drop cord, even with alleged T1 connections plugged in, it drop in accordance with usage that exceeds the max capacity even though they sell it as it's max capacity?. Sometimes I watch the wave of bandwidth and wonder, but a question seldom asked if service is satisfactory. > > Remember that network speeds have become the biggest single > factor in determining application performance nowadays - it used > to be memory and disk speed - so we as programmers need to > be very conscious of the impact of gratuitous downloads and > consider caching strategies etc. We can't do a lot about other > people streaming videos other than minimise our network requirements. > But we should at least be conscious of how network habits affect > other users. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Tue Jun 29 11:48:55 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 29 Jun 2010 02:48:55 -0700 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On Tue, Jun 29, 2010 at 01:06, Alan Gauld wrote: > "Richard D. Moores" wrote > >>> You log into Gmail and your browser downloads the Gmail page; >> >> Yes, of course. But I'm always logged into Gmail. > > But it is still continually downloading. The same applies to a > desktop client, if you leave it running it can continually poll the > server, just like gmail. Well, as I said, I found having Eudora do that was quite annoying (I'm afraid I've forgotten the particulars). Gmail is not. In any event, There are many, many reasons to choose to use Gmail over Eudora or OE and their ilk. >> That's what I meant by "my mail is just always THERE", and because you >> know the difference between OE and Gmail you knew what I meant, > > But its exactly wrong because in gmail your mail is never there. No, I meant what Gmail shows in the inbox continually because I'm always logged on. > It has to be fetched each and every time you read it. And it IS there in a usually not noticeable instant. > In OE/Eudora/TB > it is really there on your PC. You can read it even when offline. If I needed to do that, I'd look up Gears. To quote Marc Tompkins in this thread, "Gears enables offline reading [with Gmail]." > Web mail is fantastically inefficient and a huge waste of bandwidth. I have no reason to be concerned with bandwidth. Much, much worse in your book should be all those Netflix subscribers who watch a subset of its available films online. Wouldn't it take thousands of Gmail always-logged-on users like me to use the bandwidth of one online film watcher? Then there are the YouTubers, etc., etc. Sorry -- didn't mean to be parochial -- Netflix is not available outside the U.S. -- I just called them to check. > One of the big problems with the move towards "Cloud Computing" > is the massive amount of extra bandwidth required - who is going to > pay for it? The telcos can't afford to keep on giving unlimited bits to > everyone, there will need to be new charging models introduced to > make the whole thing viable. This is a very big and important issue > and as Steven says we as programmers need to understand the wider > implications of the programming solutions we build. Fine. >> Of course. Just like anything else which has to get from a Gmail >> server to me. If text, that's a small fraction of a second for me. So >> small that it appears to be instantaneous. If there are images, it's >> still a small fraction of a second, and images are usually there by >> the time I can scroll down to them. > > You must have very fast broadband! I do, but nothing special for this area. >Images general take several > seconds over my 2M (nominally 8M) connection (on a good day, > often it slows to under 1M if the neighbours are watching IP TV...) I see no noticeable neighbor effect. I'm sorry about your image loading times. Reminds me of my dial-up days of 10+ years ago. I continued to use a shell account as long as they were available -- a tc shell, pine, with vi or vim as an editor, sendmail for complex mail filters, lynx for a browser. I continued with those even after most people were using, what, Netscape? Mosaic? Then there were all those cool UNIX tools that some ISP's made available. > But that is still a shared resource and even if you have high > speed ADSL+ (20M+) it is still a performance bottleneck that > you need to be conscious of. No, I don't think so. Not where I am. Dick From paradox at pobox.com Tue Jun 29 14:26:23 2010 From: paradox at pobox.com (Thomas C. Hicks) Date: Tue, 29 Jun 2010 20:26:23 +0800 Subject: [Tutor] Suggestions for output on multiple platforms Message-ID: <20100629202623.4ad93053@midgel> I am a beginner at all this and never expected to reach a point where people other than myself may have to have access to the output of one of my programs. My problem is this - I have written a program that uses xlrd to read a series of xls files and collate and summarize the data. My original plan was to then write out that data into another xlwt spreadsheet that could be updated on a regular basis. I was thinking of adding a page per month as the data is updated regularly. The problem is that xlwt doesn't allow for very convenient addition of data to a spreadsheet - basically it has to re-create the whole spreadsheet each time. So now I am looking for suggestions of how I can output my data analysis. I am running Linux but the data needs to be able to be seen by users of OSX and Windows. I have been reading about GTK and figure I could output the analysis using that but am not sure it will be readable under Mac and Windows. Any ideas are welcome! thomas From kushal.kumaran+python at gmail.com Tue Jun 29 16:00:19 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 29 Jun 2010 19:30:19 +0530 Subject: [Tutor] Suggestions for output on multiple platforms In-Reply-To: <20100629202623.4ad93053@midgel> References: <20100629202623.4ad93053@midgel> Message-ID: On Tue, Jun 29, 2010 at 5:56 PM, Thomas C. Hicks wrote: > I am a beginner at all this and never expected to reach a point where > people other than myself may have to have access to the output of one > of my programs. ?My problem is this - I have written a program that > uses xlrd to read a series of xls files and collate and summarize the > data. ?My original plan was to then write out that data into another > xlwt spreadsheet that could be updated on a regular basis. ?I was > thinking of adding a page per month as the data is updated regularly. > > The problem is that xlwt doesn't allow for very convenient addition of > data to a spreadsheet - basically it has to re-create the whole > spreadsheet each time. > > So now I am looking for suggestions of how I can output my data > analysis. ?I am running Linux but the data needs to be able to be seen > by users of OSX and Windows. ?I have been reading about GTK and figure > I could output the analysis using that but am not sure it will be > readable under Mac and Windows. ?Any ideas are welcome! > Does it have to be a spreadsheet? Will csv files do as well? They are opened transparently in spreadsheet programs. And adding to csv files should be no difficulty as well. BTW, if you're thinking of adding a new sheet to an excel file every month, you should know that there's a limit to the number of sheets you can put in an excel workbook. -- regards, kushal From bgailer at gmail.com Tue Jun 29 16:17:14 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 29 Jun 2010 07:17:14 -0700 Subject: [Tutor] Suggestions for output on multiple platforms In-Reply-To: <20100629202623.4ad93053@midgel> References: <20100629202623.4ad93053@midgel> Message-ID: <4C2A006A.3030402@gmail.com> On 6/29/2010 5:26 AM, Thomas C. Hicks wrote: > I am a beginner at all this and never expected to reach a point where > people other than myself may have to have access to the output of one > of my programs. My problem is this - I have written a program that > uses xlrd to read a series of xls files and collate and summarize the > data. My original plan was to then write out that data into another > xlwt spreadsheet that could be updated on a regular basis. I was > thinking of adding a page per month as the data is updated regularly. > > The problem is that xlwt doesn't allow for very convenient addition of > data to a spreadsheet - basically it has to re-create the whole > spreadsheet each time. > > So now I am looking for suggestions of how I can output my data > analysis. I am running Linux but the data needs to be able to be seen > by users of OSX and Windows. I have been reading about GTK and figure > I could output the analysis using that but am not sure it will be > readable under Mac and Windows. Any ideas are welcome! > Write the data to an html file and view it in a browser. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Tue Jun 29 17:11:12 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Jun 2010 16:11:12 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006280925.57933.steve@pearwood.info><201006291032.06481.steve@pearwood.info> Message-ID: "David Hutto" wrote > > Or if the network is shared with other users or other applications > > So, the bandwidth supplied(better question for my own ISP) is like a > drop cord, even with alleged T1 connections plugged in, it drop in > accordance with usage that exceeds the max capacity even though they > sell it as it's max capacity?. It depends on the access mechanism. If its a T1 link then it is a dedicated line for your own use and not shared by anyone - although the server/router its connected to at the ISP may well be! If its a typical ADSL line it will be conneced to a DSLAM at the centeral office(by the telco) and that will be shareed. So a typical consumer line has a ratio of 50:1 users. A business line might be only 10:1 or 20:1. This works on the assumption that most users spend more time reading than downooading the content. As we move to streaming data sources that assumption becomes invalid and the DSLAM bandwidth is effectively shared. ADSL also loses bandwidth the further you are from the office so what is sold as an 8Mb line will rarely give more than 5-6Mb and may be as low as 1 or 2. But that is mostly a physical limitation on the copper cables used. And finally, the 'A' in ADSL stands for asymmetric so the upload speed it usually only a fraction of the download speed, often only a few hundred kilobits/sec. Even with ADSL+ (20M+) the upload speed is usually less than 1Mb. That means that a 1MB(yte) document may only take 1-2 sec to download but take 10s+ to upload (why sending mail is usually much slower than receiving) Alan G. From kwehaibi at yahoo.com Tue Jun 29 17:12:20 2010 From: kwehaibi at yahoo.com (Khawla Al-Wehaibi) Date: Tue, 29 Jun 2010 15:12:20 +0000 (GMT) Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: Message-ID: <590411.35767.qm@web23606.mail.ird.yahoo.com> Thanks Tino. Sorry for the way the post looks. It is terrible to read. I decided to go with Regular Expressions to modify the text. In the Python.org it is stated that they provide more options and flexibilty compared to strings and their modules. Thanks --- On Tue, 29/6/10, Tino Dai wrote: From: Tino Dai Subject: Re: [Tutor] retrieve URLs and text from web pages To: "Khawla Al-Wehaibi" Cc: tutor at python.org Date: Tuesday, 29 June, 2010, 5:34 On Sun, Jun 27, 2010 at 12:15 PM, Khawla Al-Wehaibi wrote: Hi, I?m new to programming. I?m currently learning python to write a web crawler to extract all text from a web page, in addition to, crawling to further URLs and collecting the text there. The idea is to place all the extracted text in a .txt file with each word in a single line. So the text has to be tokenized. All punctuation marks, duplicate words and non-stop words have to be removed. ?Welcome to Python! What you are doing is best done in a multi step process so that you can understand everything that you are doing. To really leverage Python, there are a couple of things that you need to read right off the bat. http://docs.python.org/library/stdtypes.html?? (Stuff about strings). In Python, everything is an object so everything will have methods or functions related to it. For instance, the String object has a find method that will return position of the string. Pretty handy if you ask me. Also, I would read up on sets for python. That will reduce the size of your code significantly. The program should crawl the web to a certain depth and collect the URLs and text from each depth (level). I decided to choose a depth of 3. I divided the code to two parts. Part one to collect the URLs and part two to extract the text. Here is my problem: 1.??? The program is extremely slow. The best way to go about this is to use a profiler: ?http://docs.python.org/library/profile.html 2.??? I'm not sure if it functions properly. To debug your code, you may want to read up on the python debugger. ?http://docs.python.org/library/pdb.html 3.??? Is there a better way to extract text? See the strings and the lists. I think that you will be pleasantly surprised ? 4.??? Are there any available modules to help clean the text i.e. removing duplicates, non-stop words ... Read up on sets and the string functions/method. They are your friend 5.??? Any suggestions or feedback is appreciated. -Tino PS: Please don't send html ladden emails, it makes it harder to work with. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 29 17:32:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Jun 2010 16:32:21 +0100 Subject: [Tutor] OT: need computer advice from wise Tutors References: <201006280925.57933.steve@pearwood.info><201006291032.06481.steve@pearwood.info> Message-ID: "Walter Prins" wrote > a) I sometimes use Gmail while we visit folks in South Africa who > are still > on 56k dial-up. Initial log-in can be a bit slow, but generally > you'd be > surprised at how efficient/quick it is w.r.t bandwidth. To be fair to Google, GMail is one of the best implemented web mail systems around. If you must use web mail then I'd go with Gmail over Yahoo for example. > the amount of mail I receive on a daily basis, using a conventional > "download then read" client on a 56k dial up link would be totally > impractical for me, I've used a desktop client for the last 25 years, even over a 1200 baud dialup modem. Because it downloads in the background you rarely notice the delays. My volumes have increased in the 30 years but only from about 30-200 mails a day, my bandwidth OTOH has increased by much more! :-). > b) Gmail does a lot of in-browser caching, Sure, as I say GMail is one of the best but the cache times out and if you read older mail it does download it afresh. I regularly reference mail from a year or more ago. > c) As the web matures the trend towards web-applications being able > to store > data locally and run off-line should increase, further improving > bandwidth Absolutely, but that requires the programmers to intimately understand the impact of their internet usage. Which is the point being made by Steven and myself. Its not a dig at Web mail per se, its the fact that as programmers we need to understand exacvtly what is going on over the network and its potential impact - and not just on the immediate user but those users potentially sharing the network. > c) Stating the obvious but you can turn downloading of images off by > default > in your browser, which will of course further reduce the actual > bandwidth I used to do that when I had Mosaic running over 9600 baud, but after I got to 56K I turned them back on - especially when web designers started sending text as graphics (to get fancy fonts) and did so without using alt tags! > d) Using Gmail means you don't waste bandwidth unneccesarily > downloading > mails with big attachments (PDF files, Word files) unless you > actually want Most desktop clients can either only download headers and fetch the body on demand, or download headers and body but leave attachments till later, or download everything. On my mobile phone I go headers only, on my work PC I get everything and on my home PC I get headers and text. > e) Actually having access to your email from places you wouldn't > normally > have access to it (on holiday, at conference) is a benefit you don't > neccesarily have with a conventional client. No, and this is where webmail is genuinely useful. I have 6 email accounts and all of them have a webmail inteface but I fetch all of them into my desktop client. But if I am on holiday and don't have my PC then I use webmail to keep abreast of things. I'm not against Web mail, I just recognise that its not a network efficient way to read email. > I absolutely agree about programmers having to be aware of the > bandwidth > costs involved with every operation they do, as bandwidth isn't > free. > However, the internet is after all, a network, and the argumentation > ostensibly against web based services (especially potentially > relatively low > bandwidth ones like gmail) on the basis that they consume network > bandwidth > per-se, seemed a little OTT to me. YMMV. I don't think anyone is arguing against these services. Cloud computing is almost certainly the future. But as programmers - and this is a programmer's list - we need to be aware of and understand how apps use the network and how we can minimise the adverse impacts. And as responsible internet users we should recognise the negative impacts our usage habits can have on our neighbours, in much the same way as drivers need to recognise the impact of bad driving on other road users. Email is, as someone pointed out a relativel small consumer of bandwidth, much worse would be somebody leaving a streaming video source on auto repeat! But having said that the latest figures still place text services as about 50% of all internet traffic, so every little helps. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Tue Jun 29 17:38:39 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 29 Jun 2010 17:38:39 +0200 Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: <590411.35767.qm@web23606.mail.ird.yahoo.com> References: <590411.35767.qm@web23606.mail.ird.yahoo.com> Message-ID: Khawla Al-Wehaibi, 29.06.2010 17:12: > I decided to go with Regular Expressions to modify the text. In the > Python.org it is stated that they provide more options and flexibilty > compared to strings and their modules. "their modules" referring to the "string" module and the string methods here, I assume. Regular expressions are also a lot harder to read and get right, you'll see. They are an important tool in a programmers toolbox, so it's good to learn them, but it's also good to know when *not* to use them. Stefan From oberoc at gmail.com Tue Jun 29 18:26:49 2010 From: oberoc at gmail.com (Tino Dai) Date: Tue, 29 Jun 2010 12:26:49 -0400 Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: References: <590411.35767.qm@web23606.mail.ird.yahoo.com> Message-ID: > > I decided to go with Regular Expressions to modify the text. In the >> Python.org it is stated that they provide more options and flexibilty >> compared to strings and their modules. >> > > "their modules" referring to the "string" module and the string methods > here, I assume. > > Regular expressions are also a lot harder to read and get right, you'll > see. They are an important tool in a programmers toolbox, so it's good to > learn them, but it's also good to know when *not* to use them. > > Khawla, Stefan is right. Regular expressions are tough especially for a beginner. The spiderman quote comes to mind: With great power, comes great responsibility. Check this article for some background on regex. http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Jun 29 18:32:29 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 29 Jun 2010 12:32:29 -0400 Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: References: <590411.35767.qm@web23606.mail.ird.yahoo.com> Message-ID: On Tue, Jun 29, 2010 at 12:26 PM, Tino Dai wrote: > > >> I decided to go with Regular Expressions to modify the text. In the >>> Python.org it is stated that they provide more options and flexibilty >>> compared to strings and their modules. >>> >> >> "their modules" referring to the "string" module and the string methods >> here, I assume. >> >> Regular expressions are also a lot harder to read and get right, you'll >> see. They are an important tool in a programmers toolbox, so it's good to >> learn them, but it's also good to know when *not* to use them. >> >> > Khawla, > > Stefan is right. Regular expressions are tough especially for a > beginner. The spiderman quote comes to mind: With great power, comes great > responsibility. Check this article for some background on regex. > > > http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html > > -Tino > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > google crawling web pages in python I did a quick check and there are some tutorials. I agree with above -- if you are new to programming, the last thing you need to tackle first are regular expressions! -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Jun 29 18:56:30 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 29 Jun 2010 12:56:30 -0400 Subject: [Tutor] Suggestions for output on multiple platforms In-Reply-To: <20100629202623.4ad93053@midgel> References: <20100629202623.4ad93053@midgel> Message-ID: On Tue, Jun 29, 2010 at 8:26 AM, Thomas C. Hicks wrote: > I am a beginner at all this and never expected to reach a point where > people other than myself may have to have access to the output of one > of my programs. My problem is this - I have written a program that > uses xlrd to read a series of xls files and collate and summarize the > data. My original plan was to then write out that data into another > xlwt spreadsheet that could be updated on a regular basis. I was > thinking of adding a page per month as the data is updated regularly. > > The problem is that xlwt doesn't allow for very convenient addition of > data to a spreadsheet - basically it has to re-create the whole > spreadsheet each time. > > So now I am looking for suggestions of how I can output my data > analysis. I am running Linux but the data needs to be able to be seen > by users of OSX and Windows. I have been reading about GTK and figure > I could output the analysis using that but am not sure it will be > readable under Mac and Windows. Any ideas are welcome! > > thomas > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I would write my output using csv (comma separated value) format (for which there are python tools). Put these files on a webserver, and create a webpage that you update with links to the csv files. If you don't have security concerns (eg an internal webserver) you could just put them in a directory and not create index.html file so that the listing of csv files would show -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jun 29 19:04:20 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 30 Jun 2010 03:04:20 +1000 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On 06/29/10 19:48, Richard D. Moores wrote: > On Tue, Jun 29, 2010 at 01:06, Alan Gauld wrote: >> "Richard D. Moores" wrote >> >>>> You log into Gmail and your browser downloads the Gmail page; >>> >>> Yes, of course. But I'm always logged into Gmail. >> >> But it is still continually downloading. The same applies to a >> desktop client, if you leave it running it can continually poll the >> server, just like gmail. > > Well, as I said, I found having Eudora do that was quite annoying (I'm > afraid I've forgotten the particulars). Gmail is not. In any event, > There are many, many reasons to choose to use Gmail over Eudora or OE > and their ilk. What makes you think what Eudora did and what rich web clients (e.g. gmail's web interface) did is any different? Gmail's rich AJAX-ful web client is almost the same as a full-fledged desktop client, except that it runs on Javascript in a browser instead of running as native code in the OS. BOTH do polls in intervals (or in case of IMAP with idle extension, wait for a push event), BOTH do download headers only or header+body only when requested, BOTH do client-side caching. Except that a rich webmail client, due to limitation by browser security, is inherently unable to do permanent caching; is much less configurable for its downloading preference; and is totally unconfigurable on polling interval. The advantages of desktop client is configurability and its caching mechanism is not constrained by browser security. The advantage of a rich webmail client is tighter coupling to the backend system and universal accessibility. From breamoreboy at yahoo.co.uk Tue Jun 29 23:16:25 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 29 Jun 2010 22:16:25 +0100 Subject: [Tutor] retrieve URLs and text from web pages In-Reply-To: References: <590411.35767.qm@web23606.mail.ird.yahoo.com> Message-ID: On 29/06/2010 17:32, Joel Goldstick wrote: [big snips] It might not be completely relevant, but there is nothing to stop anybody mixing regex and/or string methods. Horses for courses? Kindest regards. Mark Lawrence. From smokefloat at gmail.com Wed Jun 30 03:53:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Tue, 29 Jun 2010 21:53:24 -0400 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: On Tue, Jun 29, 2010 at 11:11 AM, Alan Gauld wrote: > "David Hutto" wrote > >> > Or if the network is shared with other users or other applications >> >> So, the bandwidth supplied(better question for my own ISP) is like a >> drop cord, even with alleged T1 connections plugged in, it drop in >> accordance with usage that exceeds the max capacity even though they >> sell it as it's max capacity?. > > It depends on the access mechanism. If its a T1 link then it is a > dedicated line for your own use and not shared by anyone - although > the server/router its connected to at the ISP may well be! > > If its a typical ADSL line it will be conneced to a DSLAM at the > centeral office(by the telco) and ?that will be shareed. So a typical > consumer line has a ratio of 50:1 users. A business line might be > only 10:1 or 20:1. This works on the assumption that most users > spend more time reading than downooading the content. As we > move to streaming data sources that assumption becomes invalid > and the DSLAM bandwidth is effectively shared. > > ADSL also loses bandwidth the further you are from the office so what > is sold as an 8Mb line will rarely give more than 5-6Mb and may be > as low as 1 or 2. But that is mostly a physical limitation on the > copper cables used. And finally, the 'A' in ADSL stands for asymmetric > so the upload speed it usually only a fraction of the download speed, > often only a few hundred kilobits/sec. Even with ADSL+ (20M+) the > upload speed is usually less than 1Mb. That means that a 1MB(yte) > document may only take 1-2 sec to download but take 10s+ to > upload (why sending mail is usually much slower than receiving) > > Alan G. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > But the process has to be diversified for each customer, because it all travels at the speed of light. I recall from way back in the day, that cable boxes sometimes had a weak signal depending on the distance from the consumer. This signal could be modified from the cable company, so the box amplified the 'weak', but not further away, signal. So this would also be a matter of what was being sent/received being modified, depending on the priority(given by the ISP provider) of the current DSL(or whatever connection) consumer? So I'm guessing this would be determined on the basis of recent usage, as to the priority of the sending or downloading, correct? From amartin7211 at gmail.com Wed Jun 30 07:35:10 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Wed, 30 Jun 2010 01:35:10 -0400 Subject: [Tutor] Problems installing Message-ID: I just downloaded Python 2.6.5 onto my windows vista laptop. I am attempting to install "escript version 3: Solution of Partial Differential Equations (PDE) using Finite Elements (FEM)." I downloaded the files and manually placed them in their appropriately place on my computer according to the ReadMe file. However, when I try to import escript, I get an error: >>> import esys.escript Traceback (most recent call last): File "", line 1, in import esys.escript ImportError: Bad magic number in C:\Python26\lib\site-packages\esys\escript\__init__.pyc >>> Can anybody lend me a hand? Thanks, amartin7211 -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Jun 30 08:30:10 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 29 Jun 2010 23:30:10 -0700 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: On Tue, Jun 29, 2010 at 10:35 PM, Andrew Martin wrote: > I just downloaded Python 2.6.5 onto my windows vista laptop. I am > attempting to install "escript version 3: Solution of Partial Differential > Equations (PDE) using Finite Elements (FEM)." I downloaded the files and > manually placed them in their appropriately place on my computer according > to the ReadMe file. However, when I try to import escript, I get an error: > > >>> import esys.escript > > Traceback (most recent call last): > File "", line 1, in > import esys.escript > ImportError: Bad magic number in > C:\Python26\lib\site-packages\esys\escript\__init__.pyc > >>> > > Can anybody lend me a hand? > > I don't know anything about escript, I'm afraid, but try this - .pyc files are always replaceable, as long as the .py or .pyw files they correspond to still exist. So delete __init__.pyc (I'm assuming that there's also a __init__.py file) and try again. Of course, this is only a solution if the problem is a corrupt .pyc file, which I've run into on a couple of occasions. If it's something else... Hope that helps. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From amartin7211 at gmail.com Wed Jun 30 08:39:25 2010 From: amartin7211 at gmail.com (Andrew Martin) Date: Wed, 30 Jun 2010 02:39:25 -0400 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: How exactly can I go about deleting __init__.pyc? Sorry, I am new to this so I need everything spelled out for me. On Wed, Jun 30, 2010 at 2:30 AM, Marc Tompkins wrote: > On Tue, Jun 29, 2010 at 10:35 PM, Andrew Martin wrote: > >> I just downloaded Python 2.6.5 onto my windows vista laptop. I am >> attempting to install "escript version 3: Solution of Partial Differential >> Equations (PDE) using Finite Elements (FEM)." I downloaded the files and >> manually placed them in their appropriately place on my computer according >> to the ReadMe file. However, when I try to import escript, I get an error: >> >> >>> import esys.escript >> >> Traceback (most recent call last): >> File "", line 1, in >> import esys.escript >> ImportError: Bad magic number in >> C:\Python26\lib\site-packages\esys\escript\__init__.pyc >> >>> >> >> Can anybody lend me a hand? >> >> I don't know anything about escript, I'm afraid, but try this - .pyc > files are always replaceable, as long as the .py or .pyw files they > correspond to still exist. So delete __init__.pyc (I'm assuming that > there's also a __init__.py file) and try again. > > Of course, this is only a solution if the problem is a corrupt .pyc file, > which I've run into on a couple of occasions. If it's something else... > > Hope that helps. > > -- > www.fsrtechnologies.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zubin.mithra at gmail.com Wed Jun 30 08:42:37 2010 From: zubin.mithra at gmail.com (Zubin Mithra) Date: Wed, 30 Jun 2010 12:12:37 +0530 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: On Wed, Jun 30, 2010 at 12:09 PM, Andrew Martin wrote: > How exactly can I go about deleting __init__.pyc? Sorry, I am new to this > so I need everything spelled out for me. > Go the the C:\Python26\lib\site-packages\esys\escript\ directory and delete it manually. :) > On Wed, Jun 30, 2010 at 2:30 AM, Marc Tompkins wrote: > >> On Tue, Jun 29, 2010 at 10:35 PM, Andrew Martin wrote: >> >>> I just downloaded Python 2.6.5 onto my windows vista laptop. I am >>> attempting to install "escript version 3: Solution of Partial Differential >>> Equations (PDE) using Finite Elements (FEM)." I downloaded the files and >>> manually placed them in their appropriately place on my computer according >>> to the ReadMe file. However, when I try to import escript, I get an error: >>> >>> >>> import esys.escript >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> import esys.escript >>> ImportError: Bad magic number in >>> C:\Python26\lib\site-packages\esys\escript\__init__.pyc >>> >>> >>> >>> Can anybody lend me a hand? >>> >>> I don't know anything about escript, I'm afraid, but try this - .pyc >> files are always replaceable, as long as the .py or .pyw files they >> correspond to still exist. So delete __init__.pyc (I'm assuming that >> there's also a __init__.py file) and try again. >> >> Of course, this is only a solution if the problem is a corrupt .pyc file, >> which I've run into on a couple of occasions. If it's something else... >> >> Hope that helps. >> >> -- >> www.fsrtechnologies.com >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 30 09:06:35 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 30 Jun 2010 00:06:35 -0700 (PDT) Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> Message-ID: <989021.79108.qm@web86706.mail.ird.yahoo.com> > > If its a typical ADSL line it will be conneced to a DSLAM at > > the centeral office(by the telco) and that will be shareed. > > > ADSL also loses bandwidth the further you are from the office > process has to be diversified for each customer, because it > all travels at the speed of light. It is diversified on the individual line leading to your house but it is shared from wherever it gets converted to a digital multiplex. That could be at the roadside cabinet or at the central office. At that point the data is mixed together using a round-robin type algorithm. The more active signals that are present the lower the proportion of the total bandwidth available to each. The speed of transmission is not really relevant (it only affects transit time not bandwidth) although it is as you say the speed of light (but not the speed of light in a vacuum, much lower than that) within the bearer. However within the electronics the signal travels more slowly - around the speed of sound - but fortunately for very small distances. > sometimes had a weak signal depending on the distance > from the consumer. This signal could be modified from the cable > company, so the box amplified the 'weak', but not further away, > signal. Its not a matter of signal strength but of signal smearing as it travels along the line. The digital data is sent as pulses (a great simplification!) but those pulses lose their shape as they travel along the line until eventually the electronics cannot distinguish one from another. The only way to improve is to send the pulses more widely spaced, which reduces the bandwidth, or to have repeater boxes which regenerate the pulses at regular intervals. On long distance routes, between cities, the telco will install repeaters but for domestic use they progressively reduce the bandwidth. > So this would also be a matter of what was being sent/received > being modified, depending on the priority (given by the ISP provider) > of the current DSL (or whatever connection) consumer? No, it doesn't matter what priority the comnsumer has it is down to the physical characteristics of the line. Telcos typically use copper or aluminium conductors in the local lines with paper or PTFE insulation and either crimped, twisted or soldered joints. All of these affect the transmission characteristics but the biggest factor is the length of the line. Its not economical to install repeaters in every consumer line so the bandwidth must be adjusted to match what the line is capable of. (This is done dynamically so you may even find your bandwidth varies slightly depending on the weather!) In practice it should be fairly stable and the biggest variations will be due to contention at the DSLAM. HTH, Alan G. (Who works for a telco! :-) From lang at tharin.com Wed Jun 30 09:20:51 2010 From: lang at tharin.com (Lang Hurst) Date: Wed, 30 Jun 2010 00:20:51 -0700 Subject: [Tutor] togglebutton mouseover Message-ID: <4C2AF053.7090504@tharin.com> Is there a way to make a ToggleButton not change state when moused over? I set the color of the button when clicked with a line like so: widget.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("light blue")) That works fine. On and off. Although you can't tell it's clicked until the mouse passes off of the button. In addition, when the mouse cursor passes over this button, it reverts to the unclicked gray color, until the mouse passes back off the button. If possible, I would like to have the button only change when clicked. The default seems very poor. Thanks -- There are no stupid questions, just stupid people. From steve at pearwood.info Wed Jun 30 12:18:02 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Jun 2010 20:18:02 +1000 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: <201006302018.03064.steve@pearwood.info> On Wed, 30 Jun 2010 03:35:10 pm Andrew Martin wrote: > I just downloaded Python 2.6.5 onto my windows vista laptop. I am > attempting to install "escript version 3: Solution of Partial > Differential Equations (PDE) using Finite Elements (FEM)." I > downloaded the files and manually placed them in their appropriately > place on my computer according to the > ReadMe file. However, when I try to import escript, I get an error: > >>> import esys.escript > > Traceback (most recent call last): > File "", line 1, in > import esys.escript > ImportError: Bad magic number in > C:\Python26\lib\site-packages\esys\escript\__init__.pyc Is it possible that esys only provides compiled .pyc files, and that for a different version of Python? If the .py file (source code) is there, Python *should* automatically delete the .pyc file (byte code) and re-compile it from the .py file. But if there is no .py file, then Python is stuck with using only the pre-compiled .pyc file, but it needs to have been compiled for the same version of Python. You can't have Python 2.6 run a .pyc file from 2.5 or 3.1 (say). The "magic number" is there to declare the version of Python used. -- Steven D'Aprano From smokefloat at gmail.com Wed Jun 30 16:03:35 2010 From: smokefloat at gmail.com (David Hutto) Date: Wed, 30 Jun 2010 10:03:35 -0400 Subject: [Tutor] OT: need computer advice from wise Tutors In-Reply-To: <989021.79108.qm@web86706.mail.ird.yahoo.com> References: <201006280925.57933.steve@pearwood.info> <201006291032.06481.steve@pearwood.info> <989021.79108.qm@web86706.mail.ird.yahoo.com> Message-ID: On Wed, Jun 30, 2010 at 3:06 AM, ALAN GAULD wrote: > > >> > If its a typical ADSL line it will be conneced to a DSLAM at >> > the centeral office(by the telco) and ?that will be shareed. >> >> > ADSL also loses bandwidth the further you are from the office > >> process has to be diversified for each customer, because it >> all travels at the speed of light. > > It is diversified on the individual line leading to your house > but it is shared from wherever it gets converted to a digital > multiplex. That could be at the roadside cabinet or at the > central office. At that point the data is mixed together > using a round-robin type algorithm. The more active signals > that are present the lower the proportion of the total bandwidth > available to each. > > The speed of transmission is not really relevant (it only affects > transit time not bandwidth) although it is as you say the > speed of light (but not the speed of light in a vacuum, much > lower than that) within the bearer. However within the electronics > the signal travels more slowly - around the speed of sound - but > fortunately for very small distances. > >> sometimes had a weak signal depending on the distance >> from the consumer. This signal could be modified from the cable >> company, so the box amplified the 'weak', but not further away, >> signal. > > Its not a matter of signal strength but of signal smearing as it > travels along the line. The digital data is sent as pulses (a great > simplification!) but those pulses lose their shape as they travel > along the line until eventually the electronics cannot distinguish > one from another. The only way to improve is to send the > pulses more widely spaced, which reduces the bandwidth, > or to have repeater boxes which regenerate the pulses at > regular intervals. On long distance routes, between cities, the > telco will install repeaters but for domestic use they progressively > reduce the bandwidth. > >> So this would also be a matter of what was being sent/received >> being modified, depending on the priority (given by the ISP provider) >> of the current DSL (or whatever connection) consumer? > > No, it doesn't matter what priority the comnsumer has it is down > to the physical characteristics of the line. Telcos typically use > copper or aluminium conductors in the local lines with paper > or PTFE insulation and either crimped, twisted or soldered joints. > All of these affect the transmission characteristics but the biggest > factor is the length of the line. Its not economical to install > repeaters in every consumer line so the bandwidth must be > adjusted to match what the line is capable of. (This is done > dynamically so you may even find your bandwidth varies slightly > depending on the weather!) In practice it should be fairly stable > and the biggest variations will be due to contention at the > DSLAM. > > HTH, > > Alan G. > (Who works for a telco! :-) > > Thanks for taking the time to answer, and sorry for somewhat hijacking the op's thread. From a.pringles.can at gmail.com Wed Jun 30 18:20:16 2010 From: a.pringles.can at gmail.com (Aaron Chambers) Date: Wed, 30 Jun 2010 12:20:16 -0400 Subject: [Tutor] (no subject) Message-ID: I'm new to Python, and wanted to start messing around with it, but the computer I'm using is running Windows 7, so is there a version of Python that's compatible with 7? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Jun 30 18:28:05 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Jun 2010 17:28:05 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4C2B7095.6090404@timgolden.me.uk> On 30/06/2010 17:20, Aaron Chambers wrote: > I'm new to Python, and wanted to start messing around with it, but the > computer I'm using is running Windows 7, so is there a version of Python > that's compatible with 7? Yes. I'm running versions from Python 2.1 all the way up to the latest 2.x and 3.x Subversion releases. Take your pick ---> http://python.org/download/ TJG From lie.1296 at gmail.com Wed Jun 30 18:24:55 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 01 Jul 2010 02:24:55 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 07/01/10 02:20, Aaron Chambers wrote: > I'm new to Python, and wanted to start messing around with it, but the > computer I'm using is running Windows 7, so is there a version of Python > that's compatible with 7? Yes. From malaclypse2 at gmail.com Wed Jun 30 20:03:43 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 30 Jun 2010 14:03:43 -0400 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: On Wed, Jun 30, 2010 at 1:35 AM, Andrew Martin wrote: > I just downloaded Python 2.6.5 onto my windows vista laptop. I am > attempting to install "escript version 3: Solution of Partial Differential > Equations (PDE) using Finite Elements (FEM)." I downloaded the files and > manually placed them in their appropriately place on my computer according > to the ReadMe file. However, when I try to import escript, I get an error: > I know nothing about escript, but according to the install doc on https://launchpad.net/escript-finley/, it requires python 2.5.4. The distribution appears to consist entirely of .pyc files, so I think you need to install the version of python that it requires. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 30 21:33:28 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Jun 2010 20:33:28 +0100 Subject: [Tutor] (no subject) References: Message-ID: "Aaron Chambers" wrote in message news:AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35 at mail.gmail.com... > I'm new to Python, and wanted to start messing around with it, but > the > computer I'm using is running Windows 7, so is there a version of > Python > that's compatible with 7? Yes, and I would recommend you get yours from the Activestate.com web site rather than python.org since the Activestate version is much more Windows friendly. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marris1031 at gmail.com Wed Jun 30 21:52:50 2010 From: marris1031 at gmail.com (Mary Morris) Date: Wed, 30 Jun 2010 13:52:50 -0600 Subject: [Tutor] Decorators Message-ID: I need help with the following task for my new job: The code we're using is python, which I have never worked with before. Our AMS source code relies heavily on decorators.Things look something like this: @decomaker(argA, argB, ...) def func(arg1, arg2, ...): pass which is the same as func = decomaker(argA, argB, ...)(func) and @dec2 @dec1 def func(arg1, arg2, ...): pass func = dec2(dec1(func)) Or when implemented the second example looks like: def dec1(func): def new_func(arg1, arg2, ...): ... do something... ret = func(arg1, arg 2, ...) ... do more things... return ret return new_func My first task is that there is an issue with the name new_func. When the program crashes, that is what shows up in the logs-which doesn't help debug anything. I need to find out every decorator and make sure it has a descriptive name. I was thinking I could write a simple script which would parse through all of the source files and find decorators-maybe by looking for the @ symbol? Then I could manually check to make sure it has a good name. I was thinking I could copy the searching code from find_imports.py (up to the startswith() calls) and print the list of decorators found and which files that they're in. I have never worked with python before so I definitely need help with this task-any suggestions or examples that would be helpful? -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Wed Jun 30 22:10:40 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 30 Jun 2010 22:10:40 +0200 Subject: [Tutor] Problems installing In-Reply-To: References: Message-ID: <3C5FEF66-47E9-4FE8-9911-EA0A93A1090A@gmail.com> > I just downloaded Python 2.6.5 onto my windows vista laptop. I am attempting to install "escript version 3: Solution of Partial Differential Equations (PDE) using Finite Elements (FEM)." I downloaded the files and manually placed them in their appropriately place on my computer according to the ReadMe file. However, when I try to import escript, I get an error: > > I know nothing about escript, but according to the install doc on https://launchpad.net/escript-finley/, it requires python 2.5.4. The distribution appears to consist entirely of .pyc files, so I think you need to install the version of python that it requires. There is a source distribution that has the *.py files, but looking at the dependencies, that's not going to be easy to install. Then again, the webpage claims the third party software includes Python. So your system picks up Python 2.6 (which is the default), but escript does actually include Python, presumably 2.5. So somehow, you'll need to setup your system that it picks up the correct Python. Or rather, find that Python in the escript installation (I have no idea how it's installed, so can't tell you where to look), and use that Python instead when import escript. What files did you download? Since you said you manually installed them in the correct places; that could/should have included Python. From hugo.yoshi at gmail.com Wed Jun 30 22:30:02 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 30 Jun 2010 22:30:02 +0200 Subject: [Tutor] Decorators In-Reply-To: References: Message-ID: On Wed, Jun 30, 2010 at 9:52 PM, Mary Morris wrote: > I need help with the following task for my new job: > The code we're using is python, which I have never worked with before. > Our AMS source code relies heavily on decorators.Things look something like > this: > @decomaker(argA, argB, ...) > def func(arg1, arg2, ...): > ?? ? pass > which is the same as > func = decomaker(argA, argB, ...)(func) > and > @dec2 > @dec1 > def func(arg1, arg2, ...): > ?? ? pass > func = dec2(dec1(func)) > Or when implemented the second example looks like: > def dec1(func): > ?? ? def new_func(arg1, arg2, ...): > ?? ? ? ? ?... do something... > ?? ? ? ? ?ret = func(arg1, arg 2, ...) > ?? ? ? ? ?... ?do more things... > ?? ? ? ? ?return ret > ?? ? return new_func > > My first task is that there is an issue with the name new_func. ?When the > program crashes, that is what shows up in the logs-which doesn't help debug > anything. ?I need to find out every decorator and make sure it has a > descriptive name. ?I was thinking I could write a simple script which would > parse through all of the source files and find decorators-maybe by looking > for the @ symbol? ?Then I could manually check to make sure it has a good > name. ?I was thinking I could copy the searching code from find_imports.py > (up to the startswith() calls) and print the list of decorators found and > which files that they're in. ?I have never worked with python before so I > definitely need help with this task-any suggestions or examples that would > be helpful? The functools library has a function, called wraps, that makes sure any decorated function maintains its original name and docstring. You use it inside your decorator functions, like so: from functools import wraps def decorator(func): @wraps(func) def new_func(*args, **kwargs): #do some stuff return new_func @decorator def wrapped_func(a, b): """this docstring will be saved, and if the function crashes, it will show up as 'wrapped_func' in your tracebacks""" # do some other stuff HTH, Hugo From lang at tharin.com Wed Jun 30 22:42:54 2010 From: lang at tharin.com (Lang Hurst) Date: Wed, 30 Jun 2010 13:42:54 -0700 Subject: [Tutor] togglebutton mouseover In-Reply-To: <4C2AF053.7090504@tharin.com> References: <4C2AF053.7090504@tharin.com> Message-ID: <4C2BAC4E.90704@tharin.com> Sorry, I just realized I posted this to the wrong list. On 06/30/2010 12:20 AM, Lang Hurst wrote: > Is there a way to make a ToggleButton not change state when moused > over? I set the color of the button when clicked with a line like so: > > widget.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("light blue")) > > That works fine. On and off. Although you can't tell it's clicked > until the mouse passes off of the button. In addition, when the mouse > cursor passes over this button, it reverts to the unclicked gray > color, until the mouse passes back off the button. If possible, I > would like to have the button only change when clicked. The default > seems very poor. > > Thanks > -- There are no stupid questions, just stupid people. From marris1031 at gmail.com Wed Jun 30 23:12:30 2010 From: marris1031 at gmail.com (Mary Morris) Date: Wed, 30 Jun 2010 15:12:30 -0600 Subject: [Tutor] Decorators revised Message-ID: I need help with the following task for my new job: The code we're using is written in python, which I have never worked with before. Our AMS source code relies heavily on decorators.Things look something like this: @decomaker(argA, argB, ...) def func(arg1, arg2, ...): pass which is the same as func = decomaker(argA, argB, ...)(func) and @dec2 @dec1 def func(arg1, arg2, ...): pass func = dec2(dec1(func)) Or when implemented the second example looks like: def dec1(func): def new_func(arg1, arg2, ...): ... do something... ret = func(arg1, arg 2, ...) ... do more things... return ret return new_func My first task is that there is an issue with the name new_func. When the program crashes, that is what shows up in the logs-which doesn't help debug anything. I need to find out every decorator and make sure it has a descriptive name. I was thinking I could write a simple script which would parse through all of the source files and find decorators-maybe by looking for the @ symbol? Then I could manually check to make sure it has a good name. I was thinking I could copy the searching code from find_imports.py (up to the startswith() calls) and print the list of decorators found and which files that they're in. What I want to do is use a find() for the @dec maybe.... I also don't know how to parse out everything that's not the name- at dec(arg1, arg2) should be "dec". I have never worked with python before so I definitely need help with this task-any suggestions or examples that would be helpful? -------------- next part -------------- An HTML attachment was scrubbed... URL: