From alan.gauld at freenet.co.uk Wed Jun 1 00:08:16 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 31 May 2005 23:08:16 +0100 Subject: [Tutor] Planning a program with algorithm? References: Message-ID: <005c01c5662d$3f64f6b0$42c98751@xp> > And I'm doing chapter4. In the book it says it's recommended to plan a prog. > with pseudocode. > > Can i just ignore it? No, pseudo code is a very powerful technique. But one of the guidelines is that every line of pseudocode should correspond to 5-10 lines of program code (which means that it depends on the language used of course - one of its weaknesses since pseudocode intended for C programmers is not of much benefit to a Python programmer!) Since anything less than about 5-10 lines of pseudoccode is pretty much pointless that means that pseudocode comes into its own when your programs get to around 30 lines of Python or bigger. Practice using psudocode in shorter programs by all means but it won't be very useful unil you start to write bigger programs. By the time your programs are several hundreds of lines long and spread over several files psueudocode becomes a very powerful techniqie of seeing the "big picture" of your programs structure. Once you get above 500-1000 lines pseudo code starts to break down again - you need pseudo code for your pseudo code!! At this point you need to start looking at higher level design techniques including diagramming tools. Alan G. From alan.gauld at freenet.co.uk Wed Jun 1 00:11:04 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 31 May 2005 23:11:04 +0100 Subject: [Tutor] Planning a program with algorithm? References: Message-ID: <006101c5662d$a3bef750$42c98751@xp> > One approach you could consider is to write pseudocode, turn it into comments > and write the real code in between those. That way you get the benefits of > pseudocode (being able to spot algorithm errors at a higher level) as well as > properly commented code. Difficult portions then automatically get more > comments, while easier portions get fewer comments - just as it should be. And this is exactly what we do at work in large projects. Because pseudo code sits at the 5-10 lines of real code level it works well as comment text regardless of language and you can extract the detailed design from the code using a simple text filter like grep... The ISO 9000 quality auditors love it... Alan G. From alan.gauld at freenet.co.uk Wed Jun 1 00:14:26 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 31 May 2005 23:14:26 +0100 Subject: [Tutor] Planning a program with algorithm? References: Message-ID: <006801c5662e$1bd4d930$42c98751@xp> > The textbook "How to Design Programs" focuses on a design approach to > program construction. The book's host language is Scheme, but I feel a > lot of the material is language agnostic and valuable to any programmer: > > http://www.htdp.org > I second the recommendation, but you do have to remember to ignore the heavy use of recursion if you are working in Python. Otherwise the basic concepts are very sound. And the formulistic approach to designing a function is excellent. Alan G. From denise.hartley at gmail.com Wed Jun 1 00:28:48 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 31 May 2005 15:28:48 -0700 Subject: [Tutor] Variations on putpixel - More Pixel manipulation - #14 In-Reply-To: <60987dac050531142732b19cf5@mail.gmail.com> References: <8daabe56050531141177e08c78@mail.gmail.com> <60987dac050531142732b19cf5@mail.gmail.com> Message-ID: <8daabe5605053115281d9617d6@mail.gmail.com> Rudy, I have the im.getpixel incrementing at every pixel by i (in a for loop for each pixel in wire.png), and I know incrementing the xy in the new one goes like this: x + 1 y + 1 x - 1 x - 1 y - 1 y - 1 x + 1 x + 1 x + 1 ... etc First the x and then the y is incremented by 1, then that 1 is made negative and the # of times += 1. then, back around, then the 1 is made positive again, and so on. But how can I increment a changing "to_coordinate" variable in this weird way each time while still only incrementing the "from_coordinate" by 1 in a for loop? I keep trying to set up my function and only being able to change one or the other at a time! I apologize if my question seems elementary, I am still rather new at this :) ~Denise On 5/31/05, Rudy Schockaert wrote: > import Image # PIL > im = Image.open(r'd:\riddle\wire.png') > im1=Image.new(im.mode,(100,100)) > ..... > im1.putpixel((x,yl),im.getpixel((p,0))) > .... > > Trying not to spoil all the fun > > > On 5/31/05, D. Hartley wrote: > > > > Hello, everyone! > > > > I know you didn't expect to hear from me anymore about these pesky > > challenges, since I started the off-tutor list about it, but I'm > > afraid I'm stuck and cannot get a hint. > > > > If I want to rearrange a long string of pixels in a different order, > > using "putpixel" with a certain size new image (in this case, 100x100) > > will take the long string of pixels, fill the first line of the new > > image, and then more or less "carriage return" to fill the next line > > from the left to the right. > > > > Does anyone know a different way to .... put.. pixels? > > > > (Again, this *is* for the python challenges, if anyone has passed this > point). > > > > Thanks, and sorry for bringing this back into the list! > > > > ~Denise > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > "Don't you wish there were a knob on the TV to turn up the intelligence? > There's one marked 'Brightness,' but it doesn't work." - Gallagher From rmkrauter at yahoo.com Wed Jun 1 01:04:51 2005 From: rmkrauter at yahoo.com (Rich Krauter) Date: Tue, 31 May 2005 19:04:51 -0400 Subject: [Tutor] ftplib: retrbinary all files in directory In-Reply-To: <35D8A7DE4D78AF4AB3CD455CF6085DFF08550F@CIXMX1.compxnet.com> References: <35D8A7DE4D78AF4AB3CD455CF6085DFF08550F@CIXMX1.compxnet.com> Message-ID: <429CED93.5090609@yahoo.com> Israel Carr wrote: > I'm using ftplib to connect to a server, and I want to grab every file > from a specific folder. The filenames change frequently. What is the > best way to use retrbinary with wildcards(or some better option) to > transfer all files? > > Thanks, > Israel > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You can try ftpmirror.py, which is included with python. From http://docs.python.org/lib/module-ftplib.html: """ The file Tools/scripts/ftpmirror.py in the Python source distribution is a script that can mirror FTP sites, or portions thereof, using the ftplib module. It can be used as an extended example that applies this module. """ Good luck. Rich From andre.roberge at gmail.com Wed Jun 1 03:09:07 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Tue, 31 May 2005 22:09:07 -0300 Subject: [Tutor] ANN: Version 0.9 of RUR-PLE Message-ID: Version 0.9 of RUR: a Python Learning Environment has been released. Information about RUR-PLE can be obtained at http://rur-ple.sourceforge.net Note that the project website is slightly out of date. Among the changes in this new version: ***Spanish translation added.* Changed image for language selection to reflect addition. Changed directory structure of lessons. Fixed "non-existent file" problem when changing language with unstranslated lesson file open in browser; the browser will open the default file in the chosen language instead. Changed dialogs (beepers to robot and resize world) to use GridBagSizer for layout as opposed to specific coordinates. Added parameter wx.BUFFER_VIRTUAL_AREA in dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA) in world_display.py; this is required to get proper scrolling since wxPython 2.5.4.1. Added SetFocus() when positioning sizer on "Robot: code and learn" page. This gets rid of the unwanted grey background. Changed list of beepers that can be placed at an intersection from 0 ... 15, 16, 17, 18, 19, 20 to 0 ... 15, 20, 40, 60, 80, 99. Removed the "from __future__ import division" command to the interpreter. Since this is not likely to be the default version for a *long* time, it seems a better idea to revert to the default behaviour for the interpreter. TODO: The lesson needs to be updated to reflect this change. World redrawn immediately after selecting a new language, so that the words "streets" and "avenues" are updated right away. Corrected tooltip language setting on speed selection slider. Added possibility to change background colour of robot world through user program. This is to be used in the random maze escape lesson. Changed the 20 robot images so that their background is transparent. Removed obsolete self-testing code in various files as well as redundant import statements. Fixed problem with seemingly random "invalid world file" error. This occured when a robot was removed from the world, and an attempt was made at resetting the world. Added SetFocus() to WorldGui.OnLeftDown(). Somehow, the WorldGUI (i.e. robot world) would no longer get focus as a matter of course when left-clicked. This meant that it was no longer possible to position the robot using the cursor keys. This problem has appeared since I made the switch to wxPython 2.6. From kent37 at tds.net Wed Jun 1 06:05:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Jun 2005 00:05:56 -0400 Subject: [Tutor] ftplib: retrbinary all files in directory In-Reply-To: <429CED93.5090609@yahoo.com> References: <35D8A7DE4D78AF4AB3CD455CF6085DFF08550F@CIXMX1.compxnet.com> <429CED93.5090609@yahoo.com> Message-ID: <429D3424.1010306@tds.net> Rich Krauter wrote: > Israel Carr wrote: > >>I'm using ftplib to connect to a server, and I want to grab every file >>from a specific folder. The filenames change frequently. What is the >>best way to use retrbinary with wildcards(or some better option) to >>transfer all files? >> >>Thanks, >>Israel >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > You can try ftpmirror.py, which is included with python. If you look at line 126 of ftpmirror.py you will see how it uses retrlines('LIST') to retrieve and parse the remote directory. Kent From kent37 at tds.net Wed Jun 1 12:04:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Jun 2005 06:04:07 -0400 Subject: [Tutor] Variations on putpixel - More Pixel manipulation - #14 In-Reply-To: <8daabe5605053115281d9617d6@mail.gmail.com> References: <8daabe56050531141177e08c78@mail.gmail.com> <60987dac050531142732b19cf5@mail.gmail.com> <8daabe5605053115281d9617d6@mail.gmail.com> Message-ID: <429D8817.4010408@tds.net> D. Hartley wrote: > Rudy, > I have the im.getpixel incrementing at every pixel by i (in a for loop > for each pixel in wire.png), and I know incrementing the xy in the new > one goes like this: > > x + 1 > y + 1 > x - 1 > x - 1 > y - 1 > y - 1 > x + 1 > x + 1 > x + 1 ... etc > > First the x and then the y is incremented by 1, then that 1 is made > negative and the # of times += 1. then, back around, then the 1 is > made positive again, and so on. > > But how can I increment a changing "to_coordinate" variable in this > weird way each time while still only incrementing the > "from_coordinate" by 1 in a for loop? I keep trying to set up my > function and only being able to change one or the other at a time! Denise, You are essentially trying to iterate two sequences at the same time. One is the simple sequence 0, 1, 2, 3, ...; the other is the more complex sequence of (x, y) pairs in the "to" coordinates. There are a couple of good ways to do this in Python. Suppose you have a loop that calculates and uses successive values of (x, y) based on some state and the previous values of x and y: x, y = initialX, initialY state = initialState while True: x, y, state = calculateXY(x, y, state) doSomething(x, y) Now suppose doSomething() needs another argument from the sequence 0, 1, .... One option is to add the calculations for the new sequence to the loop: x, y = initialX, initialY i = initialI state = initialState while True: x, y, state = calculateXY(x, y, state) i = calculateI(i) doSomething(x, y, i) What if i is actually coming from another sequence rather than being calculated? You can control iteration over a sequence by creating an explicit iterator and calling next() on it when you need a new element: x, y = initialX, initialY iIter = iter(iSequence) state = initialState while True: x, y, state = calculateXY(x, y, state) doSomething(x, y, iIter.next()) This works but it conflates three things - iteration over (x, y), iteration over iSequence, and proccessing of the triples (x, y, i). A nice way to break these apart is to create a generator function that yields (x, y) pairs: def generateXY(): x, y = initialX, initialY state = initialState while True: x, y, state = calculateXY(x, y, state) yield (x, y) Notice this is almost identical to the original loop; the call to doSomething() has been replaced by a yield. Calling generateXY creates a generator object which itself can be iterated. Now, with the help of zip(), you can easily iterate the (x, y) pairs and the iSequence elements together: for (x, y), i in zip(generateXY(), iSequence): doSomething(x, y, i) (Note the cool use of tuple unpacking too!) Kent From w.richert at gmx.net Wed Jun 1 13:16:37 2005 From: w.richert at gmx.net (Willi Richert) Date: Wed, 1 Jun 2005 13:16:37 +0200 Subject: [Tutor] Strange IndexError Message-ID: <200506011316.38559.w.richert@gmx.net> Hi, in my code I get in rare occasions an IndexError which is incomprehensible to me in that situation, where I do a simple comparison: NeedBrain.py:233: RuntimeWarning: tp_compare didn't return -1 or -2 for exception self._isNearMarker = self._markerDist < self.STAY_MIN_DIST Traceback (most recent call last): File "NeedBrain.py", line 233, in update self._isNearMarker = self._markerDist < self.STAY_MIN_DIST IndexError: tuple assignment index out of range I don't see, where tuples are involved. I only compare two floats. I've Python 2.3.4. Thanks, wr From mhansen at cso.atmel.com Wed Jun 1 16:51:06 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 01 Jun 2005 08:51:06 -0600 Subject: [Tutor] Planning a program with algorithm? In-Reply-To: References: Message-ID: <429DCB5A.7070008@cso.atmel.com> > ------------------------------------------------------------------------ > > Subject: > [Tutor] Planning a program with algorithm? > From: > ". ," > Date: > Sun, 29 May 2005 19:21:33 +0000 > To: > tutor at python.org > > To: > tutor at python.org > > > I know how to write a prog. > > But, I don't know how to plan a prog. with algorithm. [...] > > Any useful advice for algorithm would be appreciated. > > Thanks. You might want to take a look at the book Code Complete. It really covers the nuts and bolts of software construction. http://www.cc2e.com/ Mike From djennings3 at earthlink.net Wed Jun 1 17:37:59 2005 From: djennings3 at earthlink.net (Don Jennings) Date: Wed, 1 Jun 2005 11:37:59 -0400 Subject: [Tutor] securely transmitting data via email Message-ID: <21FD5349-D2B3-11D9-97B2-0003930ACB16@earthlink.net> Goal: to securely transmit data (collected on a form on a secure web site) to recipient Possible solutions, thus far: 1) create web page accessible through HTTPS; email link to recipient, BUT that adds extra steps for him. I'd like it to be as transparent as possible (doesn't everyone? ; >) 2) use cryptography directly in the python CGI program (e.g. ezPyCrypto or SSLCrypto) and email the results. I am assuming that I can import a public key created by PGP or GnuPG 3) os.popen (after sanitizing the input, of course) to use the command line interface of GnuPG to create an encrypted file and attaching that to an email Anyone have experience achieving this goal? Have I overlooked other options? Sample programs, maybe? Thanks! Don From jeffpeery at yahoo.com Wed Jun 1 18:21:06 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 1 Jun 2005 09:21:06 -0700 (PDT) Subject: [Tutor] IDLE not working? Message-ID: <20050601162106.37856.qmail@web30514.mail.mud.yahoo.com> Hello, I upgraded python to 2.4 and now my IDLE isn't working. There is an error indicating something is wrong with my configuration file for the IDLE settings. Any suggestions for how to solve this problem would be much appreciated. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050601/5e0880df/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Jun 1 19:09:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Jun 2005 10:09:50 -0700 (PDT) Subject: [Tutor] Strange IndexError In-Reply-To: <200506011316.38559.w.richert@gmx.net> Message-ID: On Wed, 1 Jun 2005, Willi Richert wrote: > in my code I get in rare occasions an IndexError which is > incomprehensible to me in that situation, where I do a simple > comparison: > > NeedBrain.py:233: RuntimeWarning: tp_compare didn't return -1 or -2 for > exception > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST Hi Willi, Hmmm! This actually looks very unusual. You should never see anything about 'tp_compare' unless you're dealing with a buggy C extension. > Traceback (most recent call last): > File "NeedBrain.py", line 233, in update > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST > IndexError: tuple assignment index out of range > > I don't see, where tuples are involved. I only compare two floats. I've > Python 2.3.4. Have you edited the program since the program started? It's very possible that the line numbers are wrong just because the program has changed in the meantime. But the warning before that talks about 'tp_compare' has me intrigued, as you should never see that error. If you don't mind, can you post your code up somewhere? Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Jun 1 19:13:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Jun 2005 10:13:17 -0700 (PDT) Subject: [Tutor] IDLE not working? In-Reply-To: <20050601162106.37856.qmail@web30514.mail.mud.yahoo.com> Message-ID: On Wed, 1 Jun 2005, Jeff Peery wrote: > Hello, I upgraded python to 2.4 and now my IDLE isn't working. There is > an error indicating something is wrong with my configuration file for > the IDLE settings. Any suggestions for how to solve this problem would > be much appreciated. thanks. Hi Jeff, This looks like bug 1080387 in SF: http://sourceforge.net/tracker/index.php?func=detail&aid=1080387&group_id=5470&atid=105470 It's also listed as a bug in the BUGS page: http://python.org/2.4/bugs.html Removing the '.idlerc' subdirectory in your home directory should force IDLE to restore default font settings. Best of wishes to you! From denise.hartley at gmail.com Wed Jun 1 19:34:30 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 1 Jun 2005 10:34:30 -0700 Subject: [Tutor] Variations on putpixel - More Pixel manipulation - #14 In-Reply-To: <429D8817.4010408@tds.net> References: <8daabe56050531141177e08c78@mail.gmail.com> <60987dac050531142732b19cf5@mail.gmail.com> <8daabe5605053115281d9617d6@mail.gmail.com> <429D8817.4010408@tds.net> Message-ID: <8daabe5605060110346c2c1bdc@mail.gmail.com> In working out the "two different iterations at once" part, I decided to do the following: function that creates a "tolist" (a list of coordinate-pair-tuples, incremented in the correct way to go around in the direction I want) and then a for loop to iterate one by one over the wire.png (the "fromlist"): for i in range(10000): newim.putpixel(tolist[i],im.getpixel((i,0))) So the first time through I should get my first "destination" pizel from tolist, and my first "fill-in" pixel (0,0) from wire.png. This part seems pretty ok. However, I think there must be a problem in my "tolist" creater function, because the picture it gave me, while completely filled in with pixels from wire.png, does not make anything recognizeable. (I am starting at the top left corner of the new image and filling in in a spiral - to the right, down, back left, up, and so on): def findtolist(): tolist = [(0,0)] x = 0 y = 0 inc = 1 numtimes = 100 while numtimes > 0: for i in range(numtimes-1): x += inc coord = (x,y) tolist.append(coord) for i in range(numtimes-1): y += inc coord = (x,y) tolist.append(coord) inc *= -1 numtimes -= 1 del tolist[10000:] return tolist However, the list that that function returns is only 9901 items long (although it DOES end where it should - at (50,50). What is going on? Where did those extra 99 pixels go? Would appreciate any ideas you have! Thanks again, Denise From denise.hartley at gmail.com Wed Jun 1 19:58:56 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 1 Jun 2005 10:58:56 -0700 Subject: [Tutor] Variations on putpixel - More Pixel manipulation - #14 In-Reply-To: <8daabe5605060110346c2c1bdc@mail.gmail.com> References: <8daabe56050531141177e08c78@mail.gmail.com> <60987dac050531142732b19cf5@mail.gmail.com> <8daabe5605053115281d9617d6@mail.gmail.com> <429D8817.4010408@tds.net> <8daabe5605060110346c2c1bdc@mail.gmail.com> Message-ID: <8daabe5605060110581a6017be@mail.gmail.com> Nevermind! Off by one. Man, that feels dumb! Thanks for your patience, everyone, and for all your hints! ~Denise From John.Gooch at echostar.com Wed Jun 1 21:00:41 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Wed, 1 Jun 2005 13:00:41 -0600 Subject: [Tutor] Win32 Question Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D437@riv-excha5.echostar.com> I am not sure if there is a better list to ask this question on, but here it is: I have a Python script that works fine for accessing WMI ( Windows Management Interface ) class properties, but it does not let me access any of their methods. The code below works fine with Win32_Process objects unless I try execute a method ( such as 'GetUser' ). Here is a link to Microsofts documentation ->http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wm i/wmi_tasks__processes.asp if that helps. Below is my code, the error I get on the 'GetOwner' line is - TypeError: 'int' object is not callable - : import threading import time import Queue #import ping #rom mx import ODBC import odbc import socket import re import win32com.client import win32api import win32con import win32file import pythoncom import datetime import os pythoncom.CoInitialize() #connect to localhost wmi service wmi = win32com.client.GetObject('winmgmts://' ) wtprocs = {}#create empty dictionary results = wmi.execQuery( "SELECT name,processid,usermodetime FROM WIN32_Process WHERE name='saclient.exe'" ) for process in results: #tsecs = int( float(process.KernelModeTime) + float(process.UserModeTime )/10000000 ) name = process.name pid = process.processid tsecs = int( float( process.UserModeTime )/10000000.00 ) #if ( tsecs >= 10800 ): #owner = os.system("c:\batch2000\kill.exe " + process.processid) owner = "" domain = "" this line causes the error given above -----> process.GetOwner() #apply( process.GetOwner ) print "Process %s (id %d owner %s ) has been running %d hours" % ( process.name,process.processid,owner,int(tsecs/3600) ) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo Sent: Wednesday, June 01, 2005 11:13 AM To: Jeff Peery Cc: tutor at python.org Subject: Re: [Tutor] IDLE not working? On Wed, 1 Jun 2005, Jeff Peery wrote: > Hello, I upgraded python to 2.4 and now my IDLE isn't working. There > is an error indicating something is wrong with my configuration file > for the IDLE settings. Any suggestions for how to solve this problem > would be much appreciated. thanks. Hi Jeff, This looks like bug 1080387 in SF: http://sourceforge.net/tracker/index.php?func=detail&aid=1080387&group_id=54 70&atid=105470 It's also listed as a bug in the BUGS page: http://python.org/2.4/bugs.html Removing the '.idlerc' subdirectory in your home directory should force IDLE to restore default font settings. Best of wishes to you! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From Connor.Smith at huntington.com Wed Jun 1 21:16:36 2005 From: Connor.Smith at huntington.com (Connor.Smith@huntington.com) Date: Wed, 1 Jun 2005 15:16:36 -0400 Subject: [Tutor] Process control and capturing output Message-ID: Hi there - I'm trying to capture the output of a long-running command in the background (it's a CVS rdiff on a fairly big repository). I need to capture the stdout from this command, and then parse it later for a report Defining the function: def rdiffApp (targetModule, buildFromStamp, buildToStamp = "HEAD"): command = "cvs rdiff -s -r \"%(buildFromStamp)s\" -r \"%(buildToStamp)s\" %(targetModule)s" % locals() print "Running CVS Command:" print command try: cvsrdiffoutfile, cvsstdinfile = popen2.popen2(command) except os.error: print "CVS command failed at OS level." print "Rdiff operation did not complete" print "Bailing..." sys.exit(1) except: print "Unknown error occurred." print "Rdiff operation did not complete." print "Bailing..." sys.exit(2) #And return with anything we found in here cvsrdiffout = cvsrdiffoutfile.readlines() return cvsrdiffout And then running the following line: cvs = rdiffApp("MODULE_NAME", "TAG") never returns. In fact, it hangs the interpreter, and I have to kill the window to try again. I'm running Python 2.4 on a Windows 2000 box. It looks like popen2 isn't waiting for the command to complete, and I don't know how to make it do that. An easy solution to this would be to write the stdout file to disk, and then read it later, but I'd rather not write temp files to disk, if I can keep them in a file-like object in memory. Any help? Thanks in advance, -Cs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050601/071b432b/attachment.htm From alan.gauld at freenet.co.uk Wed Jun 1 21:39:49 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 1 Jun 2005 20:39:49 +0100 Subject: [Tutor] Strange IndexError References: <200506011316.38559.w.richert@gmx.net> Message-ID: <005701c566e1$acacaec0$26ba8651@xp> > Traceback (most recent call last): > File "NeedBrain.py", line 233, in update > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST > IndexError: tuple assignment index out of range > > I don't see, where tuples are involved. I only compare two floats. I've Python > 2.3.4. Usually when that kind of thing happens to me I've accidentally used a comma instead of a period. Are you sure you don't have self,_isNearMarker = ... So Python sees it like a,b = True Just a thought, Alan G. From alan.gauld at freenet.co.uk Wed Jun 1 21:57:30 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 1 Jun 2005 20:57:30 +0100 Subject: [Tutor] Win32 Question References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D437@riv-excha5.echostar.com> Message-ID: <006a01c566e4$253b7f40$26ba8651@xp> > this line causes the error given above -----> process.GetOwner() > #apply( process.GetOwner ) I may be barking up the wrong tree but why not just call process.GetOwner() directly? Why use apply() at all? Or is that what the comment means? That you get an error when you try to use it directly? Also checking the Win32 API it looks like: uint32 GetOwner( string User, string Domain ); expects a couple of parameters to hold the return values. I dunno how Winall handles that but it may be worth investigating. Alan G. From jeffpeery at yahoo.com Wed Jun 1 22:57:57 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 1 Jun 2005 13:57:57 -0700 (PDT) Subject: [Tutor] imbedding python into another program? In-Reply-To: Message-ID: <20050601205758.91917.qmail@web30503.mail.mud.yahoo.com> hello, is it possible to add something like the python IDLE into another program, say if I wanted to simply run scripts from within a wxPython program? Could someone point me to the correct reference? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050601/41d8e75d/attachment.html From cgw501 at york.ac.uk Wed Jun 1 23:24:05 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 01 Jun 2005 22:24:05 +0100 Subject: [Tutor] List processing Message-ID: Hi, I have a load of files I need to process. Each line of a file looks something like this: eYAL001C1 Spar 81 3419 4518 4519 2 1 So basically its a table, separated with tabs. What I need to do is make a new file where all the entries in the table are those where the values in columns 1 and 5 were present as a pair more than once in the original file. I really have very little idea how to achiev this. So far I read in the file to a list , where each item in the list is a list of the entries on a line. *Any* help appreciated. Thanks, Chris From dyoo at hkn.eecs.berkeley.edu Wed Jun 1 23:33:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Jun 2005 14:33:19 -0700 (PDT) Subject: [Tutor] imbedding python into another program? In-Reply-To: <20050601205758.91917.qmail@web30503.mail.mud.yahoo.com> Message-ID: On Wed, 1 Jun 2005, Jeff Peery wrote: > hello, is it possible to add something like the python IDLE into another > program Hi Jeff, Getting IDLE to work within wxPython is technically possible, but probably a little tricky, since it'll involve getting the GUI event loops to cooperate. I believe it is doable --- there's code in the Twisted Python project, for example, that allows the Tkinter event loop to integrate into Twisted's event loop. That being said, this might be overkill for what you're trying to do. > say if I wanted to simply run scripts from within a wxPython program? > Could someone point me to the correct reference? thanks. Hmmm... do you necessarily have to have those scripts run through IDLE then? What kind of scripts are you trying to run through wxPython? Would something like the 'commands' module be useful for you? http://www.python.org/doc/lib/module-commands.html Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Jun 1 23:37:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Jun 2005 14:37:59 -0700 (PDT) Subject: [Tutor] List processing In-Reply-To: Message-ID: On 1 Jun 2005 cgw501 at york.ac.uk wrote: > I have a load of files I need to process. [text cut] > So basically its a table, separated with tabs. What I need to do is make > a new file where all the entries in the table are those where the values > in columns 1 and 5 were present as a pair more than once in the original > file. Hi Chris, Have you thought about sorting? If you sort them based on specific columns, then elements with the same columns will cluster together in runs. So you may not even need Python much in this case; pipine your input through a 'sort -k1,5' might do the brunt of the work. If you want to do this with Python alone, that's doable too in a fairly straightforward way. Are you familiar with the "dictionary" data structure yet? Best of wishes to you! From chuck at freshsources.com Wed Jun 1 23:42:27 2005 From: chuck at freshsources.com (Chuck Allison) Date: Wed, 1 Jun 2005 15:42:27 -0600 Subject: [Tutor] File Input of "Objects" Message-ID: <375302724.20050601154227@freshsources.com> Hello tutor, I notice that with 'print >> f' one can print the string representation of objects to a file. Is there a corresponding input facility that parses through a file creating objects? I can't find one. In the meantime, I did this: >>> f = open('out.dat','w') >>> print >> f, 1, 2 >>> f.close() >>> s = open('out.dat').read() >>> x,y = tuple(map(eval,s.split()[:2])) >>> x,y (1, 2) This is just what came to mind without thought. Is there a Pythonic way to read formatted objects? Thanks. -- Best regards, -- Chuck Allison From andre.roberge at gmail.com Thu Jun 2 00:26:59 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Wed, 01 Jun 2005 19:26:59 -0300 Subject: [Tutor] imbedding python into another program? In-Reply-To: <20050601205758.91917.qmail@web30503.mail.mud.yahoo.com> References: <20050601205758.91917.qmail@web30503.mail.mud.yahoo.com> Message-ID: Jeff Peery wrote: > hello, is it possible to add something like the python IDLE into > another program, say if I wanted to simply run scripts from within a > wxPython program? Could someone point me to the correct reference? > thanks. > Hi Jeff, you may want to have a look at PyCrust, PyShell and the like. I do something like this in my rur-ple app (on sourceforge). The relevant lines of code are: import wx.py as py [inside a wx.Notebook] win = py.shell.Shell(self.window, -1, introText = tr.INTERPRETER_INTRO_TEXT) self.window.AddPage(win, tr.PYTHON_INTERPRETER) ============ HTH, Andr? From carroll at tjc.com Thu Jun 2 00:33:47 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 1 Jun 2005 15:33:47 -0700 (PDT) Subject: [Tutor] List processing In-Reply-To: Message-ID: On 1 Jun 2005 cgw501 at york.ac.uk wrote: > eYAL001C1 Spar 81 3419 4518 4519 2 1 > > So basically its a table, separated with tabs. What I need to do is make > a new file where all the entries in the table are those where the values > in columns 1 and 5 were present as a pair more than once in the original > file. This is half-baked, but I toss it out in case anyone can build on it. Create a dictionary, keyed on column 1. Read a line and split it into the columns. For each line, create a dictionary entry that is a dictionary keyed by column 5, whose entry is a list of lists, the inner list of which contains columns 2, 3, 4 and 6. When a dupe is found, add an additional inner list. So, upon processing this line, you have a dictionary D: {'eYAL001C1': {'4518': [['Spar', '3419', '4519', '2', '1']]}} As you process each new line, one of three things is true: 1) Col 1 is used as a key, but col5 is not used as an inner key; 2) Col 1 is used as a key, and col5 is used as an inner key 3) Col 1 is not used as a key So, for each new line: if col1 in d.keys(): if col5 in d[col1].keys() d[col1][col5].append([col2, col3, col4, col6]) else d[col1][col5] = [[col2, col3, col4, col6]] else: d[col1]={col5:[[col2, col3, col4, col6] The end result is that you'll have all your data from the file in the form of a dictionary indexed by column 1. Each entry in the top-level dictionary is a second-level dictionary indexed by column 2. Each entry in that second-level dictionary is a list of lists, and each list in that list of lists is columns 2, 3, 4 and 6. if the list of lists has a length of 1, then the col1/col5 combo only appears once in the input file. But if it has a length > 1, it occurred more than once, and satisfies you condition of "columns 1 and 5 were present as a pair more than once" So to get at these: for key1 in d: for key2 in d[key1]: if len(d[key1][key2]) > 1: for l in d[key1][key2]: print key1, l[0], l[1], l[2], key2, l[3] I haven't tested this approach (or syntax) but I think the approach is basically sound. From jeffpeery at yahoo.com Thu Jun 2 00:37:38 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 1 Jun 2005 15:37:38 -0700 (PDT) Subject: [Tutor] imbedding python into another program? In-Reply-To: Message-ID: <20050601223738.90728.qmail@web30505.mail.mud.yahoo.com> ok, thanks! that helps. I have an application that reads a data file, crunches some numbers, and spits out some graphs. In addition to this I would also like users to be able to write small python scripts to operate on the data that is available within the program. I suppose this could be accomplished by simply reading a text input and sending off the command to the command module and then returning the result to the user?? Is this feasible? thanks for the help! Jeff Danny Yoo wrote: On Wed, 1 Jun 2005, Jeff Peery wrote: > hello, is it possible to add something like the python IDLE into another > program Hi Jeff, Getting IDLE to work within wxPython is technically possible, but probably a little tricky, since it'll involve getting the GUI event loops to cooperate. I believe it is doable --- there's code in the Twisted Python project, for example, that allows the Tkinter event loop to integrate into Twisted's event loop. That being said, this might be overkill for what you're trying to do. > say if I wanted to simply run scripts from within a wxPython program? > Could someone point me to the correct reference? thanks. Hmmm... do you necessarily have to have those scripts run through IDLE then? What kind of scripts are you trying to run through wxPython? Would something like the 'commands' module be useful for you? http://www.python.org/doc/lib/module-commands.html Best of wishes to you! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050601/2b7f7111/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Jun 2 02:06:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Jun 2005 17:06:47 -0700 (PDT) Subject: [Tutor] imbedding python into another program? In-Reply-To: <20050601223738.90728.qmail@web30505.mail.mud.yahoo.com> Message-ID: On Wed, 1 Jun 2005, Jeff Peery wrote: > ok, thanks! that helps. I have an application that reads a data file, > crunches some numbers, and spits out some graphs. In addition to this I > would also like users to be able to write small python scripts to > operate on the data that is available within the program. I suppose this > could be accomplished by simply reading a text input and sending off the > command to the command module and then returning the result to the > user?? Is this feasible? Hi Jeff, Yes, this should be very feasible with the 'commands' module. But if we're guaranteeing that we're going to work only with Python programs, we can simplify this tremendously by just treating those subprograms as modules. Python allows us to dynamically load Python programs in as modules with the '__import__' statement. For example, let's say that we had two programs in the current directory called 'foo.py' and 'bar.py'. ### foo.py ### def sayHello(): print "hellooo everybody, I'm so glad to see you." ###### ### bar.py ### def sayHello(): print "como estas" ###### Once we have this, then we can do something like this: ### controller.py ### import traceback def main(): while True: moduleName = raw_input( "Please enter a module name, or 'quit' to exit: ") if moduleName == 'quit': break try: dynamicModule = __import__(moduleName) dynamicModule.sayHello() except ImportError: traceback.print_exc() if __name__ == '__main__': main() ###### The approach above can be seen as a "plugin"-style approach, where we dynamically pull in modules and use a common interface to talk with them. There's a lot of things we can take advantage of if we're in pure Python. But if we're not, we're can still use some other kind of interprocess communication mechanism, such as the 'commands' module or even 'xmlrpc' if we want to be buzzword-compliant. *grin* Best of wishes! From kent37 at tds.net Thu Jun 2 04:47:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Jun 2005 22:47:22 -0400 Subject: [Tutor] List processing In-Reply-To: References: Message-ID: <429E733A.9050804@tds.net> cgw501 at york.ac.uk wrote: > Hi, > > I have a load of files I need to process. Each line of a file looks > something like this: > > eYAL001C1 Spar 81 3419 4518 4519 2 1 > > So basically its a table, separated with tabs. What I need to do is make a > new file where all the entries in the table are those where the values in > columns 1 and 5 were present as a pair more than once in the original file. > > I really have very little idea how to achiev this. So far I read in the > file to a list , where each item in the list is a list of the entries on a > line. I would do this with two passes over the data. The first pass would accumulate lines and count pairs of (col1, col5); the second pass would output the lines whose count is > 1. Something like this (untested): lines = [] counts = {} # Build a list of split lines and count the (col1, col5) pairs for line in open('input.txt'): line = line.split() # break line on tabs key = (line[1], line[5]) # or (line[0], line[4]) depending on what you mean by col 1 counts[key] = counts.get(key, 0) + 1 # count the key pair lines.append(line) # Output the lines whose pairs appear more than once f = open('output.txt', 'w') for line in lines: if counts[(line[1], line[5])] > 1: f.write('\t'.join(line)) f.write('\n') f.close() Kent From alan.gauld at freenet.co.uk Thu Jun 2 07:17:30 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 2 Jun 2005 06:17:30 +0100 Subject: [Tutor] List processing References: Message-ID: <00a801c56732$6052ec00$26ba8651@xp> > I have a load of files I need to process. Each line of a file looks > something like this: > > eYAL001C1 Spar 81 3419 4518 4519 2 1 > > So basically its a table, separated with tabs. What I need to do is make a > new file where all the entries in the table are those where the values in > columns 1 and 5 were present as a pair more than once in the original file. My immediate answer would be to use awk. However if that's not possible or desirable then look at the fileinput module and the string.split function. Alan G From kraus at hagen-partner.de Thu Jun 2 08:34:23 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 02 Jun 2005 08:34:23 +0200 Subject: [Tutor] File Input of "Objects" In-Reply-To: <375302724.20050601154227@freshsources.com> References: <375302724.20050601154227@freshsources.com> Message-ID: Chuck Allison wrote: > Hello tutor, > > I notice that with 'print >> f' one can print the string > representation of objects to a file. Is there a corresponding input > facility that parses through a file creating objects? I can't find > one. In the meantime, I did this: > > >>>>f = open('out.dat','w') >>>>print >> f, 1, 2 >>>>f.close() >>>>s = open('out.dat').read() >>>>x,y = tuple(map(eval,s.split()[:2])) >>>>x,y > > (1, 2) > > This is just what came to mind without thought. Is there a Pythonic > way to read formatted objects? Thanks. > If you want to save objects to a file and reread them later, the best solution is pickle: http://www.python.org/doc/2.4.1/tut/node9.html#SECTION009220000000000000000 and http://www.python.org/doc/2.4.1/lib/module-pickle.html HTH, Wolfram From w.richert at gmx.net Thu Jun 2 11:39:36 2005 From: w.richert at gmx.net (Willi Richert) Date: Thu, 2 Jun 2005 11:39:36 +0200 Subject: [Tutor] Strange IndexError In-Reply-To: References: Message-ID: <200506021139.36873.w.richert@gmx.net> Hi, my app is a Pyrobot (http://emergent.brynmawr.edu/~dblank/pyro/) simulation which connects to PlayerStage (playerstage.sf.net) to simulate three Pioneer robots. These are controlled using NeedBrain.py. In parallel to the three NeedBrains there is one MonitorBrain running for some management tasks, so I have four parallel running classes. NeedBrain.py -> http://deadbeefbabe.org/paste/762 MonitorBrain.py -> http://deadbeefbabe.org/paste/763 I added assertion code, which shows that I am comparing real floats. Nevertheless, I get: NeedBrNeedBrain.py:232: RuntimeWarning: tp_compare didn't return -1 or -2 for exception assert type(self._markerDist)==type(1.0), str(self._markerDist)+"is not float" Traceback (most recent call last): File "NeedBrain.py", line 232, in update assert type(self._markerDist)==type(1.0), str(self._markerDist)+"is not float" IndexError: tuple assignment index out of range Locals by frame, innermost last Frame __bootstrap in /usr/lib/python2.3/threading.py at line 436 self = Frame run in /home/wr/forschung/software/ps/pyrobot/brain/__init__.py at line 148 count = 0 self = Frame step in NeedBrain.py at line 465 self = Frame step in /home/wr/forschung/software/ps/pyrobot/brain/behaviors/__init__.py at line 63 s = ApproachMarker20Action self = Frame run in /home/wr/forschung/software/ps/pyrobot/brain/behaviors/__init__.py at line 299 r = [1.0, 'rotate', -2.2425874250672049, 'Rule2', 'MoveToMarkerBehavior', 'ApproachMarker20Action'] b = bkey = AvoidObstacleBehavior self = Frame update in NeedBrain.py at line 237 self = e = tuple assignment index out of range Any comment to the code is appreciated - especially those ones that solve the IndexError ;-) Regards, wr Am Mittwoch, 1. Juni 2005 19:09 schrieb Danny Yoo: > On Wed, 1 Jun 2005, Willi Richert wrote: > > in my code I get in rare occasions an IndexError which is > > incomprehensible to me in that situation, where I do a simple > > comparison: > > > > NeedBrain.py:233: RuntimeWarning: tp_compare didn't return -1 or -2 for > > exception > > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST > > Hi Willi, > > Hmmm! This actually looks very unusual. You should never see anything > about 'tp_compare' unless you're dealing with a buggy C extension. > > > Traceback (most recent call last): > > File "NeedBrain.py", line 233, in update > > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST > > IndexError: tuple assignment index out of range > > > > I don't see, where tuples are involved. I only compare two floats. I've > > Python 2.3.4. > > Have you edited the program since the program started? It's very possible > that the line numbers are wrong just because the program has changed in > the meantime. > > But the warning before that talks about 'tp_compare' has me intrigued, as > you should never see that error. If you don't mind, can you post your > code up somewhere? > > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cpu.crazy at gmail.com Wed Jun 1 23:20:37 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 01 Jun 2005 15:20:37 -0600 Subject: [Tutor] Looking for HOWTO's In-Reply-To: References: Message-ID: <429E26A5.70203@gmail.com> Hi, I could use some howto's or tutorials in python, on how to build an image reader (like: Kview, or Kodak's Easy Share Software). I searched Google but can't find anything (I also have pay-by-the-minute dial up so I don't surf much) I know it's reinventing the wheel, but, I just want to learn how to make one.... may come in handy later on. Thanks, Joe PS> I wouldn't mind /any/ Python HOWTO or tutorial.... From marco at meder.de Thu Jun 2 15:11:34 2005 From: marco at meder.de (Marco Scheidhuber) Date: Thu, 02 Jun 2005 15:11:34 +0200 Subject: [Tutor] Looking for HOWTO's In-Reply-To: <429E26A5.70203@gmail.com> References: <429E26A5.70203@gmail.com> Message-ID: <429F0586.4090300@meder.de> hi joseph, Joseph Quigley wrote: > PS> I wouldn't mind /any/ Python HOWTO or tutorial.... google is your friend ;-) Your first tutorial should be http://python.org/doc/2.4.1/tut/tut.html or maybe http://honors.montana.edu/~jjc/easytut/easytut/ and a search for "image reader" python gives e.g. http://sourceforge.net/projects/pdsimagereader/ hth marco -- marco scheidhuber------------------------------------------------- internetmanufaktur jo----------------------------- Berlin, Germany |||||||||||||||meder-------------------fon: ++49-30-417 17 63 34 http://www.meder.de/ ------------------- fax: ++49-30-417 17 63 45 Kollwitzstr. 75 ------------------------ mob: ++49-172- 3 22 07 83 10435 Berlin ----------------------------------------------------- From tubaranger at gmail.com Thu Jun 2 15:48:04 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Thu, 2 Jun 2005 08:48:04 -0500 Subject: [Tutor] Building an SQL query Message-ID: <57aa550605060206484a305bcb@mail.gmail.com> Hello- I am building a query to hit a Postgres (8.0.1) database from Python (4.2.1) on Linux. Here's how I've been doing it for the past year or so: data = {} data['start_date'] = '2005-6-2' data['last_name'] = 'Johnson' query = ''' SELECT * FROM my_table WHERE date >= '%(start_date)s' AND last_name = '%(last_name)s' ''' % data results = my_database.Execute(query) and life has been good. What I would like to do now is use the Postgres "IN" operator. For example: ids_to_process = ('1','2','3','5','7','11') I would like to get something akin to: query = ''' UPDATE my_table SET state = 'processed' WHERE id IN ids_to_process ''' This would, of course, set the 'state' column to 'processed' for all of the ids in the list, but can not figure out how to get this into a query to pass to the database. Have any of you smart cookies out there dealt with this? There are other ways to get the job done, worst case being writing a look and issuing an UPDATE for each id, but that is not too elegant, IMHO. Any help or pointers would be greatly appreciated, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/613e1f88/attachment.htm From golarru at hotmail.com Thu Jun 2 16:56:38 2005 From: golarru at hotmail.com (Xabier Gonzalez) Date: Thu, 02 Jun 2005 16:56:38 +0200 Subject: [Tutor] How interacts Python with .exe files Message-ID: I wanted to know how can I use in Python the inputs and the outputs of an .exe file. Maybe the question is too simple, but I?m new in Python and I have not too much experience in programming (basic C++ knowledge). Xabier Gonzalez (Spain) From albertito_g at hotmail.com Thu Jun 2 18:13:35 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 02 Jun 2005 16:13:35 +0000 Subject: [Tutor] Py2exe Problem Message-ID: Hey I'm having a problem with Py2exe. I created the executable but when I try to execute it it gives the following error: Traceback (most recent call last): File "NovusExtension.pyw", line 8, in ? File "Pmw\__init__.pyc", line 28, in ? WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: 'C:\\Documents and Settings\\percy.IMPOR-FERNANDO\\Escritorio\\NovExt\\dist\\library.zip\\Pmw/*.*' The thing is when I run the .pyw, runs smoothly Here is the code for the setup creation: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') ##setup( ## windows = [{'script': "NovusExtension.pyw",'icon_resources': [(1, "icono.ico")]}], ##) setup( windows = [{'script': "NovusExtension.pyw"}], ) Am I doing something wrong? Another thing. I have a MySQL Server in my PC and the app I've made has to be used by others PC and have to connect to my machine. How can I accomplish that? If you need the code I can send it as an attachment Please Help From bgailer at sbcglobal.net Thu Jun 2 17:23:33 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Thu, 02 Jun 2005 08:23:33 -0700 Subject: [Tutor] How interacts Python with .exe files In-Reply-To: References: Message-ID: <6.1.2.0.0.20050602082148.0371ee20@pop.sbcglobal.yahoo.com> At 07:56 AM 6/2/2005, Xabier Gonzalez wrote: >I wanted to know how can I use in Python the inputs and the outputs of an >.exe file. Take a look at the popen2 module. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/35200469/attachment.htm From bgailer at sbcglobal.net Thu Jun 2 17:33:26 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Thu, 02 Jun 2005 08:33:26 -0700 Subject: [Tutor] Building an SQL query In-Reply-To: <57aa550605060206484a305bcb@mail.gmail.com> References: <57aa550605060206484a305bcb@mail.gmail.com> Message-ID: <6.1.2.0.0.20050602082536.036c1690@pop.sbcglobal.yahoo.com> At 06:48 AM 6/2/2005, Greg Lindstrom wrote: >Hello- > >I am building a query to hit a Postgres (8.0.1) database from Python >(4.2.1) on Linux. Here's how I've been doing it for the past year or so: > >data = {} >data['start_date'] = '2005-6-2' >data['last_name'] = 'Johnson' > >query = ''' > SELECT * > FROM my_table > WHERE date >= '%(start_date)s' > AND last_name = '%(last_name)s' >''' % data >results = my_database.Execute(query) > >and life has been good. What I would like to do now is use the Postgres >"IN" operator. For example: > >ids_to_process = ('1','2','3','5','7','11') > >I would like to get something akin to: > >query = ''' > UPDATE my_table > SET state = 'processed' > WHERE id IN ids_to_process >''' Do you want, in this case, the where clause to be : WHERE id IN ('1','2','3','5','7','11')? If so, how about: query = ''' UPDATE my_table SET state = 'processed' WHERE id IN ''' + str(ids_to_process) >This would, of course, set the 'state' column to 'processed' for all of >the ids in the list, but can not figure out how to get this into a query >to pass to the database. Have any of you smart cookies out there dealt >with this? There are other ways to get the job done, worst case being >writing a look and issuing an UPDATE for each id, but that is not too >elegant, IMHO. > >Any help or pointers would be greatly appreciated, > >--greg >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/af98cae2/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Jun 2 21:00:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 Jun 2005 12:00:58 -0700 (PDT) Subject: [Tutor] Strange IndexError In-Reply-To: <200506021139.36873.w.richert@gmx.net> Message-ID: On Thu, 2 Jun 2005, Willi Richert wrote: > my app is a Pyrobot (http://emergent.brynmawr.edu/~dblank/pyro/) > simulation which connects to PlayerStage (playerstage.sf.net) to > simulate three Pioneer robots. These are controlled using NeedBrain.py. > In parallel to the three NeedBrains there is one MonitorBrain running > for some management tasks, so I have > four parallel running classes. Hi Willi, I think you may want to bring this up on comp.lang.python: I have a strong feeling I'm in over my head. *grin* The experts on comp.lang.python should be able to better pinpoint the exact problem. The code that prints that peculiar error message is at the very core of Python's object implementation in doing object equality checking: /*** Objects/object.c, about line 441 in Python 2.4 source ***/ /* Helper to warn about deprecated tp_compare return values. Return: -2 for an exception; -1 if v < w; 0 if v == w; 1 if v > w. (This function cannot return 2.) */ static int adjust_tp_compare(int c) { if (PyErr_Occurred()) { if (c != -1 && c != -2) { PyObject *t, *v, *tb; PyErr_Fetch(&t, &v, &tb); if (PyErr_Warn(PyExc_RuntimeWarning, "tp_compare didn't return -1 or -2 " "for exception") < 0) { Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); } else PyErr_Restore(t, v, tb); /******/ We can reason that PyErr_Occurred() somehow returned true, and that the error information is being captured in C code throught the 't', 'v' and 'tb' variables. Those three variables are ultimately responsible for what's printing out: IndexError: tuple assignment index out of range and the output that talks about 'tp_compare' shows up because of the PyErr_Warn call. That explains why we see both error messages. I'm staring at the code a little more; there's a bit of code around line 229 that bothers me a bit: ###### try: self._markerObject = self.get("robot/fiducial/id")(self.marker) finally: if not self._markerObject: self._markerDist = 1000.0 else: self._markerDist = self._markerObject.range ###### My hypothesis now is that the equality check against the type of self._markerDist is raising an error, which would require self._markerDist to be something unusual. I know, I'm reaching, but let me see how far this goes. *grin* I don't see anything else that assigns to self._markerDist in any other part of the code. In the code above, I see in the 'else' block that self._markerDist is being assigned to 'self._markerObject.range'. What type is 'self._markerObject', and what type is 'self._markerObject.range? Do you mind adding some code to print those out? I can't assume that 'range' is a number, since 'range' is being used in all sorts of contexts, especially in the pyro source code. For example, pyro.PyroHierarchy has the following comment: ###### class PyroHierarchy (object): """ A wrapper class for the pyro devices hierarchy. An instance of this class represents a node of the hierarchy, with an attribute for every subnode. Getting an attribute is equivalent to using robot.get . Setting an attribute is equivalent to using robot.set . Numeric nodes can be accessed as list elements. Examples of use: h.robot.range.all # returns another PyroHierarchy object h.robot.range.name # return a string h.robot.range.all.value # return a list of numbers h.robot.range[1].value # returns a number h.robot.range[1:4] # returns a list of PyroHierarchy objects h.devices.gripper.command = "open" # issues command "open" to gripper0 """ ###### so I strongly suspect that this 'range' object is something much richer than a float. Something like: print self._markerDist, type(self._markerDist) might help us see what's going on better. Best of wishes to you! From denise.hartley at gmail.com Thu Jun 2 21:55:20 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 2 Jun 2005 12:55:20 -0700 Subject: [Tutor] quick PIL question Message-ID: <8daabe56050602125541eff523@mail.gmail.com> What does it mean if my image mode is "P"? In the documentation, it says "typical values are '1', 'L', 'RGB', 'CMYK.'" (it's a gif, if that's important) Thanks! :) ~Denise From bgibson at us.ibm.com Thu Jun 2 22:21:00 2005 From: bgibson at us.ibm.com (Bob Gibson) Date: Thu, 2 Jun 2005 16:21:00 -0400 Subject: [Tutor] Connect to Apache Derby databases using Python In-Reply-To: Message-ID: For Your Information / Enjoyment / Entertainment / Education... (whatever): http://www.ibm.com/developerworks/db2/library/techarticle/dm-0505gibson Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/9be718d5/attachment.htm From alan.gauld at freenet.co.uk Thu Jun 2 22:39:11 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 2 Jun 2005 21:39:11 +0100 Subject: [Tutor] Building an SQL query References: <57aa550605060206484a305bcb@mail.gmail.com> Message-ID: <010801c567b3$226fdb10$26ba8651@xp> > I am building a query to hit a Postgres (8.0.1) database > from Python (4.2.1) on Linux. Here's how I've been doing > it for the past year or so: > ... > query = ''' > SELECT * > FROM my_table > .... Its a really bad idea to use SELECT * FROM in production code. There are two main reasons: 1) If the database structure changes your code is likely to break since SELECT * does not normally guarantee anything about the order of fields returned, so if the table gets an extra field added you might find the order changing. At the very least there will be an extra item in your tuple ofvalues returned whichj may well break your code. 2) Using * also prevents the database from precompiling your query and caching it, thus you will slow down the processing by forcing a SQL compile step each time. (This is true on Oracle, DB2 and Interbase, I don't know about Postgres but assume it is similar) Of course if you are the only user and the database is small these are not likely to be major issues but if two or more apps use the same database or if many users are hitting it it could be. SELECT * is great for experimenting but in production code its much safer to explicitly list the fields that you want back. > query = ''' > UPDATE my_table > SET state = 'processed' > WHERE id IN ids_to_process > ''' > > This would, of course, set the 'state' column to 'processed' > for all of the ids in the list, but can not figure out how > to get this into a query to pass to the database. What have you tried? What happened? It should just be a case of using variable interpolation as you did for the Select. Alan G. From missive at hotmail.com Thu Jun 2 22:55:56 2005 From: missive at hotmail.com (Lee Harr) Date: Fri, 03 Jun 2005 01:25:56 +0430 Subject: [Tutor] Building an SQL query Message-ID: >data = {} >data['start_date'] = '2005-6-2' >data['last_name'] = 'Johnson' > >query = ''' > SELECT * > FROM my_table > WHERE date >= '%(start_date)s' > AND last_name = '%(last_name)s' >''' % data >results = my_database.Execute(query) First up. This is a "bad idea". It may be ok now, as long as you have absolute control over what start_date and last_name are, but what about next week when you decide ... "let's allow the user to put in the dates for start_date" and they make start_date "'6-2-05'; DELETE FROM my_table; SELECT * FROM my_table WHERE date='6-2-05' " Instead, use the arg quoting mechanism from the db interface you are using. You don't say which one that is, but it should look something like ... data = {} data['start_date'] = '2005-6-2' data['last_name'] = 'Johnson' query = ''' SELECT * FROM my_table WHERE date >= '%(start_date)s' AND last_name = '%(last_name)s' ''' results = my_database.execute(query, data) >ids_to_process = ('1','2','3','5','7','11') > >I would like to get something akin to: > >query = ''' > UPDATE my_table > SET state = 'processed' > WHERE id IN ids_to_process >''' You can use an array type in postgres. I use something like this: data = {} data['ids_to_process'] = ['1','2','3','5','7','11'] query = ''' UPDATE my_table SET state = 'processed' WHERE id IN ARRAY%(ids_to_process)s ''' db.execute(query, data) Notice that I changed the data tuple to a list. The postgres syntax for an array is ARRAY[1, 2, 3, 5, 7, 11] so you need the square brackets that a list will give you. It's kind of a hack, but as far as I know none of the other databases have arrays, so the db-api people are not into creating a special array access method. _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From tubaranger at gmail.com Thu Jun 2 23:05:53 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Thu, 2 Jun 2005 16:05:53 -0500 Subject: [Tutor] Building an SQL query In-Reply-To: <010801c567b3$226fdb10$26ba8651@xp> References: <57aa550605060206484a305bcb@mail.gmail.com> <010801c567b3$226fdb10$26ba8651@xp> Message-ID: <57aa55060506021405775eb6fb@mail.gmail.com> On 6/2/05, Alan G wrote: > > > Its a really bad idea to use SELECT * FROM in production code. > There are two main reasons: > 1) If the database structure changes your code is likely to break since > SELECT * does not normally guarantee anything about the order of fields > returned, so if the table gets an extra field added you might find the order > changing. At the very least there will be an extra item in your tuple > ofvalues returned whichj may well break your code. Alan, I'm using SELECT * specifically for this reason! I have the query and customer specific data layouts stored in a database and am using ADOpy to associate the field names to locations in a data segment. Doing it this way allows us to modify the query and/or the layout in the database without touching the code that does all of the heavy lifting. Using this strategy, we are able to perform all of our extractions to customer specific layouts with one rather small Python routine (this was the topic I spoke on at PyCon 2005) and with the web pages we've created our non-technical personnel can create/modify customer layouts. It started off as a project to do our daily data pulls but has grown to handle virtually every report we generate. 2) Using * also prevents the database from precompiling your query and > caching it, thus you will slow down the processing by forcing a SQL compile > step each time. (This is true on Oracle, DB2 and Interbase, don't know about > Postgres but assume it is similar) You are correct and in the future this may be a problem but currently we will accept the time penalty to gain the flexibility described above. > query = ''' > > UPDATE my_table > > SET state = 'processed' > > WHERE id IN ids_to_process > > ''' > What have you tried? What happened? It should just be a case > of using variable interpolation as you did for the Select. Here's what works for me (and a tip-o-the-hat to Bob Gailer for his help) query = '''UPDATE my_table SET state = 'processed' WHERE id IN %s''' % str(ids_to_process) query = query.replace('[', '(') query = query.replace(']', ')') results = adocursor.Execute(query) Notice that I have to replace [ with ( and ] with ). A small bother but the results are allowing me to perform much more complex queries out of the database. I'm always open to ways to improve this (in particular I would like to avoid recompiling the query every time this is hit). It just hit me that we could store the field names to select in the query right along with everything else...I think I'll try it to see what sort of increase we get because we plan on growing our business. Thanks for responding, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/96985a5f/attachment.htm From alan.gauld at freenet.co.uk Thu Jun 2 23:41:20 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 2 Jun 2005 22:41:20 +0100 Subject: [Tutor] Building an SQL query References: <57aa550605060206484a305bcb@mail.gmail.com> <010801c567b3$226fdb10$26ba8651@xp> <57aa55060506021405775eb6fb@mail.gmail.com> Message-ID: <011801c567bb$d0aa63a0$26ba8651@xp> > > SELECT * does not normally guarantee anything about the order of fields > > returned, so if the table gets an extra field added you might find the order > > I'm using SELECT * specifically for this reason! I have the query and > customer specific data layouts stored in a database and am using ADOpy > to associate the field names to locations in a data segment. Hmm, I dunno ADOpy but assume it somehow miraculously turns your data set into a dictionary of some sort? How it guesses which order the SELECT will return the fields is a mystery to me, but maybe it has knowledge of the Postgres hashing function or somesuch. > Here's what works for me (and a tip-o-the-hat to Bob Gailer for his help) > > query = '''UPDATE my_table SET state = 'processed' WHERE id IN %s''' % > str(ids_to_process) > query = query.replace('[', '(') Why not convert the list to a tuple before applying str(): str(tuple(ids_to_process)) > like to avoid recompiling the query every time this is hit). > It just hit me that we could store the field names to select > in the query right along with everything else... That's what we usually do, so that if we do need to change the data retrieved for multiple queries we only change it in one place, but still keep the predictability of defined foield names. > I think I'll try it to see what sort of increase we get > because we plan on growing our business. Unless ADOpy is very slow I wouldn't expect a huge performance increase since it will only be the compile phase, but if you hit the query a lot then maybe 5-10%. You are more likely to see the benefit in a drop CPU loading on the server. Alan G. From jfouhy at paradise.net.nz Fri Jun 3 00:06:18 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 03 Jun 2005 10:06:18 +1200 (NZST) Subject: [Tutor] Py2exe Problem In-Reply-To: References: Message-ID: <1117749978.429f82dab0f0e@www.paradise.net.nz> Quoting Alberto Troiano : > I'm having a problem with Py2exe. > I created the executable but when I try to execute it it gives the > following > error: > > Traceback (most recent call last): > File "NovusExtension.pyw", line 8, in ? > File "Pmw\__init__.pyc", line 28, in ? > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: > > 'C:\\Documents and > Settings\\percy.IMPOR-FERNANDO\\Escritorio\\NovExt\\dist\\library.zip\ > \Pmw/*.*' It might help if you translated that error message :-) But, I will make one guess, since I see the problem is to do with Pmw: >From this page: http://pmw.sourceforge.net/doc/dynamicloader.html """ When Pmw is first imported, an instance of PmwLoader is created and placed into sys.modules['Pmw']. From that point on, any reference to attributes of the Pmw 'module' is handled by the loader. The real Pmw package is stored in sys.modules['_Pmw']. ... Freezing Pmw Since the dynamic loader requires that Pmw be installed at run time, it can not be used when freezing Pmw. In this case, a single module containing all Pmw code is required, which can then be frozen with the rest of the application's modules. The bundlepmw.py script in the Pmw bin directory can be used to create such a file. This script concatenates (almost) all Pmw megawidget files into a single file, Pmw.py, which it writes to the current directory. The script is called like this: bundlepmw.py [-noblt] [-nocolor] /path/to/Pmw/Pmw_X_X_X/lib The last argument should be the path to the lib directory of the required version of Pmw. By default, the Pmw.py file imports the PmwBlt and PmwColor modules and so, to freeze an application using Pmw, you will need to copy the files PmwBlt.py and PmwColor.py to the application directory before freezing. If you are sure that your application does not use any of the Pmw.Blt or Pmw.Color functions, you can use the -noblt or -nocolor options. In this case Pmw.py will be modified so that it does not import these module(s) and so will not need to be included when freezing the application. If your application only uses a few Pmw megawidgets, you can remove the references to the usused ones in the files list in the bundlepmw.py code. To make the change, take a copy of the script and modify it. This will make the Pmw.py file smaller. However, be sure that you do not delete megawidgets that are components or base classes of megawidgets that you use. """ If you haven't done this, you will need to, otherwise Pmw won't work with py2exe. -- John. From zmerch at 30below.com Fri Jun 3 00:20:51 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Thu, 02 Jun 2005 18:20:51 -0400 Subject: [Tutor] Building an SQL query In-Reply-To: <011801c567bb$d0aa63a0$26ba8651@xp> References: <57aa550605060206484a305bcb@mail.gmail.com> <010801c567b3$226fdb10$26ba8651@xp> <57aa55060506021405775eb6fb@mail.gmail.com> Message-ID: <5.1.0.14.2.20050602180521.04c90fd0@mail.30below.com> Rumor has it that Alan G may have mentioned these words: >Hmm, I dunno ADOpy but assume it somehow miraculously turns your data >set into a dictionary of some sort? I dunno ADOpy, but the pg module for PostgreSQL can return a list of dictionaries from a query. >>> import pg >>> pg.set_defuser('example') >>> pg.set_defpasswd('example') >>> pg.set_defbase('spam') >>> pgpasswd = pg.DB() >>> pgpasswd.query('select dtg, classc, helo from ips limit 3;').dictresult() [{'helo': 'veda.cz', 'dtg': '2005-03-30', 'classc': '85.39.122'}, {'helo': 'ck336290-a.dokku1.fr.home.nl', 'dtg': '2005-03-30', 'classc': '217.123.211'}, {'helo': 'keymaster.com', 'dtg': '2005-03-30', 'classc': '220.73.88'}] *** output edited slightly with carriage returns *** > How it guesses which order the >SELECT will return the fields is a mystery to me, It's a mystery to some RDBs as well, IIRC with SQL there's no 'default behavior' -- if it's not defined, it can be spit out in any order it chooses; prolly depends on the implementation. It might also matter how the indices & primary keys are set up as to what comes out first... > but maybe it has >knowledge of the Postgres hashing function or somesuch. With dictionaries, it doesn't matter nearly so much. ;-) The ease with which data can be I/O'd thru PostgreSQL with Python is one of the main factors of my dumping Perl for it; I can spend more time diddling with the data than I need to do making the proggies run. ;-) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Bugs of a feather flock together." sysadmin, Iceberg Computers | Russell Nelson zmerch at 30below.com | From carroll at tjc.com Fri Jun 3 00:39:16 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Jun 2005 15:39:16 -0700 (PDT) Subject: [Tutor] quick PIL question In-Reply-To: <8daabe56050602125541eff523@mail.gmail.com> Message-ID: On Thu, 2 Jun 2005, D. Hartley wrote: > What does it mean if my image mode is "P"? In the documentation, it > says "typical values are '1', 'L', 'RGB', 'CMYK.'" (it's a gif, if > that's important) That's really weird. It does say that (in the description of im.mode, where you'd expect it). But other parts of the doc refer to a "P" mode; see the descriptions of im.convert; im.putpalette; and the BMP format description. Seems to be some sort of "palette" format. Hey! Look under "Concepts": The mode of an image defines the type and depth of a pixel in the image. The current release supports the following standard modes: . . . - P (8-bit pixels, mapped to any other mode using a colour palette) . . . Palette The palette mode ("P") uses a colour palette to define the actual colour for each pixel. Not sure what that means, exactly, but it looks like im.palette will get the palette of a a P-mode image, and im.putpalette will change it. I'm not sure how to interpret the palette once you have it, though. The description of the ImagePalette class is not too helpful. From maxnoel_fr at yahoo.fr Fri Jun 3 00:49:05 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 2 Jun 2005 23:49:05 +0100 Subject: [Tutor] quick PIL question In-Reply-To: References: Message-ID: On Jun 2, 2005, at 23:39, Terry Carroll wrote: > The palette mode ("P") uses a colour palette to define the actual > colour for each pixel. > > > > Not sure what that means, exactly, but it looks like im.palette > will get > the palette of a a P-mode image, and im.putpalette will change it. > > I'm not sure how to interpret the palette once you have it, > though. The > description of the ImagePalette class is not too helpful. Here's what this means. Computers nowadays use 24-bit display modes (8 bits for each of the components R, G and B -- 32-bit display is the same thing with an extra 8 bits of alpha/transparency). That is, 16.7 million different possible colors. GIF images, on the other hand, are 256-color (8-bit) images. However, these 256 colors are not fixed: they can be any of the regular 16.7 million. This is where the palette comes into play. Each 256-color image has a palette, which is basically an array of length 256, where each element is a (24-bit RGB) color. The color data for each pixel in the image is actually an index in this array. Makes sense? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Fri Jun 3 00:53:50 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Jun 2005 15:53:50 -0700 (PDT) Subject: [Tutor] quick PIL question In-Reply-To: Message-ID: On Thu, 2 Jun 2005, Max Noel wrote: [explanation snipped] > Makes sense? Yes. Thanks very much. I think the problem is the the PIL documentation (reasonably) assumes that the reader already understands all the structures used in the imaging it supports; it just explains how PIL gives access to those structures. Perfectly usable for those of us who have worked with images before, and now just want to use Python to do so; less usable for those of us who use Python, and now want to extend our knowledge to cover images. From tim.peters at gmail.com Fri Jun 3 01:11:48 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 2 Jun 2005 19:11:48 -0400 Subject: [Tutor] quick PIL question In-Reply-To: References: Message-ID: <1f7befae05060216111cdb9b29@mail.gmail.com> [Max Noel] > ... > This is where the palette comes into play. Each 256-color image > has a palette, which is basically an array of length 256, where each > element is a (24-bit RGB) color. The color data for each pixel in the > image is actually an index in this array. Adding a bit of detail, in PIL getpalette() returns a list with 256*3 = 768 integers. The first three are the red, green and blue intensity levels (each in 0 thru 255) for "palette index 0", the next three are the RGB values for palette index 1, and so on. The "palette index" is more conceptual here than directly reflected in the PIL data structures. In general, if p is a PIL palette, p[3*i : 3*i+3] returns [R, G, B] for pixel index i. Going back a level, if getpixel((x, y)) returns an integer i for a "P"-mode image, then getpalette()[3*i:3*i+3] returns pixel (x, y)'s RGB values. BTW, I didn't know this before I had to learn it to solve some of the Python Challenge riddles. If you like puzzles, these are an excellent motivator to learn about some under-appreciated Python libraries! Highly recommended. From tubaranger at gmail.com Fri Jun 3 01:29:00 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Thu, 2 Jun 2005 18:29:00 -0500 Subject: [Tutor] Building an SQL query In-Reply-To: <011801c567bb$d0aa63a0$26ba8651@xp> References: <57aa550605060206484a305bcb@mail.gmail.com> <010801c567b3$226fdb10$26ba8651@xp> <57aa55060506021405775eb6fb@mail.gmail.com> <011801c567bb$d0aa63a0$26ba8651@xp> Message-ID: <57aa5506050602162912effc18@mail.gmail.com> > > Hmm, I dunno ADOpy but assume it somehow miraculously turns your data > set into a dictionary of some sort? How it guesses which order the > SELECT will return the fields is a mystery to me, but maybe it has > knowledge of the Postgres hashing function or somesuch. Yeah. I used to do it by hand by looking at the description of the cursor object, which holds the name of each field as defined in the database with other stuff. You can then get the field value by getting the index of the field name, then hitting the row data. It's not a lot of fun, but I did it because I didn't want to depend on the order being returned in case we wanted to drop a field for some reason. > Here's what works for me (and a tip-o-the-hat to Bob Gailer for his help) > > query = '''UPDATE my_table SET state = 'processed' WHERE id IN %s''' % > str(ids_to_process) > query = query.replace('[', '(') >Why not convert the list to a tuple before applying str(): >str(tuple(ids_to_process)) Didn't think of it...thanks :-) >Unless ADOpy is very slow I wouldn't expect a huge performance >increase since it will only be the compile phase, but if you >hit the query a lot then maybe 5-10%. You are more likely to >see the benefit in a drop CPU loading on the server. Which is good, too. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/dd93a1e9/attachment.html From tubaranger at gmail.com Fri Jun 3 01:35:34 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Thu, 2 Jun 2005 18:35:34 -0500 Subject: [Tutor] Tutor Digest, Vol 16, Issue 7 In-Reply-To: References: Message-ID: <57aa55060506021635f956dcf@mail.gmail.com> > > >data = {} > >data['start_date'] = '2005-6-2' > >data['last_name'] = 'Johnson' > > > >query = ''' > > SELECT * > > FROM my_table > > WHERE date >= '%(start_date)s' > > AND last_name = '%(last_name)s' > >''' % data > >results = my_database.Execute(query) > > > First up. This is a "bad idea". > > It may be ok now, as long as you have absolute control > over what start_date and last_name are, but what about > next week when you decide ... "let's allow the user to put > in the dates for start_date" and they make start_date > "'6-2-05'; DELETE FROM my_table; SELECT * FROM my_table > WHERE date='6-2-05' " > > Instead, use the arg quoting mechanism from the db > interface you are using. You don't say which one that > is, but it should look something like ... > > data = {} > data['start_date'] = '2005-6-2' > data['last_name'] = 'Johnson' > > query = ''' > SELECT * > FROM my_table > WHERE date >= '%(start_date)s' > AND last_name = '%(last_name)s' > ''' > results = my_database.execute(query, data) Very nice. Thank-you. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050602/16434029/attachment.htm From work at infomaniak.ch Fri Jun 3 11:52:45 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Fri, 03 Jun 2005 11:52:45 +0200 Subject: [Tutor] Looking for HOWTO's In-Reply-To: <429F0586.4090300@meder.de> References: <429E26A5.70203@gmail.com> <429F0586.4090300@meder.de> Message-ID: <20050603095245.GD3155@obs.unige.ch> Maybe this is Off-Topic but I found recently a perfect repository of python tutorials at: http://www.awaretek.com/tutorials.html Ced. -- Cedric BRINER From work at infomaniak.ch Fri Jun 3 12:01:20 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Fri, 03 Jun 2005 12:01:20 +0200 Subject: [Tutor] interactif or not Message-ID: <20050603100120.GF3155@obs.unige.ch> hi, How can I know if a script is launched interactively or not because I'd like to make a script verbose or not depending if it is executed as interactive or not. eg. If I invoke it in a shell.. then it can be verbose If it is launched from a crontab.. then it is less verbose. Ced. -- Cedric BRINER From olli.rajala at gmail.com Fri Jun 3 14:07:52 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Fri, 3 Jun 2005 15:07:52 +0300 Subject: [Tutor] Postgresql+Python -tutorial? Message-ID: Hi! I've been using MySQL up this day, but would like to convert my program to use Postgresql. There seems to be awful lots of tutorials for MySQL+Python, but not so many for Postgresql+Python. Where should I start? I'm not very good at database things, but have written some little programs with MySQL+Python/Php/Java. So, if you have some good tutorials or something else info, I'd be glad to know! Oh, I can install additional modules, but it would be great if Ubuntu had them... Thanks! -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From cpu.crazy at gmail.com Fri Jun 3 04:20:46 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 02 Jun 2005 20:20:46 -0600 Subject: [Tutor] Py2exe Problem In-Reply-To: References: Message-ID: <429FBE7E.8050306@gmail.com> Traceback (most recent call last): > File "NovusExtension.pyw", line 8, in ? > File "Pmw\__init__.pyc", line 28, in ? > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: this: > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: is spanish for: WindowsErrorL [Errno 3] The system can not find the file/directory specified. There are better ways of saying that.. but that's simple enough, is it? Joe From albertito_g at hotmail.com Fri Jun 3 15:15:16 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 03 Jun 2005 13:15:16 +0000 Subject: [Tutor] Py2exe Problem In-Reply-To: <1117749978.429f82dab0f0e@www.paradise.net.nz> Message-ID: Hey Thanks for the docs I finally was able to make a good compilation After I freezed Pmw into pmw.py I had to restart Python (Ctrl-Alt-Del and terminate all python process that were running, by the way why they still stay there and how can I terminate them?) and only then the compilation didn't include the Pmw library inside the dist folder that py2exe creates. But I made a compilation a few months before (I didn't remember how to compile with Pmw) and I remembered that I had to copy inside the dist folder all the images I was using and of course de pmw.py and pmwblt.py and pmwcolor.py also This is in case you want to make a compilation and you have the same problems I had Best Regards to all Alberto >From: jfouhy at paradise.net.nz >To: "tutor at python.org" >Subject: Re: [Tutor] Py2exe Problem >Date: Fri, 03 Jun 2005 10:06:18 +1200 (NZST) > >Quoting Alberto Troiano : > > > I'm having a problem with Py2exe. > > I created the executable but when I try to execute it it gives the > > following > > error: > > > > Traceback (most recent call last): > > File "NovusExtension.pyw", line 8, in ? > > File "Pmw\__init__.pyc", line 28, in ? > > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: > > > > 'C:\\Documents and > > Settings\\percy.IMPOR-FERNANDO\\Escritorio\\NovExt\\dist\\library.zip\ > > \Pmw/*.*' > >It might help if you translated that error message :-) > >But, I will make one guess, since I see the problem is to do with Pmw: > > >From this page: http://pmw.sourceforge.net/doc/dynamicloader.html > >""" > When Pmw is first imported, an instance of PmwLoader is created and >placed into >sys.modules['Pmw']. From that point on, any reference to attributes of the >Pmw >'module' is handled by the loader. The real Pmw package is stored in >sys.modules['_Pmw']. > >... > > Freezing Pmw > >Since the dynamic loader requires that Pmw be installed at run time, it can >not >be used when freezing Pmw. In this case, a single module containing all Pmw >code >is required, which can then be frozen with the rest of the application's >modules. The bundlepmw.py script in the Pmw bin directory can be used to >create >such a file. This script concatenates (almost) all Pmw megawidget files >into a >single file, Pmw.py, which it writes to the current directory. The script >is >called like this: > > bundlepmw.py [-noblt] [-nocolor] /path/to/Pmw/Pmw_X_X_X/lib > >The last argument should be the path to the lib directory of the required >version of Pmw. By default, the Pmw.py file imports the PmwBlt and PmwColor >modules and so, to freeze an application using Pmw, you will need to copy >the >files PmwBlt.py and PmwColor.py to the application directory before >freezing. > >If you are sure that your application does not use any of the Pmw.Blt or >Pmw.Color functions, you can use the -noblt or -nocolor options. In this >case >Pmw.py will be modified so that it does not import these module(s) and so >will >not need to be included when freezing the application. > >If your application only uses a few Pmw megawidgets, you can remove the >references to the usused ones in the files list in the bundlepmw.py code. >To >make the change, take a copy of the script and modify it. This will make >the >Pmw.py file smaller. However, be sure that you do not delete megawidgets >that >are components or base classes of megawidgets that you use. >""" > >If you haven't done this, you will need to, otherwise Pmw won't work with >py2exe. > >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From mhansen at cso.atmel.com Fri Jun 3 15:17:38 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 03 Jun 2005 07:17:38 -0600 Subject: [Tutor] question about "hiding" a function/method in a class Message-ID: <42A05872.8090902@cso.atmel.com> I haven't done much OO in Python yet. For various web apps we write, we usually write up a DB schema in a spreadsheet. Then we write the sql script that would create the tables in the database. I thought it would be neat to save the spreadsheet as a csv file and have python write the sql script. So I started to write the Python program. --------------------- #!/usr/bin/env python """ SQLGEN takes a csv file of a database schema and writes the sql script that will create the tables and fields in the database Mike Hansen Jun 2005 """ class DBField(object): def __init__(self, fieldName): self.fieldName = fieldName self.type = "" self.size = 0 self.notNull = False self.unique = False self.references = "" self.default = "" def printField(self): self.fieldStr = " %s %s" %(self.fieldName, self.type) if self.size > 0: self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) if self.notNull: self.fieldStr = "%s NOT NULL" %self.fieldStr if self.unique: self.fieldStr = "%s UNIQUE" %self.fieldStr if self.default: self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default) # if self.references return self.fieldStr def __getattr__(self, attrname): if attrname == "fieldStr": return self.printField() else: raise AttributeError, attrname def main(): pass def test(): areas = DBField("area") areas.type = "VARCHAR" areas.size = 80 areas.notNull = True areas.unique = True print areas.fieldStr stuff = DBField("stuff") stuff.type = "INTEGER" stuff.notNull = True print stuff.fieldStr if __name__ == "__main__": # main() test() --------------------------- I was wondering if I should "hide" the printField function, so I or someone else won't do x.printField() in the main program but use the x.fieldStr attribute. If so, how would I do that, def __printField(self):? How would I call it from __getattr__? I know I'm not really hiding it ;just mangling it. On the other hand, I guess it doesn't matter. What do you think? Mike From kent37 at tds.net Fri Jun 3 15:45:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Jun 2005 09:45:20 -0400 Subject: [Tutor] question about "hiding" a function/method in a class In-Reply-To: <42A05872.8090902@cso.atmel.com> References: <42A05872.8090902@cso.atmel.com> Message-ID: <42A05EF0.6010905@tds.net> Mike Hansen wrote: > class DBField(object): > def __init__(self, fieldName): > self.fieldName = fieldName > self.type = "" > self.size = 0 > self.notNull = False > self.unique = False > self.references = "" > self.default = "" > > def printField(self): > self.fieldStr = " %s %s" %(self.fieldName, self.type) > if self.size > 0: > self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) > if self.notNull: > self.fieldStr = "%s NOT NULL" %self.fieldStr > if self.unique: > self.fieldStr = "%s UNIQUE" %self.fieldStr > if self.default: > self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default) > # if self.references > return self.fieldStr > > def __getattr__(self, attrname): > if attrname == "fieldStr": > return self.printField() > else: > raise AttributeError, attrname > --------------------------- > > I was wondering if I should "hide" the printField function, so I or someone else > won't do x.printField() in the main program but use the x.fieldStr attribute. If > so, how would I do that, def __printField(self):? How would I call it from > __getattr__? I know I'm not really hiding it ;just mangling it. On the other > hand, I guess it doesn't matter. What do you think? Python programmers tend to take the attitude "We're all adults here" towards things like this. We use conventions to put warning labels where appropriate, then trust the client programmer to do what is right for them. So, to answer your direct question, yes, you could call the method __printField(), which nominally hides the name from other modules, or _printField(), which by convention marks the method as for internal use only (a warning label). You would call it from __getattr__() as __printField() or _printField(). (A quick experiment would have answered this part of the question.) However, for your particular usage of dynamically computing the value of a field, there is a better way to do this - use a property. class DBField(object): def _printField(self): ... # Create a read-only fieldStr attribute whose value is computed by _printField() fieldStr = property(_printField) # Remove _printField so it can't be called directly del _printField A few more comments: - The name _printField() is a bit of a misnomer since nothing is printed; _getFieldStr() might be a better name. - Another, simpler way to do this is to define __str__() instead of _printField() and fieldStr; then clients can just call str(field) to get the string representation. This will work well if you don't need any other string representation. - Of course you could also just define getFieldStr() and forget about the fieldStr attribute entirely. This is also a very simple, straightforward approach. Kent From olli.rajala at gmail.com Fri Jun 3 18:34:19 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Fri, 3 Jun 2005 19:34:19 +0300 Subject: [Tutor] Database connections don't stay alive Message-ID: Well, I asked about tutorials, but maybe this was not so good day, because it has been quite "silent". :) So, good tutorials are still welcome, though I know now how to connect to the Postgresql database. I just have some problems, though. With MySQL I can do like this: import MySQLdb def connectDB(): try: db = MySQLdb.connect(host='localhost', user='user', db='pictures', passwd='passwd') cursor = db.cursor() return cursor except: print 'Error' cursor = connectDB() cursor.execute('SELECT * FROM categories') print cursor.fetchall() And everything works as I thought. But with Postgre, it seems that the connection don't stay alive. I mean, with the same kind of code: from pyPgSQL import PgSQL def connectDB(): try: db = PgSQL.connect(host='localhost', database='pictures', user='user', password='passwd') return db.cursor() except: print "Error" cursor = connectDB() cursor.execute("SELECT * FROM categories") print cursor.fetchall() The result is: Traceback (most recent call last): File "test.py", line 23, in ? cursor.execute("SELECT * FROM categories") File "/usr/lib/python2.4/site-packages/pyPgSQL/PgSQL.py", line 2992, in execute raise InterfaceError, "execute failed - the cursor is closed." libpq.InterfaceError: execute failed - the cursor is closed. So, what's the solution for this? I saw somewhere some mentions about 'connection pooling', what's that and how I'm supposed to use that? It's quite hard to code when you don't have good manuals and have to put together information from very different sources and try to make it work... For example, this is from a manual I've used: 2.1.3.1 PQconnectdb Syntax: c = PQconnectdb(conninfo) Where conninfo is a string containing connection information. What the heck is 'conninfo', I mean, what's it's syntax? Yeah, I was finally able to figure it out, but it took hours googling, trying and stumbling. Okay, okay, back to business. Hope that someone will be able to help me. :) Yours sincerely, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From kent37 at tds.net Fri Jun 3 19:02:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Jun 2005 13:02:44 -0400 Subject: [Tutor] Database connections don't stay alive In-Reply-To: References: Message-ID: <42A08D34.306@tds.net> Olli Rajala wrote: > Well, I asked about tutorials, but maybe this was not so good day, > because it has been quite "silent". :) > > So, good tutorials are still welcome, though I know now how to connect > to the Postgresql database. I just have some problems, though. You might want to try asking on the DB-SIG mailing list... http://www.python.org/sigs/db-sig/ Kent From venkatasubramanian at gmail.com Fri Jun 3 19:12:51 2005 From: venkatasubramanian at gmail.com (venkata subramanian) Date: Fri, 3 Jun 2005 22:42:51 +0530 Subject: [Tutor] insering into lists through slices Message-ID: Hi, I am a newbie to Python (that's very guessable). I simply fail to understand the semantics of the following piece of code. #assuming ls=[1,2,3,4] >>>ls[1:1]=[5,6] #then ls becomes >>> ls [1, 5, 6, 2, 3, 4] i would be happy to know how it works. Basically, ls[1:1] returns an empty list and assigning [5,6] to it, actually inserts the elements... but how? From ajikoe at gmail.com Fri Jun 3 19:25:05 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 3 Jun 2005 19:25:05 +0200 Subject: [Tutor] insering into lists through slices In-Reply-To: References: Message-ID: when you operate slice be carefull of the position of pointer which slice the list: L = [ 0 , 1 , 2 , 3] ^ ^ pos 0 1 That's why : L = [1,2,3] L[0:1] = [7] print L # will replace element 1 L = [1,2,3] L[1:1] = [7] print L # will insert 7 between element 1 and 2 pujo On 6/3/05, venkata subramanian wrote: > Hi, > I am a newbie to Python (that's very guessable). > I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > > i would be happy to know how it works. > > Basically, ls[1:1] returns an empty list and assigning [5,6] to it, > actually inserts the elements... but how? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Jun 3 19:45:32 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 3 Jun 2005 18:45:32 +0100 Subject: [Tutor] interactif or not References: <20050603100120.GF3155@obs.unige.ch> Message-ID: <016f01c56864$0a914cc0$26ba8651@xp> > If I invoke it in a shell.. then it can be verbose > > If it is launched from a crontab.. then it is less verbose. You need to check who the process owner is. That can be done on *Nix by reading the USER environment variable. Cron jobs are usually run under the 'cron' user I believe. Hoever that won;t work if the python script is executed in a shell script that is then executed by a user. Its usually better to make verbosity controllable by a flag - traditionally -v. Thus the default is non verbode and verbosity can be switched on(or even given any one of several levels) as desired. Alan G. From mpalfram at bellsouth.net Fri Jun 3 18:20:13 2005 From: mpalfram at bellsouth.net (mjp) Date: Fri, 03 Jun 2005 12:20:13 -0400 Subject: [Tutor] Webbrowser module Message-ID: <42A0833D.8060405@bellsouth.net> I am using the webbrowser module to open a URL in Mozilla. My question is what happens when I exit from Mozilla. I have a script running on a Desktop with WindowsXP and a Laptop also with windowsXP In the first case return from Mozilla is to the function containing the webbrowser command ,in the other case it restarts the whole script. mike p From dyoo at hkn.eecs.berkeley.edu Fri Jun 3 20:06:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 11:06:56 -0700 (PDT) Subject: [Tutor] insering into lists through slices In-Reply-To: Message-ID: On Fri, 3 Jun 2005, venkata subramanian wrote: > I am a newbie to Python (that's very guessable). > I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > > i would be happy to know how it works. > > Basically, ls[1:1] returns an empty list and assigning [5,6] to it, > actually inserts the elements... but how? Hi Venkata, Actually, this is a gotcha. Usually, when we are doing assignments (=), the left hand side has to be a variable name. For example: ###### >>> x = 42 >>> def double(x): ... return x * 2 ... >>> double(3) = 42 SyntaxError: can't assign to function call >>> 2**3 = 8 SyntaxError: can't assign to operator ###### So we're not allowed to just put anything on the left hand side, since that wouldn't fit well with the concept of assignment. When we're assigning, we're trying to bind some value to some name or place or thing. The reason that we get those SyntaxErrors about in the example above is because the left hand side wasn't describing a valid place for storing things. With that in mind, let's go back to: ls[1:1] = [5,6] This is a kind of assignment that Python does allow. It doesn't mean to take the left hand side and evaluate it, but instead, it means to squeeze the elements of the right hand side into the place described by the left hand side. This is list slice assignment, and it's a special case. (For the gory details on what is allowed on the right hand side of an assignment, you can take a quick look at the Reference Manual: http://docs.python.org/ref/assignment.html but I wouldn't recommend focusing on it too much.) Anyway, hope that makes some sense. Please feel free to ask more questions. From gsf at panix.com Fri Jun 3 20:07:10 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 3 Jun 2005 14:07:10 -0400 Subject: [Tutor] Building an SQL query In-Reply-To: <011801c567bb$d0aa63a0$26ba8651@xp> References: <57aa550605060206484a305bcb@mail.gmail.com> <010801c567b3$226fdb10$26ba8651@xp> <57aa55060506021405775eb6fb@mail.gmail.com> <011801c567bb$d0aa63a0$26ba8651@xp> Message-ID: <20050603180710.GC21991@panix.com> On Thu, Jun 02, 2005 at 10:41:20PM +0100, Alan G wrote: > Why not convert the list to a tuple before applying str(): > > str(tuple(ids_to_process)) I'm just getting started with Python and PostgreSQL but I found that str(tuple(valueList)) wouldn't work for me because I had a few values with apostrophes. PostgreSQL needed 'Lion''s Mane' but Python was sending it "Lion's Mane", so I ended up writing this little function: def sqlNice(valueList): count = 1 y = '(' for x in valueList: x = x.replace("'", "''") y = y + "'" + x + "'" if count < len(valueList): y = y + ', ' count = count + 1 y = y + ')' y = y.replace("'NULL'", 'NULL') return y Does anyone see any major stumbling blocks in that? On a side note, I've struggled with PyGreSQL. At first I was using the pg module, but I switched to pgdb when insert() wasn't working for me and I thought I would have less trouble using something that's DB-API compliant. There seemed to be more documentation there, and I figured it's a good idea to go with the standard. However, it does seem like I'm covering ground I'm sure someone else has already crossed when I create these re functions to manipulate queries. For inserts, at least, it seems a Python dictionary should be able to do the job nicely. gabe From dyoo at hkn.eecs.berkeley.edu Fri Jun 3 20:09:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 11:09:35 -0700 (PDT) Subject: [Tutor] insering into lists through slices In-Reply-To: Message-ID: > (For the gory details on what is allowed on the right hand side of an ^^^^^ > assignment, you can take a quick look at the Reference Manual: Hi Venkata, Gaaa, I don't know my left from my right. *grin* I meant to say "left" hand side, since that's the target of the assignment. There's no restriction on what can be on the right hand side, except that it needs to be an expression. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Fri Jun 3 20:32:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 11:32:10 -0700 (PDT) Subject: [Tutor] Building an SQL query In-Reply-To: <20050603180710.GC21991@panix.com> Message-ID: On Fri, 3 Jun 2005, Gabriel Farrell wrote: > def sqlNice(valueList): > count = 1 > y = '(' > for x in valueList: > x = x.replace("'", "''") > y = y + "'" + x + "'" > if count < len(valueList): > y = y + ', ' > count = count + 1 > y = y + ')' > y = y.replace("'NULL'", 'NULL') > return y > > Does anyone see any major stumbling blocks in that? Hi Gabriel, Hmmm... there's got be something already in PyGreSQL that does most of that, and if there is, let's avoid reinventing the wheel. Let me check... ok, there is an undocumented function in pg.py that does the individual value quotation in pgdb._quote(). It looks like you might be able to get away with: ###### def sqlNice(valueList): quotedValues = [str(pgdb._quote(x)) for x in valueList] return '(' + ','.join(quotedValues) + ')' ###### That being said, I feel nervous about advocating using an underscored function, since that's a hint that it's not a part of the interface to the pydb module. Maybe you can contact the author and ask if '_quote()' could be renamed to 'quote()', or at least to provide some kind of official access to the quote function. ... Wait a minute. According to the content of the _quote() function, it handles tuples and lists properly: ### pgdb.py, from PyGreSQL-3.6.2 ### def _quote(x): if isinstance(x, DateTime.DateTimeType): x = str(x) elif isinstance(x, unicode): x = x.encode( 'utf-8' ) if isinstance(x, types.StringType): x = "'" + string.replace( string.replace(str(x), '\\', '\\\\'), "'", "''") + "'" elif isinstance(x, (types.IntType, types.LongType, types.FloatType)): pass elif x is None: x = 'NULL' elif isinstance(x, (types.ListType, types.TupleType)): x = '(%s)' % string.join(map(lambda x: str(_quote(x)), x), ',') elif hasattr(x, '__pg_repr__'): x = x.__pg_repr__() else: raise InterfaceError, 'do not know how to handle type %s' % type(x) return x ###### So you should be able to pass lists without any problems. Can you show us what some of your SQL execution statements have looked like? You should be able to do something like: ###### cursor.execute("select name from foo where id in %s", ([1, 2, 3, 4, 5]) ###### Best of wishes! From CTaylor at tradepointsystems.com Fri Jun 3 20:34:08 2005 From: CTaylor at tradepointsystems.com (Taylor, Chris) Date: Fri, 3 Jun 2005 14:34:08 -0400 Subject: [Tutor] python and apache.... Message-ID: How do I execute a python script on my apache server? *(I am attempting to install google's sitemap generator... thanks Chris STATEMENT OF CONFIDENTIALITY: The information contained in this electronic message is intended for the exclusive use of the addressee(s) and may contain confidential information. If you are not the intended recipient of this email, be advised you have received this message in error and that any use, dissemination, forwarding, printing, or copying is strictly prohibited. Please notify TradePoint Systems LLC immediately at (603) 889-3200 and destroy all copies of this message and any attachments. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050603/5d54d50f/attachment.htm From alan.gauld at freenet.co.uk Fri Jun 3 20:53:13 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 3 Jun 2005 19:53:13 +0100 Subject: [Tutor] Postgresql+Python -tutorial? References: Message-ID: <018101c5686d$7eff9450$26ba8651@xp> > I've been using MySQL up this day, but would like to convert > my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? The reason I ask is that I am torn between these two for my own use. Up until now I've been a happy user of Intebase on both Windows and Linux but I'd like to move my Linux DB to an Opensource one and although Firebird is the obvious choice one of the big two would offer good experience(*). But which one? Oh, I can install additional modules, but it would be great if Ubuntu had them... Ubuntu??? A linux distro maybe? (*) I'm currently using SqlLite for my online tutorial on database programming but the more I use it the less I like it! To the extent that I might change to one of the others even though it means a re-write of the tutorial topic... Alan G. From mhansen at cso.atmel.com Fri Jun 3 20:54:01 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 03 Jun 2005 12:54:01 -0600 Subject: [Tutor] question about "hiding" a function/method in a class In-Reply-To: References: Message-ID: <42A0A749.2020304@cso.atmel.com> > Subject: > Re: [Tutor] question about "hiding" a function/method in a class > From: > Kent Johnson > Date: > Fri, 03 Jun 2005 09:45:20 -0400 > > CC: > tutor at python.org > > > Mike Hansen wrote: > >> class DBField(object): >> def __init__(self, fieldName): >> self.fieldName = fieldName >> self.type = "" >> self.size = 0 >> self.notNull = False >> self.unique = False >> self.references = "" >> self.default = "" >> >> def printField(self): >> self.fieldStr = " %s %s" %(self.fieldName, self.type) >> if self.size > 0: >> self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) >> if self.notNull: >> self.fieldStr = "%s NOT NULL" %self.fieldStr >> if self.unique: >> self.fieldStr = "%s UNIQUE" %self.fieldStr >> if self.default: >> self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, >> self.default) >> # if self.references >> return self.fieldStr >> >> def __getattr__(self, attrname): >> if attrname == "fieldStr": >> return self.printField() >> else: >> raise AttributeError, attrname >> --------------------------- >> >> I was wondering if I should "hide" the printField function, so I or >> someone else won't do x.printField() in the main program but use the >> x.fieldStr attribute. If so, how would I do that, def >> __printField(self):? How would I call it from __getattr__? I know I'm >> not really hiding it ;just mangling it. On the other hand, I guess it >> doesn't matter. What do you think? > > > Python programmers tend to take the attitude "We're all adults here" > towards things like this. We use conventions to put warning labels where > appropriate, then trust the client programmer to do what is right for them. > > So, to answer your direct question, yes, you could call the method > __printField(), which nominally hides the name from other modules, or > _printField(), which by convention marks the method as for internal use > only (a warning label). You would call it from __getattr__() as > __printField() or _printField(). (A quick experiment would have answered > this part of the question.) > > However, for your particular usage of dynamically computing the value of > a field, there is a better way to do this - use a property. > > class DBField(object): > def _printField(self): > ... > > # Create a read-only fieldStr attribute whose value is computed by > _printField() > fieldStr = property(_printField) > > # Remove _printField so it can't be called directly > del _printField > > > A few more comments: > - The name _printField() is a bit of a misnomer since nothing is > printed; _getFieldStr() might be a better name. > - Another, simpler way to do this is to define __str__() instead of > _printField() and fieldStr; then clients can just call str(field) to get > the string representation. This will work well if you don't need any > other string representation. > - Of course you could also just define getFieldStr() and forget about > the fieldStr attribute entirely. This is also a very simple, > straightforward approach. > > Kent > Doh, I forgot about properties! If I had read a little more in Learning Python on the page with __getattr__, I might have noticed properties. I might go with the "Simple is better than complex" approach using getFieldStr(). I agree that printField wasn't sounding like a good name. Thanks for the comments. Mike From alan.gauld at freenet.co.uk Fri Jun 3 20:57:58 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 3 Jun 2005 19:57:58 +0100 Subject: [Tutor] question about "hiding" a function/method in a class References: <42A05872.8090902@cso.atmel.com> Message-ID: <018801c5686e$287d51c0$26ba8651@xp> > I haven't done much OO in Python yet. For various web apps we write, we usually > write up a DB schema in a spreadsheet. Wow! How exactly do you represent a schema in a spreadsheet? I confess I cannot conceive of such a thing. Can you send a representative sample to illustrate? > create the tables in the database. I thought it would be neat to save the > spreadsheet as a csv file and have python write the sql script. So I started to > write the Python program. You do know that there are lots of ERD programs that allow you to draw the schema as an ERD and generate the SQL DDL directly? In fact even Visio can do that. Alan G. From alan.gauld at freenet.co.uk Fri Jun 3 21:07:33 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 3 Jun 2005 20:07:33 +0100 Subject: [Tutor] insering into lists through slices References: Message-ID: <019101c5686f$7fd76bd0$26ba8651@xp> > I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > Basically, ls[1:1] returns an empty list and assigning [5,6] to > it, actually inserts the elements... but how? ls[1:1] returns whatever lies between ls item 1 and ls item 1 which is nothing. ls[1:1] = [5.6] inserts the contents of [5,6] between ls item 1 and ls item 1 - in other words at index 1 - which results in [1,5,6,2,3,4] So the behaviour of [1:1] is consistent, it refers to the items between index 1 and 1. Similarly ls[2:3] refers to whats between 2 and 3 which is 3 ls[2,3 = [5,6] replaces whats between 2 and 3 with 5,6 so the result is: [1,2,5,6,4] Note that the numbers in a slice refer to the commas not the list indexes (to take a simplistic view, for a more accurate one read the docs onslicing!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mhansen at cso.atmel.com Fri Jun 3 21:52:10 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 03 Jun 2005 13:52:10 -0600 Subject: [Tutor] question about "hiding" a function/method in a class In-Reply-To: <018801c5686e$287d51c0$26ba8651@xp> References: <42A05872.8090902@cso.atmel.com> <018801c5686e$287d51c0$26ba8651@xp> Message-ID: <42A0B4EA.3040509@cso.atmel.com> Alan G wrote: >>I haven't done much OO in Python yet. For various web apps we write, > > we usually > >>write up a DB schema in a spreadsheet. > > > Wow! How exactly do you represent a schema in a spreadsheet? > I confess I cannot conceive of such a thing. Can you send a > representative sample to illustrate? > Maybe it's not a "schema" exactly. |Table Name|Fields |Type |Size|Primary Key|Not Null|Unique|Foreign Key| ... |areas |area_id |serial | |x |x |x | | | |area |varchar|80 | |x |x | | | |enabled |boolean| | |x | | | |'s represent each cell. It's just a way to organize your thoughts, and have something a little more readable than an SQ script for a DB schema. There's been less than 20 tables in a database for most of these applications that we write. It's clear enough to see the relations(there's another column references). > >>create the tables in the database. I thought it would be neat to > > save the > >>spreadsheet as a csv file and have python write the sql script. So I > > started to > >>write the Python program. > > > You do know that there are lots of ERD programs that allow you to draw > the schema as an ERD and generate the SQL DDL directly? In fact even > Visio > can do that. > > Alan G. > Can you point me to some Open Source/Free ERD programs that work with Postgre?(I'll google after I send this message.) I'd certainly would like to look at ways to do this better. Last time I looked at Visio which was Visio 2000, the ERD stuff cost extra and was very unstable. Mike From olli.rajala at gmail.com Fri Jun 3 22:07:39 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Fri, 3 Jun 2005 23:07:39 +0300 Subject: [Tutor] Postgresql+Python -tutorial? In-Reply-To: <018101c5686d$7eff9450$26ba8651@xp> References: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: I said: > > I've been using MySQL up this day, but would like to convert > > my program to use Postgresql. And then Alan G replied: > I'm curious. Why? > Is there some advantage to Postgres over MySql? Well, I'm not 100% sure. I've been using MySql some years now. It may sound that I know much, but I've done only some very basic programs, so... But I know something about the differences. Quite many system administrator don't think MySQL as Real SQL(tm) database. It has been improved during last years, but it doesn't meet the SQL standards (yet) but Postgresql does that. That's probably the biggest reason. If you want to do it by easy way, use MySQL, there just is so much more tutorials and other info around the Net, but if you want to get system that meet standards, try Postgresql. Oh, and thanks for the guy who suggested me the other list concentrating for databases. I got there the info I needed and now my program is under total refactoring. At least the sql side... ;) > Ubuntu??? A linux distro maybe? Yep. The best of the best of the best. :) http://www.ubuntulinux.org For those who know something about Linux, it's 'Debian loaded with current software'. ;) I mean, it's based on Debian, but the dev cycle is much faster than with Debian. Yours, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From python at venix.com Fri Jun 3 22:15:52 2005 From: python at venix.com (Lloyd Kvam) Date: Fri, 03 Jun 2005 16:15:52 -0400 Subject: [Tutor] Building an SQL query (Gabriel Farrell) In-Reply-To: References: Message-ID: <1117829752.1334.0.camel@www.venix.com> The code to update the database should look something like: the_cursor.execute( sql_cmd, data) I am not using postgresql so I do not know the place-holder mark for your module. You can get that from the module documentation. So sql_cmd could be something like "UPDATE my_table SET title= where record_id=" If data gets passed as a tuple (some modules support dict), data is ("Lion's Mane", 12345) For mysql the place-holder is %s, and the code would be the_cursor.execute("UPDATE my_table SET title=%s where record_id=%s", ("Lion's Mane", 12345) ) > I'm just getting started with Python and PostgreSQL but I found that > str(tuple(valueList)) wouldn't work for me because I had a few values > with apostrophes. PostgreSQL needed 'Lion''s Mane' but Python was > sending it "Lion's Mane", so I ended up writing this little function: > > def sqlNice(valueList): > count = 1 > y = '(' > for x in valueList: > x = x.replace("'", "''") > y = y + "'" + x + "'" > if count < len(valueList): > y = y + ', ' > count = count + 1 > y = y + ')' > y = y.replace("'NULL'", 'NULL') > return y > > Does anyone see any major stumbling blocks in that? > > On a side note, I've struggled with PyGreSQL. At first I was using > the pg module, but I switched to pgdb when insert() wasn't working for > me and I thought I would have less trouble using something that's > DB-API compliant. There seemed to be more documentation there, and I > figured it's a good idea to go with the standard. However, it does > seem like I'm covering ground I'm sure someone else has already > crossed when I create these re functions to manipulate queries. For > inserts, at least, it seems a Python dictionary should be able to do > the job nicely. > > gabe -- Lloyd Kvam Venix Corp -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Fri Jun 3 22:38:07 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 13:38:07 -0700 (PDT) Subject: [Tutor] python and apache.... In-Reply-To: Message-ID: On Fri, 3 Jun 2005, Taylor, Chris wrote: > How do I execute a python script on my apache server? > > *(I am attempting to install google's sitemap generator... Hi Chris, This is more of an Apache configuration question, so you may get better help by asking on an Apache-specific forum. It's not that we don't like getting questions, but we want to keep the content on Tutor focused on learning Python. In any case, here are details on setting up Apache support for Python: http://httpd.apache.org/docs/misc/FAQ.html#CGIoutsideScriptAlias http://httpd.apache.org/docs-2.0/howto/cgi.html The second link, in particular, should be really helpful; when the documentation refers to '.pl', add a '.py' in there too, and you should be ok. *grin* If you have more questions on setting up Apache, again, you'll probably get better answers by asking on a forum like: http://httpd.apache.org/userslist.html Best of wishes to you. From dyoo at hkn.eecs.berkeley.edu Fri Jun 3 22:45:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 13:45:02 -0700 (PDT) Subject: [Tutor] Postgresql+Python -tutorial? In-Reply-To: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: On Fri, 3 Jun 2005, Alan G wrote: > > I've been using MySQL up this day, but would like to convert my > > program to use Postgresql. > > I'm curious. Why? > Is there some advantage to Postgres over MySql? Hi Alan, Yes. The 'MySQL Gotchas' page details specifically some of the tricky areas that are MySQL-specific: http://sql-info.de/mysql/gotchas.html Postgres behaves a lot like Python in that it'll die early rather than try to guess at what the user means. Postgres handles bad data much more responsibly, and usually doesn't quietly fail the way that MySQL does. Best of wishes! From cyresse at gmail.com Fri Jun 3 22:45:29 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat, 4 Jun 2005 08:45:29 +1200 Subject: [Tutor] [Pythoncard-users] TextField bug? In-Reply-To: <20050603160815.48128.qmail@web51404.mail.yahoo.com> References: <20050603160815.48128.qmail@web51404.mail.yahoo.com> Message-ID: What's tfStudy? I assume it's your textfield.What are the attributes of your text field in the resource file? If you copy and post your code and resource file somewhere like this - http://www.rafb.net/paste/ it'd be a lot easier to figure out. On 6/4/05, John Henry wrote: > > Thanks for the reply. > > "What's the platform ?" > > Windows XP fp 2 > > "Version of wxPython" > > wxPython2.5-win32-unicode-2.5.4.1-py23.exe > > "and of Python ?" > > 2.3.5 > > "Do the Pythoncard samples work OK ?" > > Yes. > > "How about the wxPython demos ?" > > I don't see any demo ap in the wxPython directory. > > I am beginning to wonder if it has to do with the > keyPress event I am trying. This is what I am doing: > > #********* > def on_tfStudy_keyPress(self, event): > keyCode = event.keyCode > if keyCode==13 : > ...some processing code... > else: > event.skip() > #********* > > Without this event, the program doesn't crash. > > > > Thanks, > > -- > John > > > > > -----Original Message----- > From: pythoncard-users-admin at lists.sourceforge.net > [mailto:pythoncard-users-admin at lists.sourceforge.net] > On Behalf Of Liam Clarke > Sent: Friday, June 03, 2005 4:57 AM > To: pythoncard-users at lists.sourceforge.net > Subject: Re: [Pythoncard-users] TextField bug? > > > > > > On 6/3/05, Alex Tweedly wrote: > kimwaic888-pythoncard at yahoo.com wrote: > > >Hello list, > > > >I am having touble with textfield objects in > >Pythoncard - I am using the latest version downloaded > > >from www.pythoncard.org (ver 0.81?). > > > >I have a no-brainer application and when I run it, > the > >moment I hit a key when inside a textfield, I get an > >exception in class point within _core.py, method > >__getitem__. The code says: > > > > def __getitem__(self, index): > > return self.Get()[index] > > > >and it's choking on indexing out-of-range. > > > >I've checked and the size of self.Get() is 2 and the > >value of index is 2 and that's why it crashed. > > > >As I said, this is a no-brainer ap (just a textfield > >and nothing else). What's wrong? > > > > > > > What's the platform ? Version of wxPython, and of > Python ? > Do the Pythoncard samples work OK ? > How about the wxPython demos ? > > -- > Alex Tweedly http://www.tweedly.net > > > > -- > No virus found in this outgoing message. > Checked by AVG Anti-Virus. > Version: 7.0.322 / Virus Database: 267.5.2 - Release > Date: 03/06/2005 > > > > ------------------------------------------------------- > This SF.Net email is sponsored by Yahoo. > Introducing Yahoo! Search Developer Network - Create > apps using Yahoo! > Search APIs Find out how you can build Yahoo! directly > into your own > Applications - visit > http://developer.yahoo.net/?fr=offad-ysdn-ostg-q22005 > _______________________________________________ > Pythoncard-users mailing list > Pythoncard-users at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/pythoncard-users > > > > > > Ai, please post the whole error message, is _core.py > part of the Pythoncard package? I get the feeling it's > a part of wxPython. > -- > 'There is only one basic human right, and that is to > do as you damn well please. > And with it comes the only basic human duty, to take > the consequences.' > > > > ------------------------------------------------------- > This SF.Net email is sponsored by: NEC IT Guy Games. How > far can you shotput > a projector? How fast can you ride your desk chair down the office luge > track? > If you want to score the big prize, get to know the little guy. > Play to win an NEC 61" plasma display: http://www.necitguy.com/?r=20 > _______________________________________________ > Pythoncard-users mailing list > Pythoncard-users at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/pythoncard-users > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050604/c430f0f3/attachment-0001.html From alan.gauld at freenet.co.uk Sat Jun 4 00:16:02 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 3 Jun 2005 23:16:02 +0100 Subject: [Tutor] question about "hiding" a function/method in a class References: <42A05872.8090902@cso.atmel.com><018801c5686e$287d51c0$26ba8651@xp> <42A0B4EA.3040509@cso.atmel.com> Message-ID: <01c701c56889$d441d6a0$26ba8651@xp> > Maybe it's not a "schema" exactly. > > |Table Name|Fields |Type |Size|Primary Key|Not Null|Unique|Foreign Key| ... > > |'s represent each cell. It's just a way to organize your thoughts, and have > something a little more readable than an SQ script for a DB schema. There's been > less than 20 tables in a database for most of these applications that we write. > It's clear enough to see the relations(there's another column references). OK, so its just a tabular version of the SQL statements, I see. I guess that works for small schenas, I tend to think in terms of several hundred tables in a schema so I forget not everyone is doing those kinds of things! > > You do know that there are lots of ERD programs that allow you to draw > > the schema as an ERD and generate the SQL DDL directly? In fact even > > Visio > Can you point me to some Open Source/Free ERD programs that work with > Postgres? I've never used Postgres but I've used several commercial tools that generate Oracle, SQL Server, Sybase, Informix, DB2, etc. So I suspect they have postgres DDL drivers too. A couple of tools that spring to mind are Popkins System Architect and ERWin. Both are commercial but ERWin can be had for less than a single day of a contractor, and Popkins for less than a week. For any serious database development they pay back almost immediately. I've used Visio too for a smaller system - about 60-70 tables and it worked OK with Oracle. Again it cost less than a day of a staffer's time never mind a contractor! > (I'll google after I send this message.) I'd certainly would like to > look at ways to do this better. I don't know of any free tools but I'll be surprised if there aren't some at least - even if just demos with limited numbers of tables. The commercial tools are so cheap(relatively) that we've never even looked for freeware... Many of the UML tools (BOrland, iLogix, Rational Rose etc) have free trial versions which might be workable, at least to prove the concept before investing real money... Alan G. From missive at hotmail.com Sat Jun 4 00:21:42 2005 From: missive at hotmail.com (Lee Harr) Date: Sat, 04 Jun 2005 02:51:42 +0430 Subject: [Tutor] Building an SQL query Message-ID: >data = {} >data['ids_to_process'] = ['1','2','3','5','7','11'] > >query = ''' > UPDATE my_table > SET state = 'processed' > WHERE id IN ARRAY%(ids_to_process)s >''' >db.execute(query, data) > Sorry. It should look like ... query = ''' UPDATE my_table SET state = 'processed' WHERE id = ANY(ARRAY%(ids_to_process)s) ''' _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From missive at hotmail.com Sat Jun 4 00:28:41 2005 From: missive at hotmail.com (Lee Harr) Date: Sat, 04 Jun 2005 02:58:41 +0430 Subject: [Tutor] Postgresql+Python -tutorial? Message-ID: >> > I've been using MySQL up this day, but would like to convert my >> > program to use Postgresql. >> >>I'm curious. Why? >>Is there some advantage to Postgres over MySql? > >Postgres behaves a lot like Python in that it'll die early rather than try >to guess at what the user means. Postgres handles bad data much more >responsibly, and usually doesn't quietly fail the way that MySQL does. > That describes it pretty well for me. That plus the fact that mysql devs kept saying things like "relational integrity? What do you need that for?" You mean in a relational database? Ah. Hmm.... _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From gsf at panix.com Sat Jun 4 01:00:37 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 3 Jun 2005 19:00:37 -0400 Subject: [Tutor] Building an SQL query (Gabriel Farrell) In-Reply-To: <1117828209.336.58.camel@www.venix.com> References: <1117828209.336.58.camel@www.venix.com> Message-ID: <20050603230037.GB7568@panix.com> On Fri, Jun 03, 2005 at 03:50:09PM -0400, Lloyd Kvam wrote: > The code to update the database should look something like: > the_cursor.execute( sql_cmd, data) > In PyGreSQL/pgdb it's cursor.execute(query[, params]) but it means more or less the same thing because pgdb's paramstyle (I knew from the DB-API[1] to look in help(pgdb) for "paramstyle") is "pyformat". I googled that and found some explanation of pyformat in a message[2] on the DB-SIG mailing list. To quickly summarize that message, pyformat means the string fed to cursor.execute() should follow all the usual rules of Python string formatting. Knowing this, I can now execute my query thusly: >>> import pgdb >>> db = pgdb.connect(database='asdc') >>> cursor = db.cursor() >>> data = { ... 'noteType': None, ... 'note': "Lion's Mane", ... 'recordIdentifier': 'gsf136' ... } >>> cursor.execute("INSERT INTO notes (notetype, note, recordidentifier) \ ... VALUES (%(noteType)s, %(note)s, %(recordIdentifier)s)", data) >>> db.commit() Note that the re matching I had to do before is now taken care of by pgdb (in the _query() function Danny Yoo was kind enough to track down). Before the query gets to PostgreSQL, the None value turns into a NULL and "Lion's Mane" transforms into 'Lion''s Mane'. No re incantations necessary! gabe [1] http://www.python.org/peps/pep-0249.html [2] http://aspn.activestate.com/ASPN/Mail/Message/db-sig/1632007 From zamb at saudi.net.sa Sat Jun 4 01:32:25 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sat, 04 Jun 2005 02:32:25 +0300 Subject: [Tutor] interactif or not In-Reply-To: <016f01c56864$0a914cc0$26ba8651@xp> References: <20050603100120.GF3155@obs.unige.ch> <016f01c56864$0a914cc0$26ba8651@xp> Message-ID: <1117841545.14760.12.camel@localhost.localdomain> On Fri, 2005-06-03 at 18:45 +0100, Alan G wrote: > > If I invoke it in a shell.. then it can be verbose > > > > If it is launched from a crontab.. then it is less verbose. > > You need to check who the process owner is. > > That can be done on *Nix by reading the USER environment > variable. Cron jobs are usually run under the 'cron' user > I believe. > > Hoever that won;t work if the python script is executed > in a shell script that is then executed by a user. Its usually > better to make verbosity controllable by a flag > - traditionally -v. Thus the default is non verbode and > verbosity can be switched on(or even given any one of > several levels) as desired. > > Alan G. > I think there's a better solution. Here's a quote from the ?bash? manual: ?An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.? >From above you can examine the ?$-? environment variable and check for ?i? in it, if it exist you have an interactive ?bash? shell, if not you have a non-interactive ?bash? shell. However this only works if you're using ?bash? (or, maybe, compatible shells like ?ksh?, but I'm not sure). The other option would be to check for the environment variable ?$PS1?. If it exist, then it's most likely an interactive shell (and I think it works with other shells like ?csh?, again I'm not sure as I never worked with any other shell but ?bash?). Hope this helpful to someone. Ziyad. From spartan-ii at tds.net Sat Jun 4 02:40:03 2005 From: spartan-ii at tds.net (spartan-ii@tds.net) Date: Fri, 03 Jun 2005 20:40:03 -0400 Subject: [Tutor] Class reference problem? Message-ID: <42A0F863.90703@tds.net> for item in function1(args): object = class() if (function2(item)): if (condition): object.variable = value object.function() print object # debug print object #debug The above pseudo code (not really, but close enough) is essentially what I'm playing with. I hope it gives a sense of what I'm trying to do. Any way, the debug lines both print "<__main__.CLASSNAME instance at ADDRESS>" like they should, but the addresses never match up. This leads me to believe that the original object isn't being referenced inside the second if block. This idea is reinforced slightly by the fact that outside of the two if blocks, the variable of the original object has not been modified. I've not encountered this problem before and I really have no idea what I should Google for. So, am I missing something or is there a way to get around this problem? This is being attempted with Python 2.4.1, by the way. I thank you in advance and apologize if I simply have not researched by problem thoroughly enough. From dyoo at hkn.eecs.berkeley.edu Sat Jun 4 03:18:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Jun 2005 18:18:27 -0700 (PDT) Subject: [Tutor] Class reference problem? In-Reply-To: <42A0F863.90703@tds.net> Message-ID: On Fri, 3 Jun 2005, spartan-ii at tds.net wrote: > for item in function1(args): > object = class() > if (function2(item)): > if (condition): > object.variable = value > object.function() > print object # debug > print object #debug > > The above pseudo code (not really, but close enough) is essentially what > I'm playing with. I hope it gives a sense of what I'm trying to do. Hello! Hmmm... you may want to modify the print statements slightly to make it more clear which of the two print statements are being displayed. That is, I'd recommend you distinguish the debug statements by putting some kind of mark, like: ###### for item in function1(args): object = class() if (function2(item)): if (condition): object.variable = value object.function() print "inner", object # debug print "outer", object #debug ###### As the code stands, it's not clear that 'condition' is ever set to true. When you mention that: > Any way, the debug lines both print "<__main__.CLASSNAME instance at > ADDRESS>" like they should, but the addresses never match up. there is one alternative explanation for what you're seeing: it's possible that all of the print statements are coming off the outer print statement alone, and that neither the 'function2()' nor 'condition' branches are being taken. I just want to make sure you're testing what you think you're testing. *grin* Best of wishes to you! From kent37 at tds.net Sat Jun 4 03:30:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Jun 2005 21:30:53 -0400 Subject: [Tutor] Class reference problem? In-Reply-To: <42A0F863.90703@tds.net> References: <42A0F863.90703@tds.net> Message-ID: <42A1044D.8000008@tds.net> spartan-ii at tds.net wrote: > for item in function1(args): > object = class() > if (function2(item)): > if (condition): > object.variable = value > object.function() > print object # debug > print object #debug > > The above pseudo code (not really, but close enough) is essentially what > I'm playing with. I hope it gives a sense of what I'm trying to do. > > Any way, the debug lines both print "<__main__.CLASSNAME instance at > ADDRESS>" like they should, but the addresses never match up. Can you post some working code that shows the problem? Thanks, Ken From spartan-ii at tds.net Sat Jun 4 06:39:14 2005 From: spartan-ii at tds.net (spartan-ii@tds.net) Date: Sat, 04 Jun 2005 00:39:14 -0400 Subject: [Tutor] Class reference problem? In-Reply-To: References: Message-ID: <42A13072.8000301@tds.net> > Hmmm... you may want to modify the print statements slightly to make > it more clear which of the two print statements are being displayed. > As the code stands, it's not clear that 'condition' is ever set to true. /me slaps himself in the forehead. After modifying the print statements as suggested, it turns out that the memory addresses aren't changing. Only the second print statement was executing (as you said might be the case), which would explain why no two printed memory addresses were ever the same. > I just want to make sure you're testing what you think you're testing. I appreciate it. So, thank you! If you hadn't pointed that out, I would probably have continued pulling my hair out over something so minor as an if statement not being executed. Back to bug searching, I guess. Talk about embarrassing. :) From leec03273 at mac.com Sat Jun 4 18:47:25 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 12:47:25 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please Message-ID: Pythonese/Efficiency/Generalese critique please I'm new to Python and as an exercise created a little utility module. I'm learning from the O'Reilly books and updating that understanding from the 2.4 documentation. The utility produces a csv file of a specified directory tree for import to a spreadsheet application. My first attempt employed os.walk(), but I found converting the results of such more troublesome than the recursive approach of this version. Including the module code in this email puts it a little over the 40K limit (lots of comments) so I uploaded it to my dotMac iDisk: http://homepage.mac.com/lee_cullens/dirtss.py.zip On a Mac (at least) the .py is recognized as an executable and warns of such so Ctrl click (right click) and open with your programming text editor. It would fail to run anyway without arguments. I would appreciate any comments you see fit to offer. Thank you, Lee C Dual 2.5 Power Macintosh G5 (OS 10.4.1) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050604/3cb91b0f/attachment.html From arcege at gmail.com Sat Jun 4 19:32:46 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Sat, 4 Jun 2005 13:32:46 -0400 Subject: [Tutor] interactif or not In-Reply-To: <20050603100120.GF3155@obs.unige.ch> References: <20050603100120.GF3155@obs.unige.ch> Message-ID: <7e5ba92205060410325590158c@mail.gmail.com> On 6/3/05, Cedric BRINER wrote: > > hi, > > How can I know if a script is launched interactively or not because I'd > like to make a script verbose or not depending if it is executed as > interactive or not. > > eg. > > If I invoke it in a shell.. then it can be verbose > > If it is launched from a crontab.. then it is less verbose. > > Ced. > If you want to know if your program has been launched from an interactive terminal or from a system background process like cron or init, then you look to see if stdin is a tty. Unix is usually very careful about who has a "controlling tty" and who does not. In Python, file objects have an isatty() method that will return True or False. import sys isinteractive = sys.stdin.isatty() if isinteractive: ... else: ... How you make a program this way manually (i.e. to make a program into cron) is slightly more complicated, but still all the tools are there in Python. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050604/6fbefcc4/attachment.html From flamesrock at gmail.com Sat Jun 4 19:36:02 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Sat, 4 Jun 2005 17:36:02 +0000 Subject: [Tutor] Help: Possible to Pickle and Image? Message-ID: <2c2812b605060410367f371ca0@mail.gmail.com> Hi again :), My goal is to store an image file with lots of information relating to the image and the file it was extracted from, persistantly. Pickle seems like a really easy way to do this. So I'm wondering, is it possible to serialize things like images into a pickle? How do I do it? If not, is there another way? -thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050604/2cbdaaf4/attachment.htm From javier at ruere.com.ar Sat Jun 4 21:17:56 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 04 Jun 2005 16:17:56 -0300 Subject: [Tutor] Help: Possible to Pickle and Image? In-Reply-To: <2c2812b605060410367f371ca0@mail.gmail.com> References: <2c2812b605060410367f371ca0@mail.gmail.com> Message-ID: Aaron Elbaz wrote: > Hi again :), > > My goal is to store an image file with lots of information relating to > the image and the file it was extracted from, persistantly. Pickle seems > like a really easy way to do this. So I'm wondering, is it possible to > serialize > things like images into a pickle? How do I do it? If not, is there > another way? If you mean the image's file content, like file("f.png").read(), then yes, it can be pickled but if you mean an image object from a graphic toolkit then I don't know but wouldn't bet on it. Never the less I would recomend keeping a pointer (a path if it is kept in the filesystem) to the image file and storing the metadata in a database like SQLite. Javier From javier at ruere.com.ar Sat Jun 4 22:21:06 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 04 Jun 2005 17:21:06 -0300 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: Lee Cullens wrote: > Pythonese/Efficiency/Generalese critique please > > The utility produces a csv file of a specified directory tree for import > to a spreadsheet application. My first attempt employed os.walk(), but > I found converting the results of such more troublesome than the > recursive approach of this version. I think it would simplify the logic of your program. > Including the module code in this email puts it a little over the 40K > limit (lots of comments) so I uploaded it to my dotMac iDisk: > http://homepage.mac.com/lee_cullens/dirtss.py.zip > On a Mac (at least) the .py is recognized as an executable and warns of > such so Ctrl click (right click) and open with your programming text > editor. It would fail to run anyway without arguments. > > I would appreciate any comments you see fit to offer. The first time I ran this script ("python dirtss.py Media/ out.csv"), it failed. It was confused by the slash after Media. I didn't even notice it since bash completed the name. In os.path there are functions for managing paths which avoid this and other problems. There is no error handling. The script fails when it meets a directory for which it has no access. Comments are very good but those refering to the behaviour of a function should be placed inside of it. I, personaly, do it like this: # The following code is not tested. def foo(a, b, c): """foo(a:int, b:str, c:sequence):sequence Prepends b, a times to the strings in c. a: The number of times b will be repeated. b: A string to prepend a times to the strings is c. c: A sequence with strings. """ return map(lambda x : (b * a) + x, c) String concatenations like this: for i in range(alvl, clvl): csvline = csvline + '"' + pl[i] + '",' should be replaced by something like the following: cvsline += '"' + pl[alvl:clvl].join('",') Besides that everything else seems OK. I believe using os.walk and the csv module would simplify the code but I'm too lazy to rewrite the script myself. A note on style: I have never seen so many nested functions but I don't dislike it. :) A note on design: Maybe making the function a generator of tuples may simplify the code and separate processing from formatting and output. Maybe first making a better os.walk which flags entries as file, dir, empty dir, link, etc. would make a nice function you might use in the future. Javier From xiaoxia at dix.Mines.EDU Sat Jun 4 05:42:00 2005 From: xiaoxia at dix.Mines.EDU (Xiaoxia Xu) Date: Fri, 3 Jun 2005 21:42:00 -0600 (MDT) Subject: [Tutor] how to generate random numbers in Python Message-ID: Hello, I tried to use a Python library module random() to generate some noise to my data. But the interpreter gave me an error message saying NameError: name 'random' is not defined. I thought this error is because I don't have the pertinent library included. Could anyone tell me how can I get this to work? Many thanks, Ellen From ajikoe at gmail.com Sat Jun 4 23:43:38 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sat, 4 Jun 2005 23:43:38 +0200 Subject: [Tutor] how to generate random numbers in Python In-Reply-To: References: Message-ID: Don't forget to call : import random try: import random print random.randint(2,8) print random.random() good luck pujo On 6/4/05, Xiaoxia Xu wrote: > Hello, > > I tried to use a Python library module random() to generate some > noise to my data. But the interpreter gave me an error > message saying NameError: name 'random' is not defined. > I thought this error is because I don't have the pertinent > library included. Could anyone tell me how can I get this > to work? > > Many thanks, > > Ellen > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Sat Jun 4 23:45:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 4 Jun 2005 14:45:57 -0700 (PDT) Subject: [Tutor] how to generate random numbers in Python In-Reply-To: Message-ID: On Fri, 3 Jun 2005, Xiaoxia Xu wrote: > I tried to use a Python library module random() to generate some noise > to my data. But the interpreter gave me an error message saying > NameError: name 'random' is not defined. I thought this error is > because I don't have the pertinent library included. Could anyone tell > me how can I get this to work? Hi Ellen, Can you show us what you typed in as well? This will help us give you better help, because then we can see exactly how you got that error. There are several ways of getting the same error message, so we need more context to be sure we're answering your question properly. Otherwise, we might respond in a way where we direct our energies toward the error message, and not the underlying issue! Here is a brief tutorial on using modules. We can start by "importing" a module. ###### >>> import random ###### This pulls in the 'random' module, one of the many Standard Library modules described in the documentation here: http://www.python.org/doc/lib/ A 'module' is just some thing, a container: ###### >>> random ###### which holds a lot of useful functions and other things. We can get a directory listing of what's in 'random' by using dir(): ###### >>> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'Random', 'SG_MAGICCONST', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', 'betavariate', 'choice', 'cunifvariate', 'expovariate', 'gammavariate', 'gauss', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'stdgamma', 'uniform', 'vonmisesvariate', 'weibullvariate'] ###### The contents of each module usually have some associated documentation, which we can ask by using the built-in help() function: ###### >>> help(random) ###### We can also look at the Library Reference for information: http://www.python.org/doc/lib/module-random.html Within the 'random' module, we find a function called 'random'. We use dot notation to get at the contents of a module: ###### >>> random.random() 0.1703040598331883 ###### Does this make sense so far? Please feel free to ask more questions, and we'll do what we can to help. Best of wishes! From lee_cullens at mac.com Sat Jun 4 23:52:53 2005 From: lee_cullens at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 17:52:53 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: <6BFEAD96-3BFC-4AAE-8E4B-718F5135D484@mac.com> Thank you for the critique Javier. You made some good points that I will play with before moving on. Beyond that, I intentionally neglected error checking in this exercise as you may have surmised. Checking input arguments and handling access restrictions gracefully would indeed be important components. The initial os.walk() approach I tried is simple in concept: pgo = os.walk(base_directory) for xnode in pgo: but I ended up with much more processing in having to sort the rows and then blank repeated cells, than the recursive listdir approach which gave me the desired ordering in one pass. Lee C From leec03273 at mac.com Sun Jun 5 00:01:19 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 18:01:19 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: <60FD47B0-2AAE-4473-B6CF-2EDAF7DBB829@mac.com> Thank you for the critique Javier. You made some good points that I will play with before moving on. Beyond that, I intentionally neglected error checking in this exercise as you may have surmised. Checking input arguments and handling access restrictions gracefully would indeed be important components. The initial os.walk() approach I tried is simple in concept: pgo = os.walk(base_directory) for xnode in pgo: but I ended up with much more processing in having to sort the rows and then blank repeated cells, than the recursive listdir approach which gave me the desired ordering in one pass. Lee C From leec03273 at mac.com Sun Jun 5 00:07:26 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 18:07:26 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: <478D2C10-AD6C-4BD7-9FBC-D174318D9825@mac.com> Sorry about the double post. I sent with the wrong from address so I resent with the correct address and before I could cancel the first the moderator had let it through :~) Lee C From kent37 at tds.net Sun Jun 5 00:54:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 18:54:02 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: <42A2310A.6070708@tds.net> Lee Cullens wrote: > Pythonese/Efficiency/Generalese critique please > > I'm new to Python and as an exercise created a little utility module. > I'm learning from the O'Reilly books and updating that understanding > from the 2.4 documentation. > > I would appreciate any comments you see fit to offer. I find the nested functions confusing myself; is there a reason they are nested? If they can stand alone I would make them separate top-level functions with names starting with _ to indicate that they are private. dlst = os.listdir(pname) if len(dlst): for dlf in dlst: There is no need for the if(dlst); if the list is empty the iteration will do nothing. You can write this as for dlf in os.listdir(pname): Some blank lines would aid readability. For example before each comment in cellpos() and before each elif in the main conditional block. Do you know there is a csv module that helps to read and write csv files? It will take care of escaping " in your filenames, if such a thing is possible... From kent37 at tds.net Sun Jun 5 00:55:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 18:55:54 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: Message-ID: <42A2317A.8010301@tds.net> Javier Ruere wrote: > for i in range(alvl, clvl): > csvline = csvline + '"' + pl[i] + '",' > > should be replaced by something like the following: > > cvsline += '"' + pl[alvl:clvl].join('",') or maybe more like this: cvsline += '"' + '",'.join(pl[alvl:clvl]) + '",' though if alvl == clvl this will output an empty cell. Kent From javier at ruere.com.ar Sun Jun 5 03:15:01 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 04 Jun 2005 22:15:01 -0300 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <42A2317A.8010301@tds.net> References: <42A2317A.8010301@tds.net> Message-ID: Kent Johnson wrote: > Javier Ruere wrote: > >>for i in range(alvl, clvl): >> csvline = csvline + '"' + pl[i] + '",' >> >>should be replaced by something like the following: >> >>cvsline += '"' + pl[alvl:clvl].join('",') > > > or maybe more like this: > cvsline += '"' + '",'.join(pl[alvl:clvl]) + '",' > > though if alvl == clvl this will output an empty cell. > > Kent True! I should start programming in Python again. :) Javier From javier at ruere.com.ar Sun Jun 5 03:17:37 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 04 Jun 2005 22:17:37 -0300 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <42A2310A.6070708@tds.net> References: <42A2310A.6070708@tds.net> Message-ID: Kent Johnson wrote: > dlst = os.listdir(pname) > if len(dlst): > for dlf in dlst: > > There is no need for the if(dlst); if the list is empty the iteration will do nothing. You can write this as > for dlf in os.listdir(pname): Though it is quite distant, there is an else statement which makes the if construct a requierement. Javier From javier at ruere.com.ar Sun Jun 5 03:32:46 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 04 Jun 2005 22:32:46 -0300 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <60FD47B0-2AAE-4473-B6CF-2EDAF7DBB829@mac.com> References: <60FD47B0-2AAE-4473-B6CF-2EDAF7DBB829@mac.com> Message-ID: Lee Cullens wrote: > The initial os.walk() approach I tried is simple in concept: > > pgo = os.walk(base_directory) > for xnode in pgo: > > > but I ended up with much more processing in having to sort the rows > and then blank repeated cells, than the recursive listdir approach > which gave me the desired ordering in one pass. You have certainly analysed this issue far more than me so you know better but I just can't see the extra processing. I guess I should just give it a try. :) Javier From leec03273 at mac.com Sun Jun 5 03:35:54 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 21:35:54 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <42A2310A.6070708@tds.net> References: <42A2310A.6070708@tds.net> Message-ID: Thanks for the critique Kent On Jun 4, 2005, at 6:54 PM, Kent Johnson wrote: > Lee Cullens wrote: > > >> Pythonese/Efficiency/Generalese critique please >> >> I'm new to Python and as an exercise created a little utility module. >> I'm learning from the O'Reilly books and updating that understanding >> from the 2.4 documentation. >> >> I would appreciate any comments you see fit to offer. >> >> > > I find the nested functions confusing myself; is there a reason > they are nested? If they can stand alone I would make them separate > top-level functions with names starting with _ to indicate that > they are private. > > I did so first for a visual indication of use and relation (eyes of the beholder thing) and second to simplify scope. The latter though is a mute point since (I believe) the scope is the same either way, and my structure does add a little baggage to the recursion which is a negative. Your point is well taken. > dlst = os.listdir(pname) > if len(dlst): > for dlf in dlst: > > There is no need for the if(dlst); if the list is empty the > iteration will do nothing. You can write this as > for dlf in os.listdir(pname): > > Something I wrestled with - but as I needed to recognize an empty directory I needed something to facilitate such ( the for else was no help) so that is what I came up with and still don't see a way around. > Some blank lines would aid readability. For example before each > comment in cellpos() and before each elif in the main conditional > block. > > Good point. I've been letting all the bright colors in WingIDE lull me into forgetting others may see just b&w. > Do you know there is a csv module that helps to read and write csv > files? It will take care of escaping " in your filenames, if such a > thing is possible... > > No, I didn't know. If I do something like this seriously I'll check it out Thanks again, Lee C > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From leec03273 at mac.com Sun Jun 5 03:48:40 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 21:48:40 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: <60FD47B0-2AAE-4473-B6CF-2EDAF7DBB829@mac.com> Message-ID: <5D937591-8962-44BE-B305-DA5F538E5DC7@mac.com> On Jun 4, 2005, at 9:32 PM, Javier Ruere wrote: > Lee Cullens wrote: > >> The initial os.walk() approach I tried is simple in concept: >> >> pgo = os.walk(base_directory) >> for xnode in pgo: >> >> >> but I ended up with much more processing in having to sort the rows >> and then blank repeated cells, than the recursive listdir approach >> which gave me the desired ordering in one pass. >> > > You have certainly analysed this issue far more than me so you know > better but I just can't see the extra processing. I guess I should > just > give it a try. :) > Or that I just was not smart enough to pull it into one pass :~) If this were a serious project I would look into the csv module Kent mentioned and possibly combine the two for a much more succinct module. > Javier > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Jun 5 03:54:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 21:54:55 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <78A5A3F9-2142-42AA-8066-974E85D93A47@mac.com> References: <42A2310A.6070708@tds.net> <78A5A3F9-2142-42AA-8066-974E85D93A47@mac.com> Message-ID: <42A25B6F.1090706@tds.net> Lee Cullens wrote: > On Jun 4, 2005, at 6:54 PM, Kent Johnson wrote: >> dlst = os.listdir(pname) >> if len(dlst): >> for dlf in dlst: >> >> There is no need for the if(dlst); if the list is empty the iteration >> will do nothing. You can write this as >> for dlf in os.listdir(pname): >> > Something I wrestled with - but as I needed to recognize an empty > directory I needed something to facilitate such ( the for else was no > help) so that is what I came up with and still don't see a way around. Ah right, I missed that. >> Some blank lines would aid readability. For example before each >> comment in cellpos() and before each elif in the main conditional block. >> > Good point. I've been letting all the bright colors in WingIDE lull me > into forgetting others may see just b&w. I have syntax highlighting but I still use a lot of vertical white space to divide the code into small sections. Kent From leec03273 at mac.com Sun Jun 5 04:27:50 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sat, 4 Jun 2005 22:27:50 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <42A2317A.8010301@tds.net> References: <42A2317A.8010301@tds.net> Message-ID: <5FEF2914-D471-476A-BFBF-E723716E8F08@mac.com> Well, I've tried both and can't produce what I was doing with the for construct. With a list pl = ['a', 'b', 'c', 'd'] of the path components I'm trying to add justified non repeated path elements, say pl[2] and pl [3] to csvline so that csvline would end up '"",'*x plus '"c","d",' >>> pl = ['a', 'b', 'c'] >>> csvl = '"",' >>> csvl += '"'.join(pl[0:2]) + '",' >>> csvl '"",a"b",' which is intended to be '"","a","b",' Saving one line of code in this module doesn't mean much, but if it were a efficiency in processing it would? Lee C On Jun 4, 2005, at 6:55 PM, Kent Johnson wrote: > Javier Ruere wrote: > >> for i in range(alvl, clvl): >> csvline = csvline + '"' + pl[i] + '",' >> >> should be replaced by something like the following: >> >> cvsline += '"' + pl[alvl:clvl].join('",') >> > > or maybe more like this: > cvsline += '"' + '",'.join(pl[alvl:clvl]) + '",' > > though if alvl == clvl this will output an empty cell. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nequeo at gmail.com Sun Jun 5 09:39:16 2005 From: nequeo at gmail.com (Simon Gerber) Date: Sun, 05 Jun 2005 17:39:16 +1000 Subject: [Tutor] Detecting my own IP address? Message-ID: <42A2AC24.2090500@gmail.com> G'day, I'm currently blundering through a script that will let me configure and then connect to PPTP VPNs from a Linux box. Just a text-based front-end to pptp-client, really. Adding in new VPN configurations was simple. Connecting is a little harder. From the command-line I would normally type: "sudo pon $TUNNEL", where TUNNEL is the name of the connection. This is followed by "sudo route add -net 192.168.1.0 netmask 255.255.255.0 dev ppp0" (as an example), once the tunnel was established. What I would really like the script to be able to do is detect when the tunnel connects, grab the IP address, and then create an appropriate route. At present, the only thing I can think of is to redirect the output of 'ifconfig' into a temporary file, then read it back in and use Python and regular expressions to try and extract the IP info from that. I could *probably* make that work... but I wouldn't feel very proud about it. Does anyone have any clues? I do prefer to figure things out for myself *cough*google*cough*, but in this case I'm not really sure where to start looking. Any help would be appreciated. Regards, From carroll at tjc.com Sun Jun 5 10:32:55 2005 From: carroll at tjc.com (Terry Carroll) Date: Sun, 5 Jun 2005 01:32:55 -0700 (PDT) Subject: [Tutor] Detecting my own IP address? In-Reply-To: <42A2AC24.2090500@gmail.com> Message-ID: The Python Cookbook (1st ed) suggests this, in recipe 10.4 ("Finding Your Own Name and Address): >>> import socket >>> myname = socket.getfqdn(socket.gethostname()) >>> myaddr = socket.gethostbyname(myname) >>> myaddr '192.168.1.120' From kent37 at tds.net Sun Jun 5 11:47:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 05:47:13 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <5FEF2914-D471-476A-BFBF-E723716E8F08@mac.com> References: <42A2317A.8010301@tds.net> <5FEF2914-D471-476A-BFBF-E723716E8F08@mac.com> Message-ID: <42A2CA21.70403@tds.net> Lee Cullens wrote: > Well, I've tried both and can't produce what I was doing with the for > construct. > With a list pl = ['a', 'b', 'c', 'd'] of the path components I'm > trying to add justified non repeated path elements, say pl[2] and pl [3] > to csvline so that csvline would end up '"",'*x plus '"c","d",' > > >>> pl = ['a', 'b', 'c'] > >>> csvl = '"",' > >>> csvl += '"'.join(pl[0:2]) + '",' > >>> csvl > '"",a"b",' > > which is intended to be '"","a","b",' OK, let's try to get this right. Given a list of strings and a divider string, join() returns the strings from the list 'joined' by the divider string. For example, >>> pl = ['a', 'b', 'c'] >>> '","'.join(pl) 'a","b","c' The syntax for this takes a little getting used to; join() is actually a string method; you call it on the divider string and pass it the list of strings to be joined. To make a list of quoted, comma separated values, you also need initial and final quotes: >>> '"' + '","'.join(pl) + '"' '"a","b","c"' In your example you need '","'.join(pl[0:2]) > Saving one line of code in this module doesn't mean much, but if it > were a efficiency in processing it would? Conventional wisdom is that it is more efficient to use the join method. More enlightened wisdom says, don't optimize until you know you have a problem, and the only way to know what is fastest in your program with your data is to test. And of course working code always beats broken code :-) I did some experiments with these alternatives and concluded that if the length of the resulting string is less than about 500-800, the version using += is faster than the one using join(): http://www.pycs.net/users/0000323/weblog/2004/08/27.html So, it is good to know about join(), but write the code the way that is clearest to you. Kent From missive at hotmail.com Sun Jun 5 12:23:50 2005 From: missive at hotmail.com (Lee Harr) Date: Sun, 05 Jun 2005 14:53:50 +0430 Subject: [Tutor] Detecting my own IP address? Message-ID: >At present, the only thing I can think of is to redirect the >output of 'ifconfig' into a temporary file, then read it back in and use >Python and regular expressions to try and extract the IP info from that. That is basically how I do it. See here: http://mail.python.org/pipermail/python-list/2005-January/258883.html _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From cyresse at gmail.com Sun Jun 5 15:29:39 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 6 Jun 2005 01:29:39 +1200 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: <42A2310A.6070708@tds.net> Message-ID: > > > There is no need for the if(dlst); if the list is empty the iteration > will do nothing. You can write this as > > for dlf in os.listdir(pname): > > Though it is quite distant, there is an else statement which makes > the if construct a requierement. > > Javier You could just do - if not len(dlst): #Your else code block here for dlf in os.listdir(pname): and so forth. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050606/d001478d/attachment.html From leec03273 at mac.com Sun Jun 5 17:45:28 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sun, 5 Jun 2005 11:45:28 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: References: <42A2310A.6070708@tds.net> Message-ID: <5864EC52-A33E-4E15-8EFF-95CF57FE0AAA@mac.com> Such would serve to pull the test and the reason for it together - more obvious. Which is a good point in writing code that others may read. Thanks Liam On Jun 5, 2005, at 9:29 AM, Liam Clarke wrote: > > > > There is no need for the if(dlst); if the list is empty the > iteration will do nothing. You can write this as > > for dlf in os.listdir(pname): > > Though it is quite distant, there is an else statement which makes > the if construct a requierement. > > Javier > > > You could just do - > > if not len(dlst): > #Your else code block here > > for dlf in os.listdir(pname): > > and so forth. > > > > -- > 'There is only one basic human right, and that is to do as you damn > well please. > And with it comes the only basic human duty, to take the > consequences.' > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From leec03273 at mac.com Sun Jun 5 18:50:01 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sun, 5 Jun 2005 12:50:01 -0400 Subject: [Tutor] Pythonese/Efficiency/Generalese critique please In-Reply-To: <42A2CA21.70403@tds.net> References: <42A2317A.8010301@tds.net> <5FEF2914-D471-476A-BFBF-E723716E8F08@mac.com> <42A2CA21.70403@tds.net> Message-ID: <961AE2DB-4B65-4F3D-8FFE-F67ED2268BF8@mac.com> OK Kent - got it: My little formating function could be written as (tested) def cellpos(pname, alvl, blvl, clvl): # breakout path components into list pl = pname.split('/') # insert empty cells for repeated names and # add new path components (cells) to csvline csvline = '"",'*(alvl - blvl) + '"' + '","'.join(pl [alvl:clvl]) + '",' return csvline "So, it is good to know about join(), but write the code the way that is clearest to you." One of my thoughts in posting this exercise is to first understand alternatives before I decide what I like best :~) Your points, together with Javier's points on presentation and thoroughness, and Liam's point on making the logic more obvious are appreciated. Thank you all for taking the time to offer your comments, Lee C On Jun 5, 2005, at 5:47 AM, Kent Johnson wrote: > Lee Cullens wrote: > > > OK, let's try to get this right. > > Given a list of strings and a divider string, join() returns the > strings from the list 'joined' by the divider string. For example, > >>>> pl = ['a', 'b', 'c'] >>>> '","'.join(pl) >>>> > 'a","b","c' > > The syntax for this takes a little getting used to; join() is > actually a string method; you call it on the divider string and > pass it the list of strings to be joined. > > To make a list of quoted, comma separated values, you also need > initial and final quotes: > >>>> '"' + '","'.join(pl) + '"' >>>> > '"a","b","c"' > > In your example you need '","'.join(pl[0:2]) > > >> Saving one line of code in this module doesn't mean much, but if it >> were a efficiency in processing it would? >> > > Conventional wisdom is that it is more efficient to use the join > method. More enlightened wisdom says, don't optimize until you know > you have a problem, and the only way to know what is fastest in > your program with your data is to test. And of course working code > always beats broken code :-) > > I did some experiments with these alternatives and concluded that > if the length of the resulting string is less than about 500-800, > the version using += is faster than the one using join(): > http://www.pycs.net/users/0000323/weblog/2004/08/27.html > > So, it is good to know about join(), but write the code the way > that is clearest to you. > > Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050605/516200fd/attachment.html From bill at celestial.net Sun Jun 5 20:29:23 2005 From: bill at celestial.net (Bill Campbell) Date: Sun, 5 Jun 2005 11:29:23 -0700 Subject: [Tutor] Detecting my own IP address? In-Reply-To: References: Message-ID: <20050605182922.GA96037@alexis.mi.celestial.com> On Sun, Jun 05, 2005, Lee Harr wrote: >>At present, the only thing I can think of is to redirect the >>output of 'ifconfig' into a temporary file, then read it back in and use >>Python and regular expressions to try and extract the IP info from that. Why go to a temporary file when you can open a pipe? import os fh = os.popen('ifconfig') #... The advantage of parsing ifconfig output instead of using socket calls is that it allows you to discriminate between multiple interfaces (e.g. most of our dual hosted machines have the primary interface on the private address which probably isn't what is required). One disadvantage of parsing ifconfig is that output varies depending on the operating system. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Systems, Inc. UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The fact is that the Constitution was intended to protect us from the government, and we cannot expect the government to enforce it willingly'' -- Dave E. Hoffmann, Reason Magazine March 2002 From kent37 at tds.net Mon Jun 6 03:53:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 21:53:16 -0400 Subject: [Tutor] Iterate through a list calling functions In-Reply-To: <58B0F1D2-D5EB-11D9-BFBC-000A27B3B070@eastlink.ca> References: <58B0F1D2-D5EB-11D9-BFBC-000A27B3B070@eastlink.ca> Message-ID: <42A3AC8C.7080806@tds.net> David Pratt wrote: > Hi Kent. Thank you for your reply. I gave this a go but get the > following traceback: > ... > result = validator(name, value) > TypeError: 'str' object is not callable > > Have put validators in list and iterate over it as in following: > > validator_list = > [isContainedIn,isDate,isDecimal,isEmail,isEmpty,isInteger... > more validators....] > results={} > for validator in validators_list: > result = validator(name, value) > if type (result) in StringTypes: > # do some stuff... > return results > Are you sure you don't have quoted strings in your validator list? That is what the error message indicates. Can you post a small complete example of the code that fails? or put print repr(validator) before the line that calls validator so you can see exactly what you are trying to call. Kent > Regards, > David > > > On Sunday, June 5, 2005, at 02:03 PM, Kent Johnson wrote: > >> David Pratt wrote: >> >>> Hi. I am creating methods for form validation. Each validator has its >>> own method and there quite a number of these. For each field, I want to >>> evaluate errors using one or more validators so I want to execute the >>> appropriate validator methods from those available. I am iterating over >>> each validator using validateField method to gather my results. It works >>> but it ugly and inefficient. Can someone advise whether there is a >>> better way of doing this. I realize that the validator variable in my >>> iteration is only a string so question is how can I make the validator >>> string reference a function so I may be able to shorten validateField to >>> something similar to this (instead of my long list of ifs which I am not >>> very happy with): >>> >>> for validator in validators_list: >>> result = validator(name, value) >>> if type (result) in StringTypes: >>> results[name] = result >> >> >> Actually you can do exactly that by putting references to the >> validator functions in your list instead of (string) name. For example >> if you have >> validators = [ 'isDecimal', 'isFoo', 'isBar' ] >> >> just change it to >> validators = [ isDecimal, isFoo, isBar ] >> >> and your loop above will work. >> >> Python makes data-driven programming easy :-) >> Kent >> >>> >>> Many thanks >>> David >>> >>> My current situation below: >>> >>> # A large list of validators >>> def isDecimal(name, value): >>> """ Test whether numeric value is a decimal """ >>> result = validateRegex(name, >>> value, >>> r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', >>> errmsg='is not a decimal number.', >>> ignore=None) >>> return result >>> >>> def isZipCode(name, value): >>> """ Tests if field value is a US Zip Code """ >>> result = validateRegex(name, >>> value, >>> r'^(\d{5}|\d{9})$', >>> errmsg='is not a valid zip code.', >>> ignore=None) >>> return result >>> >>> ... more validators >>> >>> # Iterating over validators to gather field errors >>> def validateField(name, value, validators_list, range=None, >>> valid_values=None): >>> """ Validates field input """ >>> results={} >>> for validator in validators_list: >>> if validator == 'isContainedIn': >>> result = isContainedIn(name, value) >>> if type (result) in StringTypes: >>> more... >>> if validator == 'isDate': >>> result = isDate(name, value) >>> if type (result) in StringTypes: >>> more... >>> if validator == 'isDecimal': >>> result = isDecimal(name, value) >>> if type (result) in StringTypes: >>> more... >>> >>> more validators ... >>> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From kent37 at tds.net Mon Jun 6 04:02:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 22:02:52 -0400 Subject: [Tutor] [Fwd: Re: Iterate through a list calling functions] Message-ID: <42A3AECC.9010803@tds.net> Sorry, forwarded to the wrong list. Kent -------- Original Message -------- Subject: Re: [Tutor] Iterate through a list calling functions Date: Sun, 05 Jun 2005 21:53:16 -0400 From: Kent Johnson To: Python Tutor References: <58B0F1D2-D5EB-11D9-BFBC-000A27B3B070 at eastlink.ca> David Pratt wrote: > Hi Kent. Thank you for your reply. I gave this a go but get the > following traceback: > ... > result = validator(name, value) > TypeError: 'str' object is not callable > > Have put validators in list and iterate over it as in following: > > validator_list = > [isContainedIn,isDate,isDecimal,isEmail,isEmpty,isInteger... > more validators....] > results={} > for validator in validators_list: > result = validator(name, value) > if type (result) in StringTypes: > # do some stuff... > return results > Are you sure you don't have quoted strings in your validator list? That is what the error message indicates. Can you post a small complete example of the code that fails? or put print repr(validator) before the line that calls validator so you can see exactly what you are trying to call. Kent > Regards, > David > > > On Sunday, June 5, 2005, at 02:03 PM, Kent Johnson wrote: > >> David Pratt wrote: >> >>> Hi. I am creating methods for form validation. Each validator has its >>> own method and there quite a number of these. For each field, I want to >>> evaluate errors using one or more validators so I want to execute the >>> appropriate validator methods from those available. I am iterating over >>> each validator using validateField method to gather my results. It works >>> but it ugly and inefficient. Can someone advise whether there is a >>> better way of doing this. I realize that the validator variable in my >>> iteration is only a string so question is how can I make the validator >>> string reference a function so I may be able to shorten validateField to >>> something similar to this (instead of my long list of ifs which I am not >>> very happy with): >>> >>> for validator in validators_list: >>> result = validator(name, value) >>> if type (result) in StringTypes: >>> results[name] = result >> >> >> Actually you can do exactly that by putting references to the >> validator functions in your list instead of (string) name. For example >> if you have >> validators = [ 'isDecimal', 'isFoo', 'isBar' ] >> >> just change it to >> validators = [ isDecimal, isFoo, isBar ] >> >> and your loop above will work. >> >> Python makes data-driven programming easy :-) >> Kent >> >>> >>> Many thanks >>> David >>> >>> My current situation below: >>> >>> # A large list of validators >>> def isDecimal(name, value): >>> """ Test whether numeric value is a decimal """ >>> result = validateRegex(name, >>> value, >>> r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', >>> errmsg='is not a decimal number.', >>> ignore=None) >>> return result >>> >>> def isZipCode(name, value): >>> """ Tests if field value is a US Zip Code """ >>> result = validateRegex(name, >>> value, >>> r'^(\d{5}|\d{9})$', >>> errmsg='is not a valid zip code.', >>> ignore=None) >>> return result >>> >>> ... more validators >>> >>> # Iterating over validators to gather field errors >>> def validateField(name, value, validators_list, range=None, >>> valid_values=None): >>> """ Validates field input """ >>> results={} >>> for validator in validators_list: >>> if validator == 'isContainedIn': >>> result = isContainedIn(name, value) >>> if type (result) in StringTypes: >>> more... >>> if validator == 'isDate': >>> result = isDate(name, value) >>> if type (result) in StringTypes: >>> more... >>> if validator == 'isDecimal': >>> result = isDecimal(name, value) >>> if type (result) in StringTypes: >>> more... >>> >>> more validators ... >>> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From nequeo at gmail.com Mon Jun 6 05:32:21 2005 From: nequeo at gmail.com (Simon Gerber) Date: Mon, 6 Jun 2005 13:32:21 +1000 Subject: [Tutor] Detecting my own IP address? In-Reply-To: <20050605182922.GA96037@alexis.mi.celestial.com> References: <20050605182922.GA96037@alexis.mi.celestial.com> Message-ID: <667ca7b60506052032606bae97@mail.gmail.com> Thank you for your suggestions everyone. I do wish to parse ifconfig, as I'm specifically after the address of ppp0. At this stage, I'm only writing the script for my own machine, so the downside to parsing ifconfig does not yet apply. I'm a little curious, however. When you say 'varies depending on the operarating system', are you talking about Windows vs. Linux, or, say, Debian vs. Gentoo? Cheers, From bill at celestial.net Mon Jun 6 06:27:56 2005 From: bill at celestial.net (Bill Campbell) Date: Sun, 5 Jun 2005 21:27:56 -0700 Subject: [Tutor] Detecting my own IP address? In-Reply-To: <667ca7b60506052032606bae97@mail.gmail.com> References: <20050605182922.GA96037@alexis.mi.celestial.com> <667ca7b60506052032606bae97@mail.gmail.com> Message-ID: <20050606042756.GA28309@alexis.mi.celestial.com> On Mon, Jun 06, 2005, Simon Gerber wrote: >Thank you for your suggestions everyone. > >I do wish to parse ifconfig, as I'm specifically after the address of >ppp0. At this stage, I'm only writing the script for my own machine, >so the downside to parsing ifconfig does not yet apply. I'm a little >curious, however. When you say 'varies depending on the operarating >system', are you talking about Windows vs. Linux, or, say, Debian vs. >Gentoo? The output format of ifconfig varies slightly on several Linux machines we have running here ranging from SuSE 9.3 Professional as far back as Caldera OpenLinux 1.2 or so. It's different on the FreeBSD box I'm using for e- mail now, and on an OS X box. SCO OpenServer doesn't return anything useful from ifconfig with now arguments, and one has to parse the output of ``netstat -in'' to get the interface names, then run ifconfig on each name to get full info. The differences aren't great, and it's easy to write regular expressions to extract things like IP address (ipv4 and ipv6), netmask, MAC address, etc. One could probably build a dictionary of regular expressions, keyed on the first and third entries in os.uname() output. I don't do Windows so can't say what it does (knowing Microsoft, it may vary between Windows versions, patch levels, and the phase of the moon :-). Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``... because most politicians and bureaucrats are technological idiots, it's going to be crucial for the rank and file members of the IT community to find its collective voice soon.'' --Michael Vizard, InfoWorld Editor in Chief. From SChitti at manh.com Mon Jun 6 11:19:26 2005 From: SChitti at manh.com (Suri Chitti) Date: Mon, 6 Jun 2005 05:19:26 -0400 Subject: [Tutor] How to open a telnet session and have the python program write to it. Message-ID: <476826C3AD01EC46B351C35C183E532501AEF837@ma-india09.asia.manh.com> Hi, I am attempting a python program that will open a telnet session and input the username/password, cd to a certain directory and leave the session there. I have attempted different combinations of the os.popen etc but as soon as the telnet window is opened the program cannot be coaxed to write to the telnet session (window). I have attempted the telnetlib, but the problem is that the telnet window does not show up. Can anyone give me more info in this matter? Thanks lots, -Suri. ______________________________________________ Name Suri Chitti | Sr. QA Engineer, WM-OS-QA Manhattan Associates Phone: 00 91 80 28418080 xtn.4830 Fax: 00 91 80 51156098 schitti at manh.com http://www.manh.com __________________________________________________ Looking for a new perspective on your supply chain? Plan now to attend Momentum 2005 on May 15 - 18 in Scottsdale, Arizona. Visit http://www.momentummanh.com today and register early for best rates! Momentum 2005 New Perspectives. Infinite Possibilities. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050606/9a105b1b/attachment.html From maxnoel_fr at yahoo.fr Mon Jun 6 12:46:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon, 6 Jun 2005 11:46:40 +0100 Subject: [Tutor] Detecting my own IP address? In-Reply-To: <20050606042756.GA28309@alexis.mi.celestial.com> References: <20050605182922.GA96037@alexis.mi.celestial.com> <667ca7b60506052032606bae97@mail.gmail.com> <20050606042756.GA28309@alexis.mi.celestial.com> Message-ID: On Jun 6, 2005, at 05:27, Bill Campbell wrote: > I don't do Windows so can't say what it does (knowing Microsoft, it > may > vary between Windows versions, patch levels, and the phase of the > moon :-). > > Bill Well, Windows doesn't even do ifconfig. The (more-or-less) equivalent command is ipconfig, except that it has no generic names for network interfaces. What that means, is that instead of eth0 (or en0, or whatever), it uses the full name of your NIC -- which effectively means that the output differs from one machine to another. Good luck with this one :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jeffpeery at yahoo.com Mon Jun 6 16:14:55 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 6 Jun 2005 07:14:55 -0700 (PDT) Subject: [Tutor] resizing an array of strings? Message-ID: <20050606141455.99538.qmail@web30505.mail.mud.yahoo.com> Hello, I'm having a bit of trouble resizing/reshaping an array of strings. here's what I'm trying to do: myString = ['hi','my','name','is','Jeff'] reshape(myString, (2,2)) What I get from this is something like: [['h','i'], ['m','y']] What I want is: [['hi','my'], ['name','is']] How might this work best? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050606/bce5e53c/attachment.html From ajikoe at gmail.com Mon Jun 6 17:57:53 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 6 Jun 2005 17:57:53 +0200 Subject: [Tutor] resizing an array of strings? In-Reply-To: <20050606141455.99538.qmail@web30505.mail.mud.yahoo.com> References: <20050606141455.99538.qmail@web30505.mail.mud.yahoo.com> Message-ID: Try this code: def myfuncSplit(row,col,myList): RBig = [] cou=-1 for i in range(row): RSmall= [] for j in range(col): cou+=1 RSmall.append(myList[cou]) RBig.append(RSmall[:]) return RBig if __name__== '__main__': myString = ['hi','my','name','is','Jeff'] result = myfuncSplit(2,2,myString) print result On 6/6/05, Jeff Peery wrote: > Hello, I'm having a bit of trouble resizing/reshaping an array of strings. > here's what I'm trying to do: > > myString = ['hi','my','name','is','Jeff'] > reshape(myString, (2,2)) > > What I get from this is something like: > > [['h','i'], > ['m','y']] > > What I want is: > [['hi','my'], > ['name','is']] > > How might this work best? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Mon Jun 6 18:02:33 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 6 Jun 2005 17:02:33 +0100 Subject: [Tutor] How to open a telnet session and have the python programwrite to it. References: <476826C3AD01EC46B351C35C183E532501AEF837@ma-india09.asia.manh.com> Message-ID: <025601c56ab1$299c9350$26ba8651@xp> > I am attempting a python program that will open a telnet session and > input the username/password, cd to a certain directory and leave the session > there. I have attempted different combinations of the os.popen etc but as > soon as the telnet window is opened the program cannot be coaxed to write to > the telnet session (window). I have attempted the telnetlib, but the > problem is that the telnet window does not show up. Try pyexpect.... I think you have to download it though. Alan G. From sigurd at 12move.de Mon Jun 6 18:03:39 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Mon, 06 Jun 2005 18:03:39 +0200 Subject: [Tutor] resizing an array of strings? In-Reply-To: <20050606141455.99538.qmail@web30505.mail.mud.yahoo.com> (Jeff Peery's message of "Mon, 6 Jun 2005 07:14:55 -0700 (PDT)") References: <20050606141455.99538.qmail@web30505.mail.mud.yahoo.com> Message-ID: On 6 Jun 2005, jeffpeery at yahoo.com wrote: > > Hello, I'm having a bit of trouble resizing/reshaping an array of strings. > here's what I'm trying to do: > > myString = ['hi','my','name','is','Jeff'] > reshape(myString, (2,2)) > > What I get from this is something like: > > [['h','i'], > ['m','y']] > > What I want is: > [['hi','my'], > ['name','is']] If you explained exactly what you want (and showed what you tried to do) it would be easier to help. What does e.g. the tuple `(2,2)' mean? Here's is an example which should give you an idea how to solve the problem: . >>> s = ['hi','my','name','is','Jeff'] . >>> s[0:2] . ['hi', 'my'] . >>> s[2:4] . ['name', 'is'] Your reshape function just has to create the list slices. Karl -- Please do *not* send copies of replies to me. I read the list From nixonron at yahoo.com Mon Jun 6 20:40:54 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon, 6 Jun 2005 11:40:54 -0700 (PDT) Subject: [Tutor] CPAN for python Message-ID: <20050606184054.77139.qmail@web20328.mail.yahoo.com> Is there a site like Perl's CPAN for Python? I've seen the stuff at ActiveState. Anything else? Ron Nixon __________________________________ Discover Yahoo! Have fun online with music videos, cool games, IM and more. Check it out! http://discover.yahoo.com/online.html From dyoo at hkn.eecs.berkeley.edu Mon Jun 6 20:54:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Jun 2005 11:54:01 -0700 (PDT) Subject: [Tutor] CPAN for python In-Reply-To: <20050606184054.77139.qmail@web20328.mail.yahoo.com> Message-ID: On Mon, 6 Jun 2005, Ron Nixon wrote: > Is there a site like Perl's CPAN for Python? I've seen the stuff at > ActiveState. Anything else? Hi Ron, Yes, there is a system called 'PyPI': http://www.python.org/pypi I hope this helps! From bill at celestial.net Mon Jun 6 21:11:39 2005 From: bill at celestial.net (Bill Campbell) Date: Mon, 6 Jun 2005 12:11:39 -0700 Subject: [Tutor] CPAN for python In-Reply-To: References: <20050606184054.77139.qmail@web20328.mail.yahoo.com> Message-ID: <20050606191139.GA89035@alexis.mi.celestial.com> On Mon, Jun 06, 2005, Danny Yoo wrote: > > >On Mon, 6 Jun 2005, Ron Nixon wrote: > >> Is there a site like Perl's CPAN for Python? I've seen the stuff at >> ActiveState. Anything else? > >Hi Ron, > >Yes, there is a system called 'PyPI': > > http://www.python.org/pypi There's also the vaults of parnassus http://www.vex.net/parnassus/ Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ There are three kinds of men. The ones that learn by reading. The few who learn by observation. The rest of them have to pee on the electric fence for themselves. -- Will Rogers From Christian.Wyglendowski at greenville.edu Mon Jun 6 22:57:44 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Mon, 6 Jun 2005 15:57:44 -0500 Subject: [Tutor] CPAN for python Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo > > > Yes, there is a system called 'PyPI': > > http://www.python.org/pypi > Also see EasyInstall (http://peak.telecommunity.com/DevCenter/EasyInstall). Installs packages from the command line by searching PyPI. It's pretty new from what I gather. Much more info at the above address. Christian http://www.dowski.com From joe at omc-international.com.au Tue Jun 7 02:51:28 2005 From: joe at omc-international.com.au (Joe Healy) Date: Tue, 07 Jun 2005 10:51:28 +1000 Subject: [Tutor] Database connections don't stay alive In-Reply-To: References: Message-ID: <42A4EF90.3060407@omc-international.com.au> Hi there, I have mainly used the psycopg module to connect. It seems to work quite well. quick example: import psycopg conn = psycopg.connect("dbname=mydatabase password=xxxx host=zzzz user=yyyy") cur = conn.cursor() cur.execute('select * from transit;') results = cur.fetchall() Hope this helps, Joe Olli Rajala wrote: >Well, I asked about tutorials, but maybe this was not so good day, >because it has been quite "silent". :) > >So, good tutorials are still welcome, though I know now how to connect >to the Postgresql database. I just have some problems, though. With >MySQL I can do like this: > >import MySQLdb >def connectDB(): > try: > db = MySQLdb.connect(host='localhost', user='user', >db='pictures', passwd='passwd') > cursor = db.cursor() > return cursor > except: > print 'Error' > >cursor = connectDB() >cursor.execute('SELECT * FROM categories') >print cursor.fetchall() > >And everything works as I thought. But with Postgre, it seems that the >connection don't stay alive. I mean, with the same kind of code: > >from pyPgSQL import PgSQL >def connectDB(): > try: > db = PgSQL.connect(host='localhost', database='pictures', >user='user', password='passwd') > return db.cursor() > except: > print "Error" > >cursor = connectDB() >cursor.execute("SELECT * FROM categories") >print cursor.fetchall() > >The result is: > >Traceback (most recent call last): > File "test.py", line 23, in ? > cursor.execute("SELECT * FROM categories") > File "/usr/lib/python2.4/site-packages/pyPgSQL/PgSQL.py", line 2992, >in execute > raise InterfaceError, "execute failed - the cursor is closed." >libpq.InterfaceError: execute failed - the cursor is closed. > >So, what's the solution for this? I saw somewhere some mentions about >'connection pooling', what's that and how I'm supposed to use that? > >It's quite hard to code when you don't have good manuals and have to >put together information from very different sources and try to make >it work... For example, this is from a manual I've used: > >2.1.3.1 PQconnectdb >Syntax: > c = PQconnectdb(conninfo) > Where conninfo is a string containing connection information. > >What the heck is 'conninfo', I mean, what's it's syntax? Yeah, I was >finally able to figure it out, but it took hours googling, trying and >stumbling. > >Okay, okay, back to business. Hope that someone will be able to help me. :) > >Yours sincerely, > > -- ________________________________________________________ Joe Healy | Engineer OMC-International | 6 Paterson St | Abbotsford, VIC 3067 Melbourne | Australia Phone +61 (3) 9412 6500 | Fax +61 (3) 9415 9105 www.omc-international.com.au Dedicated to safer and more efficient shipping. CONFIDENTIAL COMMUNICATIONS. The information contained in this e-mail is confidential and may be subject to legal professional privilege. It is intended solely for the addressee. If you received this correspondence by mistake, please promptly inform us by reply e-mail or by telephoning +61 3 9412 6500 and then delete the e-mail and destroy any printed copy. You must not disclose, copy or rely on any part of this correspondence if you are not the intended recipient. From carroll at tjc.com Tue Jun 7 03:20:08 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 6 Jun 2005 18:20:08 -0700 (PDT) Subject: [Tutor] Trying Ruby... Message-ID: This message is not as off-topic as it at first appears. I'm a user of Activestate's ActivePython under Windows/XP. I want to give Ruby a spin, just for the heck of it. I vaguely recall a post a few months ago, I don't know if it was in this forum, where someone had a problem in Python, and it turns out it was because a Ruby install messed with some setting, perhaps in the Windows registry. I can be more vague upon request. Anyway, I'd like to install Ruby, but want to make very sure I don't impair my Python environment. Is there anything anyone can point to to ensure this? Any suggestions on the safest Ruby to install would also be appreciated. From premshree.pillai at gmail.com Tue Jun 7 08:50:41 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 7 Jun 2005 12:20:41 +0530 Subject: [Tutor] CPAN for python In-Reply-To: <20050606191139.GA89035@alexis.mi.celestial.com> References: <20050606184054.77139.qmail@web20328.mail.yahoo.com> <20050606191139.GA89035@alexis.mi.celestial.com> Message-ID: On 6/7/05, Bill Campbell wrote: > There's also the vaults of parnassus > > http://www.vex.net/parnassus/ That's pretty much dead, isn't it? -- Premshree Pillai http://www.livejournal.com/users/premshree/ From premshree.pillai at gmail.com Tue Jun 7 08:52:51 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 7 Jun 2005 12:22:51 +0530 Subject: [Tutor] CPAN for python In-Reply-To: References: <20050606184054.77139.qmail@web20328.mail.yahoo.com> Message-ID: On 6/7/05, Danny Yoo wrote: > > > On Mon, 6 Jun 2005, Ron Nixon wrote: > > > Is there a site like Perl's CPAN for Python? I've seen the stuff at > > ActiveState. Anything else? > > Hi Ron, > > Yes, there is a system called 'PyPI': > > http://www.python.org/pypi PyPi is an index. There's effort going on to have a CPAN shell like thing for Python. One of them is Uraga: http://www.byteofpython.info/projects/uraga/uraga.html. -- Premshree Pillai http://www.livejournal.com/users/premshree/ From premshree.pillai at gmail.com Tue Jun 7 08:54:09 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 7 Jun 2005 12:24:09 +0530 Subject: [Tutor] Trying Ruby... In-Reply-To: References: Message-ID: I have Python and Ruby -- not ActiveState -- installed on an XP box. No issues. On 6/7/05, Terry Carroll wrote: > This message is not as off-topic as it at first appears. > > I'm a user of Activestate's ActivePython under Windows/XP. I want to give > Ruby a spin, just for the heck of it. I vaguely recall a post a few > months ago, I don't know if it was in this forum, where someone had a > problem in Python, and it turns out it was because a Ruby install messed > with some setting, perhaps in the Windows registry. > > I can be more vague upon request. > > Anyway, I'd like to install Ruby, but want to make very sure I don't > impair my Python environment. Is there anything anyone can point to to > ensure this? > > Any suggestions on the safest Ruby to install would also be appreciated. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Premshree Pillai http://www.livejournal.com/users/premshree/ From hugonz-lists at h-lab.net Tue Jun 7 09:52:18 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 07 Jun 2005 02:52:18 -0500 Subject: [Tutor] Not getting what execl() should be doing... Message-ID: <42A55232.6040006@h-lab.net> Hi all, I'm trying to call up flac's encoder from a Python program. I believe I should be doing it ok, but I get completely different results when doing it by hand and from the python script. Here's the command line: $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 --sample-rate=44100 --delete-input-file /var/data/myfile.raw This works fine when done by hand, and flac encodes the file. Inside the script, I do a fork() and then, on the child, I do: tw_comppath = "/usr/bin/flac" filepath = "/var/data/myfile.raw" os.execl(tw_comppath, "--endian=little", "--channels=2", "--sign=signed", "--bps=16", "--sample-rate=44100", "--delete-input-file", "%s"%filepath) In this case, the FLAC binary complains about not getting the proper options (endian, channels, etc), but it claims it is getting --delete-input-file. What am I doing wrong? I cannot seem to pass the parameters right using execl.... Thanks for your enlightening.... Hugo From hugonz-lists at h-lab.net Tue Jun 7 09:52:56 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 07 Jun 2005 02:52:56 -0500 Subject: [Tutor] Not getting what execl() should be doing... Message-ID: <42A55258.4060006@h-lab.net> Hi all, I'm trying to call up flac's encoder from a Python program. I believe I should be doing it ok, but I get completely different results when doing it by hand and from the python script. Here's the command line: $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 --sample-rate=44100 --delete-input-file /var/data/myfile.raw This works fine when done by hand, and flac encodes the file. Inside the script, I do a fork() and then, on the child, I do: tw_comppath = "/usr/bin/flac" filepath = "/var/data/myfile.raw" os.execl(tw_comppath, "--endian=little", "--channels=2", "--sign=signed", "--bps=16", "--sample-rate=44100", "--delete-input-file", "%s"%filepath) In this case, the FLAC binary complains about not getting the proper options (endian, channels, etc), but it claims it is getting --delete-input-file. What am I doing wrong? I cannot seem to pass the parameters right using execl.... Thanks for your enlightening.... Hugo From hugonz-lists at h-lab.net Tue Jun 7 09:53:32 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 07 Jun 2005 02:53:32 -0500 Subject: [Tutor] Not getting what execl() should be doing... Message-ID: <42A5527C.60800@h-lab.net> Hi all, I'm trying to call up flac's encoder from a Python program. I believe I should be doing it ok, but I get completely different results when doing it by hand and from the python script. Here's the command line: $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 --sample-rate=44100 --delete-input-file /var/data/myfile.raw This works fine when done by hand, and flac encodes the file. Inside the script, I do a fork() and then, on the child, I do: tw_comppath = "/usr/bin/flac" filepath = "/var/data/myfile.raw" os.execl(tw_comppath, "--endian=little", "--channels=2", "--sign=signed", "--bps=16", "--sample-rate=44100", "--delete-input-file", "%s"%filepath) In this case, the FLAC binary complains about not getting the proper options (endian, channels, etc), but it claims it is getting --delete-input-file. What am I doing wrong? I cannot seem to pass the parameters right using execl.... Thanks for your enlightening.... Hugo From hugonz-lists at h-lab.net Tue Jun 7 10:14:03 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 07 Jun 2005 03:14:03 -0500 Subject: [Tutor] Not getting what execl() should be doing... OK I GOT IT In-Reply-To: <42A55258.4060006@h-lab.net> References: <42A55258.4060006@h-lab.net> Message-ID: <42A5574B.3090507@h-lab.net> Just replying to myself because I am extremely dumb, so maybe it will help someone along the way if the same thing happens. I forgot to include argv[1], which is basically the same as the name of the file to be run. So: os.execl(tw_comppath, tw_comppath, "--endian=little", "--channels=2", "--sign=signed", "--bps=16", "--sample-rate=44100", "--delete-input-file", "%s"%filepath) does the trick. Thanks anyway tutors... Hugo Gonz?lez Monteverde wrote: > Hi all, > > I'm trying to call up flac's encoder from a Python program. I believe I > should be doing it ok, but I get completely different results when doing > it by hand and from the python script. Here's the command line: > > $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 > --sample-rate=44100 --delete-input-file /var/data/myfile.raw > > This works fine when done by hand, and flac encodes the file. > > Inside the script, I do a fork() and then, on the child, I do: > > > tw_comppath = "/usr/bin/flac" > filepath = "/var/data/myfile.raw" > > os.execl(tw_comppath, "--endian=little", "--channels=2", > "--sign=signed", "--bps=16", "--sample-rate=44100", > "--delete-input-file", "%s"%filepath) > > In this case, the FLAC binary complains about not getting the proper > options (endian, channels, etc), but it claims it is getting > --delete-input-file. > > What am I doing wrong? I cannot seem to pass the parameters right using > execl.... > > Thanks for your enlightening.... > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From work at infomaniak.ch Tue Jun 7 14:00:43 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Tue, 07 Jun 2005 14:00:43 +0200 Subject: [Tutor] interactif or not In-Reply-To: <7e5ba92205060410325590158c@mail.gmail.com> References: <20050603100120.GF3155@obs.unige.ch> <7e5ba92205060410325590158c@mail.gmail.com> Message-ID: <20050607120043.GA30376@obs.unige.ch> > If you want to know if your program has been launched from an interactive > terminal or from a system background process like cron or init, then you > look to see if stdin is a tty. Unix is usually very careful about who has a > "controlling tty" and who does not. In Python, file objects have an isatty() > method that will return True or False. > > import sys > isinteractive = sys.stdin.isatty() > if isinteractive: > ... > else: > ... > tested and it works ! Ced. -- Cedric BRINER From bkfignier at clsp.jhu.edu Tue Jun 7 15:18:38 2005 From: bkfignier at clsp.jhu.edu (Benjamin Klein-Fignier) Date: Tue, 7 Jun 2005 09:18:38 -0400 Subject: [Tutor] Double loop and performances Message-ID: <792F4763-70C0-4106-8E20-B9AD062B8206@clsp.jhu.edu> Hi, I am wondering if there is a way to efficiently run a double loop in Python. To be more precise, I would like to compute the sum of a function f(x,y) for every possible (x,y) pair. I have tried several alternatives so far: 1) the classic double loop: for x in X: for y in Y: sum += f(x,y) 2) using list comprehension: sum([f(x,y) for x in X for y in Y]) 3) I figured out that the loop was slow, so I used map() to generate a list of every combination and then map to compute the result. But it is not very memory efficient and still pretty slow. I know I might try to use SciPy & co to do it but I would prefer to be able to run my script on any default python installation. Any suggestion ? Regards, -- Ben From kent37 at tds.net Tue Jun 7 15:59:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 09:59:11 -0400 Subject: [Tutor] Double loop and performances In-Reply-To: <792F4763-70C0-4106-8E20-B9AD062B8206@clsp.jhu.edu> References: <792F4763-70C0-4106-8E20-B9AD062B8206@clsp.jhu.edu> Message-ID: <42A5A82F.90407@tds.net> Benjamin Klein-Fignier wrote: > Hi, > > I am wondering if there is a way to efficiently run a double loop in > Python. To be more precise, I would like to compute the sum of a > function f(x,y) for every possible (x,y) pair. How big are your lists (X and Y)? A few minor suggestions below. > I have tried several alternatives so far: > > 1) the classic double loop: > for x in X: > for y in Y: > sum += f(x,y) > > 2) using list comprehension: > sum([f(x,y) for x in X for y in Y]) In Python 2.4 you can write the above with a generator expression which may be faster and will certainly use less memory: sum(f(x,y) for x in X for y in Y) > 3) I figured out that the loop was slow, so I used map() to generate > a list of every combination and then map to compute the result. But > it is not very memory efficient and still pretty slow. Try using itertools.imap() instead of map(), it will cut down the memory use (though the result is not the same as map() if the lists passed to it are different lengths). If this is done inside a function, bind f to a local variable, that speeds lookup. This thread in comp.lang.python is interesting though it solves a more general problem and it is old so its results may no longer be valid: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/de552741a17378bc/bb02de365f85e916?q=p13x25&rnum=1&hl=en#bb02de365f85e916 Here is one solution from that thread modified to work with just two lists: def permute(X, Y): import operator result = map(lambda I: (I,), X) curr = [] for item in Y: new = map(operator.add, result, [(item,)]*len(result)) curr[len(curr):] = new result = curr return result though it's hard to believe that will be faster than just ((x,y) for x in X for y in Y) Leaving the actual testing to you, Kent From flaming_hamster at hotmail.com Tue Jun 7 19:32:57 2005 From: flaming_hamster at hotmail.com (Vladimir Rasputin) Date: Tue, 07 Jun 2005 17:32:57 +0000 Subject: [Tutor] keylogger Message-ID: Can i make a keylogger using python? has anyone ever made one/tryed to make one? does any one know how to make one? _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From alan.gauld at freenet.co.uk Tue Jun 7 19:35:12 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 7 Jun 2005 18:35:12 +0100 Subject: [Tutor] Not getting what execl() should be doing... References: <42A55232.6040006@h-lab.net> Message-ID: <029f01c56b87$42813c50$26ba8651@xp> > I'm trying to call up flac's encoder from a Python program. I believe I > should be doing it ok, but I get completely different results when doing > it by hand and from the python script. Here's the command line: > > $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 > --sample-rate=44100 --delete-input-file /var/data/myfile.raw > > This works fine when done by hand, and flac encodes the file. > > Inside the script, I do a fork() and then, on the child, I do: You should probably try using the popen() family of functions instead, or if on Python 2.4 the new commands(?) module. While your approach can be made to work it needs a fair amount of tweaking of environments and the like. popen otr commands should simplify life significantly. Alan G. From denise.hartley at gmail.com Tue Jun 7 21:05:47 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 7 Jun 2005 12:05:47 -0700 Subject: [Tutor] More image manipulation Message-ID: <8daabe56050607120517bbab86@mail.gmail.com> Hello, everyone! If someone has a few seconds, I am getting some weird errors and Python won't tell me why. What I am trying to do is take a middle chunk out of a line of an image, place that at the beginning of the line, and slide the rest over to the end, like so: aaaaaaaa111bbbbbb to: 111aaaaaaabbbbbb etc. I'm doing this for each horizontal line in a 640x480 picture, and then I want to take all those newlines and make a new image. So I made a list of all the pixel values (this is the one whose mode is "P," that strange thing I emailed about before, so instead of a tuple of RGB values, it just gives me one number for each pixel). To create this list, I did: This is what I did: def findlist(): newlist = [] for i in range(480): line = fromlist[:640] del fromlist[:640] x = line.index(195) y = x + 5 z = line[x:y] del line[x:y] for i in z: newlist.append(i) for i in line: newlist.append(i) return newlist So this worked exactly as I figured it would. It returned me a list, len 307200 (hooray!), and I looked at the first handful of 640-long chunks and indeed, each now starts with five 195's (the middle chunk I am removing from each line and re-placing at the beginning of each new line). So now I have a list 307200 pixels long of pixel values, and I want to put it into a new image. I then did the following: def makenewpic(): newim = Image.new("P",(640,480)) a = findlist() result = newim.putdata(a) return result Now two weird things happen. A). If I try to run b = makenewpic() (so that i'd have a b i could do b.show() on), I get this error: Traceback (most recent call last): File "", line 1, in ? b = makenewpic() File "Z:\misc\16.py", line 50, in makenewpic a = findlist() File "Z:\misc\16.py", line 37, in findlist x = line.index(195) ValueError: list.index(x): x not in list This is annoying enough in and of itself, besides, I am about 99% sure that there IS a set of five 195's on every single line, and the error does not seem to be valid *because*: B). If I run the steps in makenewpic one by one in the interpreter, it doesnt give me any "x not in list" error, it lets me do the result = newim.putdata(a) just fine. But then when I type result.show() it tells me 'NoneType' object has no attribute 'show'. At first I thought it was because when I was creating the blank newim, I was using mode "RGB" and adding a list of "P" pixel values to it. But I fixed it so that my newim is also mode "P" and it still tells me that type(result) = None. Again, this is probably some little typo or dumb newbie error that I'm missing because of looking at this thing four million times and getting frustrated. I'm hoping a fresh set of eyes will help? Thank you guys for your patience! ~Denise From erastley at charter.net Tue Jun 7 21:22:51 2005 From: erastley at charter.net (EUGENE ASTLEY) Date: Tue, 7 Jun 2005 12:22:51 -0700 Subject: [Tutor] Text problem Message-ID: <000001c56b96$51a37360$6501a8c0@D3K8PT61> Python, pygames problem. At the end of my game, I go back to the desk top after displaying the score of the player, as follows: Def game_over(self) Games.Message(screen = self.screen, X = 400, y = 400 Text + "Your Score is " + str(Game.score_value), Size = 60, color = color.green, Lifetime = 1000, after_death = self.screen.quit() This works well but I would like to have several lines of text. The triple quote method does not work. How can I get several lines of text into the message? I can't find the syntax that is legal for the games.message command. Gene -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050607/422fd7b6/attachment.html From tsr9988 at yahoo.com Tue Jun 7 21:38:47 2005 From: tsr9988 at yahoo.com (t sr) Date: Tue, 7 Jun 2005 12:38:47 -0700 (PDT) Subject: [Tutor] http connection, windows xp Message-ID: <20050607193847.11760.qmail@web51501.mail.yahoo.com> I'm having trouble getting a script to make an internet connection with my windows xp laptop with a wireless connection. It works fine on my desktop with a dial-up connection; page = urllib.urlopen(my_URL).read() gives the message; Traceback (most recent call last): File "C:/Python24/test.py", line 475, in -toplevel- main() File "C:/Python24/test.py", line 393, in main entries = parse_category(cat) File "C:/Python24/test.py", line 366, in parse_category page = urllib.urlopen(URL_CAT % cat).read() File "C:\Python24\lib\urllib.py", line 77, in urlopen return opener.open(url) File "C:\Python24\lib\urllib.py", line 180, in open return getattr(self, name)(url) File "C:\Python24\lib\urllib.py", line 296, in open_http h.endheaders() File "C:\Python24\lib\httplib.py", line 794, in endheaders self._send_output() File "C:\Python24\lib\httplib.py", line 675, in _send_output self.send(msg) File "C:\Python24\lib\httplib.py", line 642, in send self.connect() File "C:\Python24\lib\httplib.py", line 626, in connect raise socket.error, msg IOError: [Errno socket error] (10060, 'Operation timed out') I've tried turning off the firewall and tinkering with windows networking properties to no avail. I'm new to python, can someone please help me get a clue :) T sR __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From 3dbernard at gmail.com Tue Jun 7 21:42:39 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 7 Jun 2005 15:42:39 -0400 Subject: [Tutor] repr() Message-ID: <61d0e2b405060712426fec5107@mail.gmail.com> Hello, Possibly I am missing something, but how do you use the repr() function? I type this ultra-simple function: def myFunc(): print 'hello' Then run repr( myFunc ) Wich returns '' Okay then I run s = repr( myFunc() ) print s Wich returns 'None' Thanks Bernard From maxnoel_fr at yahoo.fr Tue Jun 7 21:50:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 7 Jun 2005 20:50:51 +0100 Subject: [Tutor] repr() In-Reply-To: <61d0e2b405060712426fec5107@mail.gmail.com> References: <61d0e2b405060712426fec5107@mail.gmail.com> Message-ID: <36EFC744-7AE8-49F8-B793-85EF054BA0C4@yahoo.fr> On Jun 7, 2005, at 20:42, Bernard Lebel wrote: > repr( myFunc ) > > Wich returns > > '' > > > Okay then I run > > s = repr( myFunc() ) > print s > > Wich returns > > 'None' That's perfectly normal. Your last assignment calls the function, then assigns to s the representation of the function's return value. A function that doesn't have a return statement returns None, and repr(None) == 'None'. Which is what you get. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Tue Jun 7 21:51:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 15:51:28 -0400 Subject: [Tutor] Text problem In-Reply-To: <000001c56b96$51a37360$6501a8c0@D3K8PT61> References: <000001c56b96$51a37360$6501a8c0@D3K8PT61> Message-ID: <42A5FAC0.4050005@tds.net> EUGENE ASTLEY wrote: > Python, pygames problem. > > At the end of my game, I go back to the desk top after displaying the > score of the player, as follows: > > Def game_over(self) > > Games.Message(screen = self.screen, > > X = 400, y = 400 > > Text + ?Your Score is ? + str(Game.score_value), > > Size = 60, color = color.green, > > Lifetime = 1000, after_death = self.screen.quit() > > > > This works well but I would like to have several lines of text. The > triple quote method does not work. How can I get several lines of text > into the message? It looks like you are using livewires and you have paraphrased your code. It's helpful if you copy and paste the exact code you have tried and any error message you get. Looking at livewires.games.py I see class Message(Text): def __init__ (self, screen, x, y, text, size, color, a=0, dx=0, dy=0, da=0, lifetime=0, after_death=None): so I would try something like this: def gameOver(self): text = ?""Your Score is %s Thank you for playing Please come again""? % Game.score_value games.Message(x = 400, y = 400, text = text, size = 60, color = color.green, lifetime = 1000, after_death = self.screen.quit()) Kent From dyoo at hkn.eecs.berkeley.edu Tue Jun 7 22:25:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Jun 2005 13:25:15 -0700 (PDT) Subject: [Tutor] repr() In-Reply-To: <61d0e2b405060712426fec5107@mail.gmail.com> Message-ID: > Okay then I run > > s = repr( myFunc() ) > print s > > Wich returns > > 'None' Hi Bernard, Ok, what do you expect to see instead of 'None'? I ask this to make sure I understand the situation better. Best of wishes? From carroll at tjc.com Tue Jun 7 22:26:16 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 7 Jun 2005 13:26:16 -0700 (PDT) Subject: [Tutor] More image manipulation In-Reply-To: <8daabe56050607120517bbab86@mail.gmail.com> Message-ID: On Tue, 7 Jun 2005, D. Hartley wrote: > def findlist(): > newlist = [] > for i in range(480): > line = fromlist[:640] > del fromlist[:640] > x = line.index(195) > y = x + 5 > z = line[x:y] > del line[x:y] > for i in z: > newlist.append(i) > for i in line: > newlist.append(i) > return newlist where does the variable named "fromlist" come from? It's not passed into the method as a parameter. > B). If I run the steps in makenewpic one by one in the interpreter, it > doesnt give me any "x not in list" error, it lets me do the result = > newim.putdata(a) just fine. But then when I type result.show() it > tells me 'NoneType' object has no attribute 'show'. At first I > thought it was because when I was creating the blank newim, I was > using mode "RGB" and adding a list of "P" pixel values to it. But I > fixed it so that my newim is also mode "P" and it still tells me that > type(result) = None. You have: > result = newim.putdata(a) > return result >From the PIL docs, putdata does not appear to return an image. The docs for putdata say: putdata im.putdata(data) im.putdata(data, scale, offset) Usually, when a PIL method returns an image, the docs say "=> image" after the method signature. My guess is that putdata returns None, which would be consistent with the error message "'NoneType' object has no attribute 'show'." You'll probably want: newim.putdata(a) return newim Instead. From carroll at tjc.com Tue Jun 7 22:29:31 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 7 Jun 2005 13:29:31 -0700 (PDT) Subject: [Tutor] repr() In-Reply-To: <61d0e2b405060712426fec5107@mail.gmail.com> Message-ID: On Tue, 7 Jun 2005, Bernard Lebel wrote: > repr( myFunc ) > '' > > > > s = repr( myFunc() ) > print s > > 'None' In the first example, your repr invocation is: repr(myFunc) i.e., you're asking for the repr of the function myFunc. In the second example, your repr invocation is: repr(myFunc()) i.e., you're calling the function myFunc and asking for the repr of the *result* From 3dbernard at gmail.com Tue Jun 7 22:42:05 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 7 Jun 2005 16:42:05 -0400 Subject: [Tutor] repr() In-Reply-To: <36EFC744-7AE8-49F8-B793-85EF054BA0C4@yahoo.fr> References: <61d0e2b405060712426fec5107@mail.gmail.com> <36EFC744-7AE8-49F8-B793-85EF054BA0C4@yahoo.fr> Message-ID: <61d0e2b405060713421e92172d@mail.gmail.com> Ok thanks a lot. The real question is, then, is there a way I can print the code of a function as a string? Something like.... 'def myFunction: print "hello"' Thanks Bernard On 6/7/05, Max Noel wrote: > > On Jun 7, 2005, at 20:42, Bernard Lebel wrote: > > > repr( myFunc ) > > > > Wich returns > > > > '' > > > > > > Okay then I run > > > > s = repr( myFunc() ) > > print s > > > > Wich returns > > > > 'None' > > That's perfectly normal. Your last assignment calls the > function, then assigns to s the representation of the function's > return value. A function that doesn't have a return statement returns > None, and repr(None) == 'None'. Which is what you get. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From Christian.Wyglendowski at greenville.edu Tue Jun 7 22:50:38 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue, 7 Jun 2005 15:50:38 -0500 Subject: [Tutor] Trying Ruby... Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Terry Carroll > Sent: Monday, June 06, 2005 8:20 PM > To: tutor at python.org > Subject: [Tutor] Trying Ruby... > > This message is not as off-topic as it at first appears. > > I'm a user of Activestate's ActivePython under Windows/XP. I > want to give > Ruby a spin, just for the heck of it. I vaguely recall a post a few > months ago, I don't know if it was in this forum, where someone had a > problem in Python, and it turns out it was because a Ruby > install messed > with some setting, perhaps in the Windows registry. Terry, If I remember correctly, it had to do with Tk getting messed up. But that's all I recall :-) Christian http://www.dowski.com From carroll at tjc.com Tue Jun 7 22:52:08 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 7 Jun 2005 13:52:08 -0700 (PDT) Subject: [Tutor] More image manipulation In-Reply-To: Message-ID: On Tue, 7 Jun 2005, Terry Carroll wrote: > On Tue, 7 Jun 2005, D. Hartley wrote: > > > def findlist(): > > newlist = [] > > for i in range(480): > > line = fromlist[:640] > > del fromlist[:640] > > x = line.index(195) > > y = x + 5 > > z = line[x:y] > > del line[x:y] > > for i in z: > > newlist.append(i) > > for i in line: > > newlist.append(i) > > return newlist > > where does the variable named "fromlist" come from? It's not passed into > the method as a parameter. I'm thinking more and more that this is the issue. Take a look at this, and see if it gives you the flavor. Only the third approach actually gives you what (I think) you want, rather than reusing the same list over and over. def testit1(): print fromlist1[0] del fromlist1[0] return fromlist1 = ['a', 'b', 'c', 'd'] print "testit1: Denise problem" testit1() testit1() testit1() def testit2(flist): print flist[0] del flist[0] return fromlist2 = ['a', 'b', 'c', 'd'] print "testit2: Python Gotcha #6" # http://www.ferg.org/projects/python_gotchas.html testit2(fromlist2) testit2(fromlist2) testit2(fromlist2) def testit3(flist): mylist = flist[:] # copy the list rather than mutating it for next time print mylist[0] del mylist[0] return fromlist3 = ['a', 'b', 'c', 'd'] print "testit3: the right way" testit3(fromlist3) testit3(fromlist3) testit3(fromlist3) From dyoo at hkn.eecs.berkeley.edu Tue Jun 7 23:04:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Jun 2005 14:04:08 -0700 (PDT) Subject: [Tutor] repr() In-Reply-To: <61d0e2b405060713421e92172d@mail.gmail.com> Message-ID: On Tue, 7 Jun 2005, Bernard Lebel wrote: > The real question is, then, is there a way I can print the code of a > function as a string? Something like.... > > 'def myFunction: print "hello"' Hi Bernard, Ah, ok. You can use 'inspect': http://www.python.org/doc/lib/inspect-source.html For example: ###### >>> import heapq >>> import inspect >>> print inspect.getsource(heapq.heappop) def heappop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0) else: returnitem = lastelt return returnitem ###### It doesn't always work: it'll work only if the function is a pure-Python function that's defined in a file that Python can find, since functions themselves don't carry their own textual representation around. Functions do contain the file name as well as their corresponding line numbers: ###### >>> heapq.__file__ '/usr/lib/python2.3/heapq.pyc' >>> heapq.heappop.func_code.co_firstlineno 136 ###### which is sorta how inspect.getsource() works. Best of wishes! From alan.gauld at freenet.co.uk Tue Jun 7 23:15:57 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 7 Jun 2005 22:15:57 +0100 Subject: [Tutor] interactif or not References: <20050603100120.GF3155@obs.unige.ch><7e5ba92205060410325590158c@mail.gmail.com> <20050607120043.GA30376@obs.unige.ch> Message-ID: <02c401c56ba6$1941c110$26ba8651@xp> > > look to see if stdin is a tty. Unix is usually very careful about who has a > > "controlling tty" and who does not. In Python, file objects have an isatty() > > method that will return True or False. > > > > import sys > > isinteractive = sys.stdin.isatty() > > if isinteractive: > > ... > > else: > > ... > > > > tested and it works ! Aha! I knew about tty on Unix so I looked in the os module for it, I never thought of it being a file method.... Alan G. From denise.hartley at gmail.com Tue Jun 7 23:57:33 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 7 Jun 2005 14:57:33 -0700 Subject: [Tutor] Fwd: More image manipulation In-Reply-To: <8daabe5605060714499328204@mail.gmail.com> References: <8daabe5605060714499328204@mail.gmail.com> Message-ID: <8daabe5605060714577da931f9@mail.gmail.com> Sorry, Terry, forgot to reply to the whole list. Here it is: ---------- Forwarded message ---------- From: D. Hartley Date: Jun 7, 2005 2:49 PM Subject: Re: [Tutor] More image manipulation To: Terry Carroll Terry, OK. I tried them out and I do see the diffence. (btw, testit1 gave me the following error: Traceback (most recent call last): File "", line 1, in ? testit1() File "", line 3, in testit1 del fromlist[0] IndexError: list assignment index out of range ... was that something you intended? that didnt happen with my original problem). Anyway I def notice the diff between 2 and 3, but see here's the thing: I think I *do* want it like #2, becaues I want it to keep returning the same list (i.e., move on and use line 2 (b), and then line 3 (c), and so on), rather than keep iterating over the same first line (a) over and over again. I want to take the first line in the picture, rearrange the pixels, and pop that line into the new list that I can then (eventually) create a new image from. I *thought* my list was populated (it's 307200 pixels long, after all), but it wont work when i try to putdata it onto a new blank image. > > where does the variable named "fromlist" come from? It's not passed into > > the method as a parameter. No, I had it defined right before the function. it pulls it in just fine. And like I said, the function returns me with a list of 307200 values - which makes me think that it "got" all 307200 of the original pixels, and performed the function correctly on each line. However, when I did the following: def test(): y = findlist() for i in range(480): piece = y[:640] del y[:640] print "Line",i," - ",y[:5] to look at the beginning five pixels of each of the new lines, for line 479 (the last i), it gave me []. This doesnt make sense! Hope I didnt miss something from your explanation...? ~Denise From alan.gauld at freenet.co.uk Wed Jun 8 00:29:36 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 7 Jun 2005 23:29:36 +0100 Subject: [Tutor] repr() References: <61d0e2b405060712426fec5107@mail.gmail.com> Message-ID: <02fb01c56bb0$62ce71c0$26ba8651@xp> > Possibly I am missing something, but how do you use the repr() function? THere are several ways of using repr, the most common is at the >>> prompt. >>> x = 5 >>> x 5 >>> when I typed x at the >>> prompt Python called repr(x) to display the result. This can be slightly different to using print which calls str() instead of repr(). Thats why: >>> s = 'hello' >>> s 'hello' >>> print s hello >>> produce different results. The other waybthat you can use repr() is by using the backtick notation >>> print `s` 'hello' >>> Note that the quote signs are back, indicating that repr() has been used. > def myFunc(): print 'hello' > > Then run > > repr( myFunc ) > >Which returns > > '' Just as you would see if you had done: >>> def myfunc(): print 'hello' >>> myfunc '' >>> > s = repr( myFunc() ) > print s Which assigns NOne to s and then prints the repr() of None > 'None' As it should. What did you think it should do? Alan G. From alan.gauld at freenet.co.uk Wed Jun 8 00:31:46 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 7 Jun 2005 23:31:46 +0100 Subject: [Tutor] repr() References: <61d0e2b405060712426fec5107@mail.gmail.com><36EFC744-7AE8-49F8-B793-85EF054BA0C4@yahoo.fr> <61d0e2b405060713421e92172d@mail.gmail.com> Message-ID: <030201c56bb0$b096dbe0$26ba8651@xp> > The real question is, then, is there a way I can print the code of a > function as a string? Something like.... > > 'def myFunction: print "hello"' There is a module for doing black magic like that. I think it may be the one with the disassembler in it? Curious as to why you would ever want to though? It may be there's another solution to whatever the problem is. Alan G. From carroll at tjc.com Wed Jun 8 00:45:54 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 7 Jun 2005 15:45:54 -0700 (PDT) Subject: [Tutor] More image manipulation (fwd) Message-ID: On Tue, 7 Jun 2005, D. Hartley wrote: > OK. I tried them out and I do see the diffence. (btw, testit1 gave me > the following error: > > Traceback (most recent call last): > File "", line 1, in ? > testit1() > File "", line 3, in testit1 > del fromlist[0] > IndexError: list assignment index out of range > > ... was that something you intended? that didnt happen with my > original problem). Interesting; I get this: testit1: Denise problem a b c testit2: Python Gotcha #6 a b c testit3: the right way a a a > Anyway I def notice the diff between 2 and 3, but see here's the thing: > > I think I *do* want it like #2, becaues I want it to keep returning > the same list (i.e., move on and use line 2 (b), and then line 3 (c), > and so on), rather than keep iterating over the same first line (a) > over and over again. Okay, gotcha. Here's my take on this sort of thing: I like to look at a method as a black box, defined by the method signature and its call. My basic rule is that I don't every like a method to alter any data except what it passes back. So... My approach, which I think is a little more clean and isolatable, is to pass anything that the function needs to operate in as a parameter; then, if I want to alter that list, I create a new copy and pass that back. I have a deep distrust of globals. So instead of this: def snip_first: delete alist[0] # find alist via scoping rules return and calling it like this: alist = ['a', 'b', 'c'] snip_first() I'd prefer to set it up like thi: def snip_first(input_list): output_list = alist[:] delete output_list[0] return output_list alist = ['a', 'b', 'c'] alist=snip_first(alist) (Both of these are untested, I'm just winging it here.) > I want to take the first line in the picture, > rearrange the pixels, and pop that line into the new list that I can > then (eventually) create a new image from. I *thought* my list was > populated (it's 307200 pixels long, after all), but it wont work when > i try to putdata it onto a new blank image. I don't know about you, but if it were me, without that encapsulation, I'd have a tough time figuring out what's getting modified when. > > > where does the variable named "fromlist" come from? It's not passed into > > > the method as a parameter. > > No, I had it defined right before the function. it pulls it in just > fine. Yes, but global scoping often messes me up, so I always use a local scope. If it's not parameter-passed into or created in a method, I don't use it in the method. From jfouhy at paradise.net.nz Wed Jun 8 01:03:53 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 08 Jun 2005 11:03:53 +1200 (NZST) Subject: [Tutor] repr() In-Reply-To: <02fb01c56bb0$62ce71c0$26ba8651@xp> References: <61d0e2b405060712426fec5107@mail.gmail.com> <02fb01c56bb0$62ce71c0$26ba8651@xp> Message-ID: <1118185433.42a627d95bb33@www.paradise.net.nz> Quoting Alan G : > The other waybthat you can use repr() is by using the backtick > notation > > >>> print `s` > 'hello' > >>> It's worth noting that backticks are going out of fashion --- I think they are queued for deletion in Py3000. Better to get in the habit of just calling repr() directly. -- John. From 3dbernard at gmail.com Wed Jun 8 01:36:52 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 07 Jun 2005 19:36:52 -0400 Subject: [Tutor] repr() In-Reply-To: <030201c56bb0$b096dbe0$26ba8651@xp> References: <61d0e2b405060712426fec5107@mail.gmail.com> <36EFC744-7AE8-49F8-B793-85EF054BA0C4@yahoo.fr> <61d0e2b405060713421e92172d@mail.gmail.com> <030201c56bb0$b096dbe0$26ba8651@xp> Message-ID: <42A62F94.4090308@gmail.com> Well, to make a long story short, this is because I use Python through another software, Softimage|XSI, and by design a string is required to pass logic to on-the-fly GUIs. Since XSI implements 3 other languages (ActivePerl, VBScript and JScript), I suppose this was designed that way with JScript's .toString() in mind. The SDK documentation does indeed show only a JScript example. Bernard Alan G wrote >Curious as to why you would ever want to though? > > > From raywood1 at entouch.net Wed Jun 8 01:54:04 2005 From: raywood1 at entouch.net (The Johnsons) Date: Tue, 7 Jun 2005 18:54:04 -0500 Subject: [Tutor] remove from python Message-ID: <000c01c56bbc$2f7a3910$0302a8c0@your46e94owx6a> how can i get my email address removed, I'm receiving way too many emails raywood1 at entouch.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050607/e780bc45/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Jun 8 02:57:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Jun 2005 17:57:45 -0700 (PDT) Subject: [Tutor] remove from python In-Reply-To: <000c01c56bbc$2f7a3910$0302a8c0@your46e94owx6a> Message-ID: On Tue, 7 Jun 2005, The Johnsons wrote: > how can i get my email address removed, I'm receiving way too many > emails Hi Raywood1, You have a few options. You may want to see if just turning the Tutor mailing list setting to "Digest Mode" might help. You can do this through: http://mail.python.org/mailman/options/tutor?email=raywood1 at entouch.net Digest mode will bundle up messages from Tutor so that you don't get so deluged. If you want to unsubscribe, there should be instructions on how to do so from that page too. Finally, if you have more questions on administrative stuff, or if you run into difficulty while unsubscribing, then send an email to tutor-owner at python.org, and the administrators will help you get off the list. From leec03273 at mac.com Wed Jun 8 05:34:21 2005 From: leec03273 at mac.com (Lee Cullens) Date: Tue, 7 Jun 2005 23:34:21 -0400 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique) Message-ID: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> In my original post I noted my recent exposure to Python and put up a little utility to my iDisk asking for a Pythonese/Efficiency/ Generalese critique. Javier, Kent and Liam were gracious enough to offer comments, which were greatly appreciated. To follow through with the learning exercise, I incorporated their comments (at least the ones there were no conflicting opinions on :~) and put up the new version as: http://homepage.mac.com/lee_cullens/DirTreeToCSV.zip I was thinking of extending the learning exercise by re-factoring it as an OO approach, since it would contain a minimum altered method. Being new to OOP also though, I'm confusing myself with how that would be best accomplished. My thinking is that class/subclass method instances would replace the recursive functions approach, but have as yet not formed the coding in my mind. I've read a lot on OOP, but seem to have a problem with the practical use of such in this utility. I'm undoubtedly creating a mountain of an ant hill in my mind, so any thoughts would be appreciated. Thanks, Lee C From javier at ruere.com.ar Wed Jun 8 07:10:21 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Wed, 08 Jun 2005 02:10:21 -0300 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique) In-Reply-To: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> Message-ID: Lee Cullens wrote: > I was thinking of extending the learning exercise by re-factoring it > as an OO approach, since it would contain a minimum altered method. > Being new to OOP also though, I'm confusing myself with how that > would be best accomplished. My thinking is that class/subclass > method instances would replace the recursive functions approach, but > have as yet not formed the coding in my mind. I can't imagine this either and, though I'm no OO guru, have never considered that that an inheritance relationship could replace a recursive function call. > I've read a lot on OOP, but seem to have a problem with the practical > use of such in this utility. I'm undoubtedly creating a mountain of > an ant hill in my mind, so any thoughts would be appreciated. I don't see any benefit from using OO in this case. Module level functions (like you have now) are ideal in this case IMHO. Maybe in a situation where you can benefit from OO it would be crearer how to use it. Having state is usually a good sign. Working with several "things" which have a behaviour would be another. Just for fun lets do it anyway. :) Directories and files could be considered things, files could tell if they are files, links or whatever and directories could tell which subdirectories and files they have. Also this objects could render themselfs to a proper string representation we can directly output as a row. So, in pseudocode, this would be something like: class File: """File(name:str, parent:Dir) parent: The directory which contains this File. name: The name of this File. """ def __init__(self, name, parent): self._parent = parent self._name = name assert exists(join(repr(parent), name)) def isLink(self): return islink(self.path) [Rest of the is* functions.] def __str__(self): return [...] class Dir: """Dir(name:str, [parent:Dir]) parent: The directory which contains this File. If omited, an absolute path is assumed. name: The name of this File. """ def __init__(self, name, parent=None) self._parent = parent self._name = name assert isdir(join(repr(parent), name)) def getDirs(self): return [...] def getFiles(self): return [...] Now, both classes could inherit from a FSElement (or something) but I see no benefit in doing that. The output functionality could also be in a different class: class CSVOutput: def __init__(self, filename): [validate for overwritting] self._out = file(filename, 'w') def process(self, root): for file in root.getFiles(): self._out.write(str(file)) for dir in root.getDirs(): self.process(dir) And the main: CVSOuput(argv[2]).process(Dir(mkAbsolutePath(argv[1]))) I'm very sleepy so this could all just be gibberish but I hope it will help you get the idea. Ideally, functions should be very small, a couple of lines, and object should be reusable. So moving the rendering to CVSOutput would be better. :) Javier From leec03273 at mac.com Wed Jun 8 07:33:08 2005 From: leec03273 at mac.com (Lee Cullens) Date: Wed, 8 Jun 2005 01:33:08 -0400 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique) In-Reply-To: References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> Message-ID: <5D756447-82AA-4BEB-8A3E-3898572BA52C@mac.com> Thanks again for your thoughts Javier. You've certainly given me a mouthful to chew on :~) I was thinking more in terms of "OOP is about code reuse" and trying to equate the function approach to such with the class methods approach in a similar way. Obviously I have got my mind wrapped around the wrong tree. I'm not actually looking for the best approach here - rather just trying to map a concept I'm familiar with to a new (to me) concept. The idea being than one learns from doing :') My initial thought that it would be a simple reusable code structure to re-map is shaping up otherwise. Thanks, Lee C On Jun 8, 2005, at 1:10 AM, Javier Ruere wrote: > Lee Cullens wrote: > > >> I was thinking of extending the learning exercise by re-factoring it >> as an OO approach, since it would contain a minimum altered method. >> Being new to OOP also though, I'm confusing myself with how that >> would be best accomplished. My thinking is that class/subclass >> method instances would replace the recursive functions approach, but >> have as yet not formed the coding in my mind. >> >> > > I can't imagine this either and, though I'm no OO guru, have never > considered that that an inheritance relationship could replace a > recursive function call. > > > >> I've read a lot on OOP, but seem to have a problem with the practical >> use of such in this utility. I'm undoubtedly creating a mountain of >> an ant hill in my mind, so any thoughts would be appreciated. >> >> > > I don't see any benefit from using OO in this case. Module level > functions (like you have now) are ideal in this case IMHO. > Maybe in a situation where you can benefit from OO it would be > crearer how to use it. Having state is usually a good sign. Working > with > several "things" which have a behaviour would be another. > Just for fun lets do it anyway. :) Directories and files could be > considered things, files could tell if they are files, links or > whatever > and directories could tell which subdirectories and files they have. > Also this objects could render themselfs to a proper string > representation we can directly output as a row. > So, in pseudocode, this would be something like: > > class File: > """File(name:str, parent:Dir) > > parent: The directory which contains this File. > name: The name of this File. > """ > def __init__(self, name, parent): > self._parent = parent > self._name = name > > assert exists(join(repr(parent), name)) > > def isLink(self): > return islink(self.path) > > [Rest of the is* functions.] > > def __str__(self): > return [...] > > class Dir: > """Dir(name:str, [parent:Dir]) > > parent: The directory which contains this File. > If omited, an absolute path is assumed. > name: The name of this File. > """ > def __init__(self, name, parent=None) > self._parent = parent > self._name = name > > assert isdir(join(repr(parent), name)) > > def getDirs(self): > return [...] > > def getFiles(self): > return [...] > > Now, both classes could inherit from a FSElement (or something) > but I > see no benefit in doing that. > The output functionality could also be in a different class: > > class CSVOutput: > def __init__(self, filename): > [validate for overwritting] > self._out = file(filename, 'w') > > def process(self, root): > for file in root.getFiles(): > self._out.write(str(file)) > > for dir in root.getDirs(): > self.process(dir) > > And the main: > > CVSOuput(argv[2]).process(Dir(mkAbsolutePath(argv[1]))) > > I'm very sleepy so this could all just be gibberish but I hope it > will help you get the idea. Ideally, functions should be very small, a > couple of lines, and object should be reusable. So moving the > rendering > to CVSOutput would be better. :) > > Javier > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cyresse at gmail.com Wed Jun 8 08:10:39 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 8 Jun 2005 18:10:39 +1200 Subject: [Tutor] remove from python In-Reply-To: References: <000c01c56bbc$2f7a3910$0302a8c0@your46e94owx6a> Message-ID: Personally, I find the Digest a bit harder to use, so I just use my gmail account for the list, and use filters to automatically tag the Python list, and gmail's so ludicrously big, you don't really notice that you have 2208 messages stored. Then they're easy to search through as well. Liam Clarke On 6/8/05, Danny Yoo wrote: > > > > On Tue, 7 Jun 2005, The Johnsons wrote: > > > how can i get my email address removed, I'm receiving way too many > > emails > > Hi Raywood1, > > You have a few options. You may want to see if just turning the Tutor > mailing list setting to "Digest Mode" might help. You can do this > through: > > http://mail.python.org/mailman/options/tutor?email=raywood1 at entouch.net > > Digest mode will bundle up messages from Tutor so that you don't get so > deluged. If you want to unsubscribe, there should be instructions on how > to do so from that page too. > > > Finally, if you have more questions on administrative stuff, or if you run > into difficulty while unsubscribing, then send an email to > tutor-owner at python.org, and the administrators will help you get off the > list. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050608/66569510/attachment.html From alan.gauld at freenet.co.uk Wed Jun 8 09:21:58 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 8 Jun 2005 08:21:58 +0100 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalesecritique) References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> <5D756447-82AA-4BEB-8A3E-3898572BA52C@mac.com> Message-ID: <033501c56bfa$c1c66d50$26ba8651@xp> > You've certainly given me a mouthful to chew on :~) I was thinking > more in terms of "OOP is about code reuse" Thats not a good approach to OOP. Code reuse is often as easy to achieve using modules and functions. As Javier said OOP is aboiut "things" - objects. You need to build your whole design around objects communicating with each other, each with some responsibility within the program. The methods implement those responsibilities. Inheritance is a way of abstracting up from specific things to higher level things - the fact that it saves some coding sometimes is a bonus side-effect. In a perfect OO design you should be able to describe (and build) the system using entirely abstract classes, then to make it effective simple implement the sub-classes and plug them in. Its rarely as clean as that but its the goal towards which OO designers strive. > I'm not actually looking for the best approach here - rather just > trying to map a concept I'm familiar with to a new (to me) concept. Thats an OK approach, but the way to map to OOP is to: 1) say what are the objects? 2) can I group the objects into super/sub class chunks 3) what are the responsibilities of each class within my problem 4) build one class, the lowest level one, with no dependencies on the others 5) test it (at the >>> prompt?) 6) build another class with no dependencies on as yet unbuilt classes 7) test it at the >>> prompt 8) test it in in conjunction with the other classes it uses. 9) repeat 6-9 until all classes are built and tested (or enough to implement some part of your application - a "use case"). 10) build the driver program/fuinctoion/object that will pull it all together into an application. And ask questions here as you go :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cyresse at gmail.com Wed Jun 8 11:24:25 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 8 Jun 2005 21:24:25 +1200 Subject: [Tutor] keylogger In-Reply-To: References: Message-ID: Out of curiosity, why the interest in logging keys? I'm also pretty sure that a Python programme couldn't run as quietly as most keyloggers tend to... On 6/8/05, Vladimir Rasputin wrote: > > Can i make a keylogger using python? > has anyone ever made one/tryed to make one? > does any one know how to make one? > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050608/23ac492c/attachment.htm From tangyuejun at myetone.com Wed Jun 8 11:34:56 2005 From: tangyuejun at myetone.com (tangyuejun@myetone.com) Date: Wed, 8 Jun 2005 17:34:56 +0800 Subject: [Tutor] Tutor Digest, Vol 16, Issue 22 In-Reply-To: Message-ID: I am looking for a web scraping sample.who can help me? Best & Regards Adam Tang Myetone info.tech. Co.,Ltd. Tel: (021)53852321-801 Fax:(021)53852320 Mail: tangyuejun at myetone.com Msn:online4u8 at hotmail.com Skype:tangyuejun Address: 403 Room,18 Xichang Road(M) Ganglu Plaza Shanghai,China Post Code: 200001 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050608/55e919ef/attachment.html From kent37 at tds.net Wed Jun 8 11:56:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 05:56:54 -0400 Subject: [Tutor] Web scraping In-Reply-To: References: Message-ID: <42A6C0E6.8060105@tds.net> tangyuejun at myetone.com wrote: > > I am looking for a web scraping sample.who can help me? Take a look at Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ Kent From kent37 at tds.net Wed Jun 8 12:12:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 06:12:41 -0400 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique) In-Reply-To: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> Message-ID: <42A6C499.4000905@tds.net> Lee Cullens wrote: > I was thinking of extending the learning exercise by re-factoring it > as an OO approach, since it would contain a minimum altered method. > Being new to OOP also though, I'm confusing myself with how that > would be best accomplished. My thinking is that class/subclass > method instances would replace the recursive functions approach, but > have as yet not formed the coding in my mind. Using an OOP approach won't change the algorithm from recursive to non-recursive. To me, OOP is about code organization and abstraction. It is a way to collect code and data into chunks that can be used at a higher level of abstraction than just the raw data. OOP is not necessary for reuse - functional modules can be very useful and reusable. There is a spectrum of re-use. Many of my programs have classes that are only instantiated once. They are not reused but they provide a useful way to organize the code and provide a useful building block for the rest of the program. I also have many classes that are reused within the program containing them, this is an important kind of reuse. And some classes I write are more broadly useful and are re-used in more than one program. I have written an essay about when to use classes that approaches the question from a very simple, practical point of view. http://www.pycs.net/users/0000323/stories/15.html Javier's File and Dir classes are strongly reminiscent of the path class in J Orendorff's path module; you might want to take a look at it. Highly recommended for file and directory manipulations. http://www.jorendorff.com/articles/python/path/ Alan G wrote: > 4) build one class, the lowest level one, with no dependencies on the > others Yes!! Try to think of your classes as reusable modules even if you don't anticipate reusing them! Don't allow dependency cycles. > 5) test it (at the >>> prompt?) Testing is good. Do yourself a favor and learn how to use unittest (or doctest or py.test). If you write your tests as unit tests instead of doing them by hand in the interpreter, you can re-run the tests as needed. This is invaluable when you make a change to your code and want to know if you have broken anything - you don't have to test manually, you just run the unit test. Kent From cyresse at gmail.com Wed Jun 8 12:23:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 8 Jun 2005 22:23:52 +1200 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique) In-Reply-To: <42A6C499.4000905@tds.net> References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> <42A6C499.4000905@tds.net> Message-ID: Path looks good. Cheers Kent. On 6/8/05, Kent Johnson wrote: > > Lee Cullens wrote: > > I was thinking of extending the learning exercise by re-factoring it > > as an OO approach, since it would contain a minimum altered method. > > Being new to OOP also though, I'm confusing myself with how that > > would be best accomplished. My thinking is that class/subclass > > method instances would replace the recursive functions approach, but > > have as yet not formed the coding in my mind. > > Using an OOP approach won't change the algorithm from recursive to > non-recursive. > > To me, OOP is about code organization and abstraction. It is a way to > collect code and data into chunks that can be used at a higher level of > abstraction than just the raw data. OOP is not necessary for reuse - > functional modules can be very useful and reusable. > > There is a spectrum of re-use. Many of my programs have classes that are > only instantiated once. They are not reused but they provide a useful way to > organize the code and provide a useful building block for the rest of the > program. I also have many classes that are reused within the program > containing them, this is an important kind of reuse. And some classes I > write are more broadly useful and are re-used in more than one program. > > I have written an essay about when to use classes that approaches the > question from a very simple, practical point of view. > http://www.pycs.net/users/0000323/stories/15.html > > Javier's File and Dir classes are strongly reminiscent of the path class > in J Orendorff's path module; you might want to take a look at it. Highly > recommended for file and directory manipulations. > http://www.jorendorff.com/articles/python/path/ > > Alan G wrote: > > 4) build one class, the lowest level one, with no dependencies on the > > others > > Yes!! Try to think of your classes as reusable modules even if you don't > anticipate reusing them! Don't allow dependency cycles. > > > 5) test it (at the >>> prompt?) > > Testing is good. Do yourself a favor and learn how to use unittest (or > doctest or py.test). If you write your tests as unit tests instead of > doing them by hand in the interpreter, you can re-run the tests as needed. > This is invaluable when you make a change to your code and want to know if > you have broken anything - you don't have to test manually, you just run the > unit test. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050608/9c70ffe1/attachment.htm From cyresse at gmail.com Wed Jun 8 12:45:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 8 Jun 2005 22:45:52 +1200 Subject: [Tutor] Web scraping In-Reply-To: <42A6C0E6.8060105@tds.net> References: <42A6C0E6.8060105@tds.net> Message-ID: An alternative win32 approach is - Use something like IEC http://www.mayukhbose.com/python/IEC/index.php or PAMIE http://pamie.sourceforge.net/, or you can use the python win32 extensions http://starship.python.net/crew/skippy/win32/Downloads.html and use IE & navigate through the DOM... but PAMIE is easier. Good luck. On 6/8/05, Kent Johnson wrote: > > tangyuejun at myetone.com wrote: > > > > I am looking for a web scraping sample.who can help me? > > Take a look at Beautiful Soup > http://www.crummy.com/software/BeautifulSoup/ > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050608/05b08f5c/attachment.html From leec03273 at mac.com Wed Jun 8 15:20:57 2005 From: leec03273 at mac.com (Lee Cullens) Date: Wed, 8 Jun 2005 09:20:57 -0400 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalesecritique) In-Reply-To: <033501c56bfa$c1c66d50$26ba8651@xp> References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> <5D756447-82AA-4BEB-8A3E-3898572BA52C@mac.com> <033501c56bfa$c1c66d50$26ba8651@xp> Message-ID: Javier, Allen, Kent, Liam Hmm, I think I understand what you all are saying. Basically, my familiar take on "code reuse" (the function model) as used in the utility is essentially not rewriting any more of a block than what is different, as opposed to "do all" blocks with convoluted switching. Whereas what it seems to me you are saying is levels of functional abstraction more akin to the Unix model. My only prior experience with OOP was with Lingo several years ago in a variable record file use, which was simple to grasp. Obviously my take is flawed, so I will study the material noted, reread my Learning Python Part VI, and take another stab at it. No doubt this is "rank amateurish" to you all - somewhat like I felt back in the 80's when a "senior analyst" asked me how to use more than one output file in a COBOL program ;') Anyway, starting with assembler in the 60s, and doing my last substantial technical work in the 80s with C and Pascal, I have a bit of catching up to do :~) Thank you all for pointing me in the right direction, Lee C From cyresse at gmail.com Wed Jun 8 15:24:42 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 9 Jun 2005 01:24:42 +1200 Subject: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalesecritique) In-Reply-To: References: <908AB8BA-AAA9-4328-B9B9-D9AB13297CC1@mac.com> <5D756447-82AA-4BEB-8A3E-3898572BA52C@mac.com> <033501c56bfa$c1c66d50$26ba8651@xp> Message-ID: Hey Lee, I can empathise with your learning of OO. Once you get past the buzz, it's just a way of designing programmes that's good for certain situations. Very useful for things like writing text validators for GUIs as an abstract class and subclassing all windows from that to inherit the validator functions for every text field, but I'd rarely create a class for some linear text processing. Regards, Liam Clarke On 6/9/05, Lee Cullens wrote: > > Javier, Allen, Kent, Liam > > Hmm, I think I understand what you all are saying. Basically, my > familiar take on "code reuse" (the function model) as used in the > utility is essentially not rewriting any more of a block than what is > different, as opposed to "do all" blocks with convoluted switching. > Whereas what it seems to me you are saying is levels of functional > abstraction more akin to the Unix model. > > My only prior experience with OOP was with Lingo several years ago in > a variable record file use, which was simple to grasp. > > Obviously my take is flawed, so I will study the material noted, > reread my Learning Python Part VI, and take another stab at it. > > No doubt this is "rank amateurish" to you all - somewhat like I felt > back in the 80's when a "senior analyst" asked me how to use more > than one output file in a COBOL program ;') Anyway, starting with > assembler in the 60s, and doing my last substantial technical work in > the 80s with C and Pascal, I have a bit of catching up to do :~) > > Thank you all for pointing me in the right direction, > Lee C > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050609/042d219f/attachment.html From erastley at charter.net Wed Jun 8 18:30:41 2005 From: erastley at charter.net (EUGENE ASTLEY) Date: Wed, 8 Jun 2005 09:30:41 -0700 Subject: [Tutor] FW: Tutor Digest, Vol 16, Issue 21, #3 Text problem Message-ID: <002701c56c47$6c8042b0$6501a8c0@D3K8PT61> I tried your suggestion but it does not work for me. I get a syntax error at use of the first question mark when trying it in Idle. When I try it from the desktop, it just flashes a black screen and returns me to the desktop. What is the question mark used for? I looked up the use of % and the glossary says it returns the modulus. I don't understand why I would want the modulus of anything. I like the idea of text = text because it allows me to more easily change my text. As long as I put text = "Your Score is : " + str( Game.score_value) the program works fine. Sorry I need further help Gene -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tutor-request at python.org Sent: Tuesday, June 07, 2005 2:58 PM To: tutor at python.org Subject: Tutor Digest, Vol 16, Issue 21 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. repr() (Bernard Lebel) 2. Re: repr() (Max Noel) 3. Re: Text problem (Kent Johnson) 4. Re: repr() (Danny Yoo) 5. Re: More image manipulation (Terry Carroll) 6. Re: repr() (Terry Carroll) 7. Re: repr() (Bernard Lebel) 8. Re: Trying Ruby... (Christian Wyglendowski) 9. Re: More image manipulation (Terry Carroll) 10. Re: repr() (Danny Yoo) 11. Re: interactif or not (Alan G) 12. Fwd: More image manipulation (D. Hartley) ---------------------------------------------------------------------- Message: 1 Date: Tue, 7 Jun 2005 15:42:39 -0400 From: Bernard Lebel <3dbernard at gmail.com> Subject: [Tutor] repr() To: tutor at python.org Message-ID: <61d0e2b405060712426fec5107 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 Hello, Possibly I am missing something, but how do you use the repr() function? I type this ultra-simple function: def myFunc(): print 'hello' Then run repr( myFunc ) Wich returns '' Okay then I run s = repr( myFunc() ) print s Wich returns 'None' Thanks Bernard ------------------------------ Message: 2 Date: Tue, 7 Jun 2005 20:50:51 +0100 From: Max Noel Subject: Re: [Tutor] repr() To: Bernard Lebel <3dbernard at gmail.com> Cc: tutor at python.org Message-ID: <36EFC744-7AE8-49F8-B793-85EF054BA0C4 at yahoo.fr> Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On Jun 7, 2005, at 20:42, Bernard Lebel wrote: > repr( myFunc ) > > Wich returns > > '' > > > Okay then I run > > s = repr( myFunc() ) > print s > > Wich returns > > 'None' That's perfectly normal. Your last assignment calls the function, then assigns to s the representation of the function's return value. A function that doesn't have a return statement returns None, and repr(None) == 'None'. Which is what you get. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ------------------------------ Message: 3 Date: Tue, 07 Jun 2005 15:51:28 -0400 From: Kent Johnson Subject: Re: [Tutor] Text problem Cc: tutor at python.org Message-ID: <42A5FAC0.4050005 at tds.net> Content-Type: text/plain; charset=windows-1252; format=flowed EUGENE ASTLEY wrote: > Python, pygames problem. > > At the end of my game, I go back to the desk top after displaying the > score of the player, as follows: > > Def game_over(self) > > Games.Message(screen = self.screen, > > X = 400, y = 400 > > Text + ?Your Score is ? + str(Game.score_value), > > Size = 60, color = color.green, > > Lifetime = 1000, after_death = self.screen.quit() > > > > This works well but I would like to have several lines of text. The > triple quote method does not work. How can I get several lines of text > into the message? It looks like you are using livewires and you have paraphrased your code. It's helpful if you copy and paste the exact code you have tried and any error message you get. Looking at livewires.games.py I see class Message(Text): def __init__ (self, screen, x, y, text, size, color, a=0, dx=0, dy=0, da=0, lifetime=0, after_death=None): so I would try something like this: def gameOver(self): text = ?""Your Score is %s Thank you for playing Please come again""? % Game.score_value games.Message(x = 400, y = 400, text = text, size = 60, color = color.green, lifetime = 1000, after_death = self.screen.quit()) Kent ------------------------------ Message: 4 Date: Tue, 7 Jun 2005 13:25:15 -0700 (PDT) From: Danny Yoo Subject: Re: [Tutor] repr() To: Bernard Lebel <3dbernard at gmail.com> Cc: tutor at python.org Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII > Okay then I run > > s = repr( myFunc() ) > print s > > Wich returns > > 'None' Hi Bernard, Ok, what do you expect to see instead of 'None'? I ask this to make sure I understand the situation better. Best of wishes? ------------------------------ Message: 5 Date: Tue, 7 Jun 2005 13:26:16 -0700 (PDT) From: Terry Carroll Subject: Re: [Tutor] More image manipulation To: "D. Hartley" , Python tutor Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Tue, 7 Jun 2005, D. Hartley wrote: > def findlist(): > newlist = [] > for i in range(480): > line = fromlist[:640] > del fromlist[:640] > x = line.index(195) > y = x + 5 > z = line[x:y] > del line[x:y] > for i in z: > newlist.append(i) > for i in line: > newlist.append(i) > return newlist where does the variable named "fromlist" come from? It's not passed into the method as a parameter. > B). If I run the steps in makenewpic one by one in the interpreter, it > doesnt give me any "x not in list" error, it lets me do the result = > newim.putdata(a) just fine. But then when I type result.show() it > tells me 'NoneType' object has no attribute 'show'. At first I > thought it was because when I was creating the blank newim, I was > using mode "RGB" and adding a list of "P" pixel values to it. But I > fixed it so that my newim is also mode "P" and it still tells me that > type(result) = None. You have: > result = newim.putdata(a) > return result >From the PIL docs, putdata does not appear to return an image. The docs for putdata say: putdata im.putdata(data) im.putdata(data, scale, offset) Usually, when a PIL method returns an image, the docs say "=> image" after the method signature. My guess is that putdata returns None, which would be consistent with the error message "'NoneType' object has no attribute 'show'." You'll probably want: newim.putdata(a) return newim Instead. ------------------------------ Message: 6 Date: Tue, 7 Jun 2005 13:29:31 -0700 (PDT) From: Terry Carroll Subject: Re: [Tutor] repr() To: Bernard Lebel <3dbernard at gmail.com>, Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Tue, 7 Jun 2005, Bernard Lebel wrote: > repr( myFunc ) > '' > > > > s = repr( myFunc() ) > print s > > 'None' In the first example, your repr invocation is: repr(myFunc) i.e., you're asking for the repr of the function myFunc. In the second example, your repr invocation is: repr(myFunc()) i.e., you're calling the function myFunc and asking for the repr of the *result* ------------------------------ Message: 7 Date: Tue, 7 Jun 2005 16:42:05 -0400 From: Bernard Lebel <3dbernard at gmail.com> Subject: Re: [Tutor] repr() To: tutor at python.org Message-ID: <61d0e2b405060713421e92172d at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 Ok thanks a lot. The real question is, then, is there a way I can print the code of a function as a string? Something like.... 'def myFunction: print "hello"' Thanks Bernard On 6/7/05, Max Noel wrote: > > On Jun 7, 2005, at 20:42, Bernard Lebel wrote: > > > repr( myFunc ) > > > > Wich returns > > > > '' > > > > > > Okay then I run > > > > s = repr( myFunc() ) > > print s > > > > Wich returns > > > > 'None' > > That's perfectly normal. Your last assignment calls the > function, then assigns to s the representation of the function's > return value. A function that doesn't have a return statement returns > None, and repr(None) == 'None'. Which is what you get. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > ------------------------------ Message: 8 Date: Tue, 7 Jun 2005 15:50:38 -0500 From: "Christian Wyglendowski" Subject: Re: [Tutor] Trying Ruby... To: "Terry Carroll" , Message-ID: Content-Type: text/plain; charset="us-ascii" > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Terry Carroll > Sent: Monday, June 06, 2005 8:20 PM > To: tutor at python.org > Subject: [Tutor] Trying Ruby... > > This message is not as off-topic as it at first appears. > > I'm a user of Activestate's ActivePython under Windows/XP. I > want to give > Ruby a spin, just for the heck of it. I vaguely recall a post a few > months ago, I don't know if it was in this forum, where someone had a > problem in Python, and it turns out it was because a Ruby > install messed > with some setting, perhaps in the Windows registry. Terry, If I remember correctly, it had to do with Tk getting messed up. But that's all I recall :-) Christian http://www.dowski.com ------------------------------ Message: 9 Date: Tue, 7 Jun 2005 13:52:08 -0700 (PDT) From: Terry Carroll Subject: Re: [Tutor] More image manipulation To: Python tutor Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Tue, 7 Jun 2005, Terry Carroll wrote: > On Tue, 7 Jun 2005, D. Hartley wrote: > > > def findlist(): > > newlist = [] > > for i in range(480): > > line = fromlist[:640] > > del fromlist[:640] > > x = line.index(195) > > y = x + 5 > > z = line[x:y] > > del line[x:y] > > for i in z: > > newlist.append(i) > > for i in line: > > newlist.append(i) > > return newlist > > where does the variable named "fromlist" come from? It's not passed into > the method as a parameter. I'm thinking more and more that this is the issue. Take a look at this, and see if it gives you the flavor. Only the third approach actually gives you what (I think) you want, rather than reusing the same list over and over. def testit1(): print fromlist1[0] del fromlist1[0] return fromlist1 = ['a', 'b', 'c', 'd'] print "testit1: Denise problem" testit1() testit1() testit1() def testit2(flist): print flist[0] del flist[0] return fromlist2 = ['a', 'b', 'c', 'd'] print "testit2: Python Gotcha #6" # http://www.ferg.org/projects/python_gotchas.html testit2(fromlist2) testit2(fromlist2) testit2(fromlist2) def testit3(flist): mylist = flist[:] # copy the list rather than mutating it for next time print mylist[0] del mylist[0] return fromlist3 = ['a', 'b', 'c', 'd'] print "testit3: the right way" testit3(fromlist3) testit3(fromlist3) testit3(fromlist3) ------------------------------ Message: 10 Date: Tue, 7 Jun 2005 14:04:08 -0700 (PDT) From: Danny Yoo Subject: Re: [Tutor] repr() To: Bernard Lebel <3dbernard at gmail.com> Cc: Tutor Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Tue, 7 Jun 2005, Bernard Lebel wrote: > The real question is, then, is there a way I can print the code of a > function as a string? Something like.... > > 'def myFunction: print "hello"' Hi Bernard, Ah, ok. You can use 'inspect': http://www.python.org/doc/lib/inspect-source.html For example: ###### >>> import heapq >>> import inspect >>> print inspect.getsource(heapq.heappop) def heappop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0) else: returnitem = lastelt return returnitem ###### It doesn't always work: it'll work only if the function is a pure-Python function that's defined in a file that Python can find, since functions themselves don't carry their own textual representation around. Functions do contain the file name as well as their corresponding line numbers: ###### >>> heapq.__file__ '/usr/lib/python2.3/heapq.pyc' >>> heapq.heappop.func_code.co_firstlineno 136 ###### which is sorta how inspect.getsource() works. Best of wishes! ------------------------------ Message: 11 Date: Tue, 7 Jun 2005 22:15:57 +0100 From: "Alan G" Subject: Re: [Tutor] interactif or not To: "Cedric BRINER" , Message-ID: <02c401c56ba6$1941c110$26ba8651 at xp> Content-Type: text/plain; charset="iso-8859-1" > > look to see if stdin is a tty. Unix is usually very careful about who has a > > "controlling tty" and who does not. In Python, file objects have an isatty() > > method that will return True or False. > > > > import sys > > isinteractive = sys.stdin.isatty() > > if isinteractive: > > ... > > else: > > ... > > > > tested and it works ! Aha! I knew about tty on Unix so I looked in the os module for it, I never thought of it being a file method.... Alan G. ------------------------------ Message: 12 Date: Tue, 7 Jun 2005 14:57:33 -0700 From: "D. Hartley" Subject: [Tutor] Fwd: More image manipulation To: Python tutor Message-ID: <8daabe5605060714577da931f9 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 Sorry, Terry, forgot to reply to the whole list. Here it is: ---------- Forwarded message ---------- From: D. Hartley Date: Jun 7, 2005 2:49 PM Subject: Re: [Tutor] More image manipulation To: Terry Carroll Terry, OK. I tried them out and I do see the diffence. (btw, testit1 gave me the following error: Traceback (most recent call last): File "", line 1, in ? testit1() File "", line 3, in testit1 del fromlist[0] IndexError: list assignment index out of range ... was that something you intended? that didnt happen with my original problem). Anyway I def notice the diff between 2 and 3, but see here's the thing: I think I *do* want it like #2, becaues I want it to keep returning the same list (i.e., move on and use line 2 (b), and then line 3 (c), and so on), rather than keep iterating over the same first line (a) over and over again. I want to take the first line in the picture, rearrange the pixels, and pop that line into the new list that I can then (eventually) create a new image from. I *thought* my list was populated (it's 307200 pixels long, after all), but it wont work when i try to putdata it onto a new blank image. > > where does the variable named "fromlist" come from? It's not passed into > > the method as a parameter. No, I had it defined right before the function. it pulls it in just fine. And like I said, the function returns me with a list of 307200 values - which makes me think that it "got" all 307200 of the original pixels, and performed the function correctly on each line. However, when I did the following: def test(): y = findlist() for i in range(480): piece = y[:640] del y[:640] print "Line",i," - ",y[:5] to look at the beginning five pixels of each of the new lines, for line 479 (the last i), it gave me []. This doesnt make sense! Hope I didnt miss something from your explanation...? ~Denise ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 16, Issue 21 ************************************* From kristiano7 at gmail.com Wed Jun 8 18:48:42 2005 From: kristiano7 at gmail.com (Kristiano Ang) Date: Thu, 9 Jun 2005 00:48:42 +0800 Subject: [Tutor] Just a Python formatting question Message-ID: <7175b2cc050608094826afaf1c@mail.gmail.com> Hey guys, I'm pretty new to Python (using Mac Python 2.4.1) and have a question with formatting that I hope you can help me with. Sometimes, when I write code with Python (copied off tuts.), I get error messages and highlights of the word "else". Take for example: #plays the guessing game higher or lower #originally written by Josh Cogliati, improved by Quique and copied by Kristiano Ang number=78 guess=0 while guess != number: guess=input ("Guess a number:") if guess > number: print "Too High" elif guess < number: print "Too low" print "Just right" I just can't get it to run and I get some indentation error. I'm pretty new to this so I'm sorry if this question(s) sound(s) amateurish. Do help. Thanks. -Kristiano Ang From john.ertl at fnmoc.navy.mil Wed Jun 8 19:09:32 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 8 Jun 2005 10:09:32 -0700 Subject: [Tutor] Just a Python formatting question Message-ID: Kristiano, It is sometimes hard to tell the indentions in an email but it looks like your last line print "Just right" has a space in front of it. Python does not know what logical block the indented part belongs to. John Ertl -----Original Message----- From: Kristiano Ang [mailto:kristiano7 at gmail.com] Sent: Wednesday, June 08, 2005 09:49 To: tutor at python.org Subject: [Tutor] Just a Python formatting question Hey guys, I'm pretty new to Python (using Mac Python 2.4.1) and have a question with formatting that I hope you can help me with. Sometimes, when I write code with Python (copied off tuts.), I get error messages and highlights of the word "else". Take for example: #plays the guessing game higher or lower #originally written by Josh Cogliati, improved by Quique and copied by Kristiano Ang number=78 guess=0 while guess != number: guess=input ("Guess a number:") if guess > number: print "Too High" elif guess < number: print "Too low" print "Just right" I just can't get it to run and I get some indentation error. I'm pretty new to this so I'm sorry if this question(s) sound(s) amateurish. Do help. Thanks. -Kristiano Ang _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Wed Jun 8 19:17:17 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 8 Jun 2005 18:17:17 +0100 Subject: [Tutor] #3 Text problem References: <002701c56c47$6c8042b0$6501a8c0@D3K8PT61> Message-ID: <004f01c56c4d$ec732d60$c7a58851@xp> > Subject: [Tutor] FW: Tutor Digest, Vol 16, Issue 21, #3 Text problem Its best not to reply to the list digest header mail! If for no other reason than the fact you send the whole digest out with your mail which isn't very friendly for those still using slow dial up! :-) > I tried your suggestion but it does not work for me. I get a syntax > error at use of the first question mark when trying it in Idle. > When I try it from the desktop, it just flashes a black screen and > returns me to the desktop. Try adding a line: raw_input('Hit enter to quit') at the end of your program. It sounds like its running and exiting before you can reads it! > What is the question mark used for? I looked up the use of % and the > glossary says it returns the modulus. Thats one use but its also used for interpolating text into strings as in: s = 'A string with the number %d in it" % 42 s now contains 'A string with the number 42 in it' So the % inserts the 42 at the position marked by %d (where d=decimal digit) You can insert other type values too. This is known as a format string, try searching the help for that. > I don't understand why I would want the modulus of anything. Modulus (ie remainder part of an integer division) is very useful for all sorts ofthings in programming, I'd be surprised if you never found a use for it! :-) Alan G. From lopoff at gmx.net Wed Jun 8 19:38:18 2005 From: lopoff at gmx.net (lmac) Date: Wed, 08 Jun 2005 19:38:18 +0200 Subject: [Tutor] long int in list as argument for seek() function Message-ID: <42A72D0A.2050000@gmx.net> Hi there, i want to use an long int from an list which i got from my function find_lineno(). But i got this error and i don't understand why i can not use this long as an argument. Where do i find a good documentation on errors so that i complete understand what the heck is going on. Many thanks. ERROR: --------------------------------------------------- Traceback (most recent call last): File "./extrmails.py", line 42, in ? inputfile.seek(0,li) IOError: [Errno 22] Invalid argument --------------------------------------------------- CODE-START: ----------------------------------------------------------------------------- inputfile=open("mails","rt") # -------------------------------------------------------------------------- def reset_inputfile(): inputfile.seek(0,0) # -------------------------------------------------------------------------- def find_lineno(string): f = -1 a = "start" found_lines = [] reset_inputfile() while len(a) != 0: a = inputfile.readline() f = a.find(string) if f != -1: found_lines.append(inputfile.tell()) return found_lines # -------------------------------------------------------------------------- from_lineno=find_lineno("From:") subj_lineno=find_lineno("Subject:") print len(subj_lineno) print len(from_lineno) reset_inputfile() for li in subj_lineno: inputfile.seek(0,li) <------ ??????? ....... ...... -------------------------------------------------------------------------- CODE-END From kent37 at tds.net Wed Jun 8 20:03:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 14:03:48 -0400 Subject: [Tutor] Text problem In-Reply-To: <002701c56c47$6c8042b0$6501a8c0@D3K8PT61> References: <002701c56c47$6c8042b0$6501a8c0@D3K8PT61> Message-ID: <42A73304.5020309@tds.net> EUGENE ASTLEY wrote: > I tried your suggestion but it does not work for me. I get a syntax > error at use of the first question mark when trying it in Idle. > When I try it from the desktop, it just flashes a black screen and > returns me to the desktop. > What is the question mark used for? Somehow the text was garbled. In the quote below it shows question mark, quote, quote and quote, quote, question mark. In both places it should be quote, quote, quote - a triple-quoted string. Kent > def gameOver(self): > text = ?""Your Score is %s > Thank you for playing > Please come again""? % Game.score_value > games.Message(x = 400, y = 400, text = text, > size = 60, color = color.green, > lifetime = 1000, after_death = self.screen.quit()) From kent37 at tds.net Wed Jun 8 20:08:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 14:08:54 -0400 Subject: [Tutor] long int in list as argument for seek() function In-Reply-To: <42A72D0A.2050000@gmx.net> References: <42A72D0A.2050000@gmx.net> Message-ID: <42A73436.20305@tds.net> lmac wrote: > Hi there, > i want to use an long int from an list which i got from my function > find_lineno(). > But i got this error and i don't understand why i can not use this long > as an argument. You have the arguments to file.seek() reversed. > Where do i find a good documentation on errors so that i complete > understand what > the heck is going on. >From http://docs.python.org/lib/bltin-file-objects.html seek( offset[, whence]) Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). Kent > Many thanks. > > ERROR: > --------------------------------------------------- > Traceback (most recent call last): > File "./extrmails.py", line 42, in ? > inputfile.seek(0,li) > IOError: [Errno 22] Invalid argument > --------------------------------------------------- > > > CODE-START: > ----------------------------------------------------------------------------- > > inputfile=open("mails","rt") > > # -------------------------------------------------------------------------- > def reset_inputfile(): > inputfile.seek(0,0) > > # -------------------------------------------------------------------------- > def find_lineno(string): > f = -1 > a = "start" > found_lines = [] > reset_inputfile() > > while len(a) != 0: > a = inputfile.readline() > f = a.find(string) > if f != -1: > found_lines.append(inputfile.tell()) > > return found_lines > > # -------------------------------------------------------------------------- > > from_lineno=find_lineno("From:") > subj_lineno=find_lineno("Subject:") > > print len(subj_lineno) > print len(from_lineno) > > reset_inputfile() > > for li in subj_lineno: > inputfile.seek(0,li) <------ ??????? > ....... > ...... > -------------------------------------------------------------------------- > CODE-END > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Jun 8 22:17:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 9 Jun 2005 08:17:02 +1200 Subject: [Tutor] keylogger In-Reply-To: References: Message-ID: I still want to know why you want to write one, however. On 6/9/05, Vladimir Rasputin wrote: > > > No i was just wondering which language would be a good one to make a > keylogger with. Could you reconmend the one that would be the easiest? > > >From: Liam Clarke > >Reply-To: Liam Clarke > >To: Vladimir Rasputin > >CC: tutor at python.org > >Subject: Re: [Tutor] keylogger > >Date: Wed, 8 Jun 2005 21:24:25 +1200 > > > >Out of curiosity, why the interest in logging keys? > > > >I'm also pretty sure that a Python programme couldn't run as quietly as > >most > >keyloggers tend to... > > > >On 6/8/05, Vladimir Rasputin wrote: > > > > > > Can i make a keylogger using python? > > > has anyone ever made one/tryed to make one? > > > does any one know how to make one? > > > > > > _________________________________________________________________ > > > Express yourself instantly with MSN Messenger! Download today it's > FREE! > > > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > >-- > >'There is only one basic human right, and that is to do as you damn well > >please. > >And with it comes the only basic human duty, to take the consequences.' > > _________________________________________________________________ > FREE pop-up blocking with the new MSN Toolbar - get it now! > http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050609/ba54d17a/attachment.htm From missive at hotmail.com Thu Jun 9 00:29:56 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 09 Jun 2005 02:59:56 +0430 Subject: [Tutor] remove from python Message-ID: >>>how can i get my email address removed, I'm receiving way too many >>>emails >>You have a few options. You may want to see if just turning the Tutor >>mailing list setting to "Digest Mode" might help. You can do this >>through: >>http://mail.python.org/mailman/options/tutor?email=3Draywood1 at entouch.net >Personally, I find the Digest a bit harder to use, so I just use my gmail >account for the list, and use filters to automatically tag the Python list I am not a big "digest" fan either. I prefer to read as a newsgroup through the gmane news server: http://gmane.org/ _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar – get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From reederk at comcast.net Thu Jun 9 08:45:59 2005 From: reederk at comcast.net (Kevin Reeder) Date: Wed, 8 Jun 2005 23:45:59 -0700 Subject: [Tutor] Calling a function Message-ID: <20050608234559.33fc32d9.reederk@comcast.net> I'm having trouble with this code which is meant to run a time comparison between two similar functions. The first module is makezeros.py def lots_of_appends(): zeros = [] for i in range(10000): zeros.append(0) def one_multiply(): zeros = [0] * 10000 The second module is timings.py. import time, makezeros def do_timing(num_times, *funcs): totals = {} for func in funcs: totals[func] = 0.0 for x in range(num_times): for func in funcs: starttime = time.time() apply(func) stoptime = time.time() elapsed = stoptime-starttime totals[func] = totals[func] + elapsed for func in funcs: print "Running %s %d times took %.3f seconds" % (func.__name__, num_times, totals[func]) do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) Here's the outcome I get: $ python ./Python/timings.py Traceback (most recent call last): File "./Python/timings.py", line 17, in ? do_timing(100, (lots_of_appends, one_multiply)) File "./Python/timings.py", line 10, in do_timing apply(func) TypeError: 'tuple' object is not callable BTW, the code is taken straight out of Learning Python, but I've been banging my head on it for awhile. Any ideas?? Kevin From meesters at uni-mainz.de Thu Jun 9 08:52:59 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 9 Jun 2005 08:52:59 +0200 Subject: [Tutor] finding path to resource files in a GUI application Message-ID: <6c58aba9519c4645e41d1c13abd8452e@uni-mainz.de> Hi Currently I'm writing a GUI application with wxPython (on OS X, but I guess the problem is the same, regardless of the UNIX derivative one is using). When I start the main script where it is located the application finds all resource files (non-Python files like images and html files for html windows) without any problem. However, if a put a link in /usr/local/bin and start the script using the link the application cannot find those resource files - unless, of course, I will use full absolute paths to point to those files. One brief example to illustrate the problem: The class Goals is in a file called Help.py, located in '/gui_lib/' as seen from my main script. class Goals(wx.Frame): def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition): wx.Frame.__init__(self,parent, -1,title,size,style=wx.DEFAULT_FRAME_STYLE) self.frame = frame self.cwd = os.getcwd() self.html = HtmlWindow(self,-1) self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) #this, of course, won't work #if the main script is called from somewhere else and not the directory where the main script #is located Any ideas what I could use instead of os.getcwd to construct a relative path which will work even if I port the script to an other machine? Cheers Christian From ewald.ertl at hartter.com Thu Jun 9 09:19:57 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 9 Jun 2005 09:19:57 +0200 Subject: [Tutor] Calling a function In-Reply-To: <20050608234559.33fc32d9.reederk@comcast.net> References: <20050608234559.33fc32d9.reederk@comcast.net> Message-ID: <20050609091957.0000376c@sunray2.hartter.com> Hi! I don't know if I'm right here, because I've tested a simple model of what you're trying to do: on Wed, 8 Jun 2005 23:45:59 -0700 Kevin Reeder wrote : --------------------------------------------------------------------------------------------- Kevin Reeder > import time, makezeros Kevin Reeder > Kevin Reeder > def do_timing(num_times, *funcs): Here funcs is a tuple containing all remaining arguments of the functions. Kevin Reeder > totals = {} Kevin Reeder > for func in funcs: totals[func] = 0.0 Kevin Reeder > for x in range(num_times): Kevin Reeder > for func in funcs: Kevin Reeder > starttime = time.time() Kevin Reeder > apply(func) Kevin Reeder > stoptime = time.time() Kevin Reeder > elapsed = stoptime-starttime Kevin Reeder > totals[func] = totals[func] + elapsed Kevin Reeder > for func in funcs: Kevin Reeder > print "Running %s %d times took %.3f seconds" % Kevin Reeder > (func.__name__, num_times, totals[func]) Kevin Reeder > Kevin Reeder > do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) You call do_timing() with the number of calls and one Argument, the tuple of functions, so the funcs in do_timing() is a tuple containing your tuple on the call here. Calling it this way should solve it: do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) Here is a short extract from the Python-Shell of my test: >>> def myfuncs( *funcs): ... for func in funcs: ... apply( func ) ... >>> def sayHello(): ... print "Hello\n" ... >>> myfuncs( sayHello, sayHello ) Hello Hello >>> myfuncs( ( sayHello, sayHello) ) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in myfuncs TypeError: 'tuple' object is not callable ------------------- end ---------------------- HTH Ewald From jfouhy at paradise.net.nz Thu Jun 9 09:31:23 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 09 Jun 2005 19:31:23 +1200 (NZST) Subject: [Tutor] Calling a function In-Reply-To: <20050608234559.33fc32d9.reederk@comcast.net> References: <20050608234559.33fc32d9.reederk@comcast.net> Message-ID: <1118302283.42a7f04b0fe71@www.paradise.net.nz> Quoting Kevin Reeder : > The second module is timings.py. > > import time, makezeros > > def do_timing(num_times, *funcs): > totals = {} > for func in funcs: totals[func] = 0.0 > for x in range(num_times): > for func in funcs: > starttime = time.time() > apply(func) > stoptime = time.time() > elapsed = stoptime-starttime > totals[func] = totals[func] + elapsed > for func in funcs: > print "Running %s %d times took %.3f seconds" % > (func.__name__, num_times, totals[func]) > > do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) Hi Kevin, I have two comments. First, a simple one: Using "apply" is no longer necessary in python. It is better to just call the function directly. (ie: replace 'apply(func)' with 'func()') Now, to your problem: You have (possibly) slightly misunderstood the "star" notation. Consider: >>> def printArgs(*args): ... print args ... >>> printArgs(1, 2, 'foo', 'bar') (1, 2, 'foo', 'bar') Basically, all the arguments to printArgs get collected into a tuple, which gets the name 'args' in this example. Here's another example: >>> def printArgs2(x, y, *args): ... print 'x:', x ... print 'y:', y ... print 'remaining:', args ... >>> printArgs2(1, 'foo', 3, 'hello world', 99) x: 1 y: foo remaining: (3, 'hello world', 99) In this case, x and y consumed the first two arguments to printArgs2, and the remainder went into the catch-all args. Now, lets look at the relevant bits of your code: ---- def do_timing(num_times, *funcs): ... ---- This says: "Call the first argument 'num_times', and put any other arguments into a tuple called 'funcs'." You then do this: ---- do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) ---- Here, you are calling do_timing with _two_ arguments. First argument: 100 Second argument: (makezeros.lots_of_appends, makezeros.one_multiply) Your second argument is a tuple with two elements. funcs in your function will be set to a tuple containing all remaining arguments --- ie: ((makezeros.lots_of_appends, makezeros.one_multiply),) (which is a tuple with one element, whose element is a tuple with two elements). You can correct this in two ways: - Change the function definition to: def do_timing(num_times, funcs): Now, funcs is just an ordinary positional argument, and it will take whatever you give it. If you give it a tuple of functions, then you can iterate over it the way you expect. or: - Change the function call to: do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) *funcs will consume the two function arguments, giving you the same result as in the first option. My personal preference would be for the first option, which I think is clearer.. (it better expresses the idea that you have written a function which will take a list of functions and time them) HTH! -- John. From klappnase at freenet.de Thu Jun 9 10:17:30 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu, 9 Jun 2005 10:17:30 +0200 Subject: [Tutor] finding path to resource files in a GUI application In-Reply-To: <6c58aba9519c4645e41d1c13abd8452e@uni-mainz.de> References: <6c58aba9519c4645e41d1c13abd8452e@uni-mainz.de> Message-ID: <20050609101730.4a2d83de.klappnase@freenet.de> On Thu, 9 Jun 2005 08:52:59 +0200 Christian Meesters wrote: > Hi > > Currently I'm writing a GUI application with wxPython (on OS X, but I > guess the problem is the same, regardless of the UNIX derivative one is > using). When I start the main script where it is located the > application finds all resource files (non-Python files like images and > html files for html windows) without any problem. However, if a put a > link in /usr/local/bin and start the script using the link the > application cannot find those resource files - unless, of course, I > will use full absolute paths to point to those files. One brief example > to illustrate the problem: > > The class Goals is in a file called Help.py, located in '/gui_lib/' as > seen from my main script. > > class Goals(wx.Frame): > def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition): > wx.Frame.__init__(self,parent, > -1,title,size,style=wx.DEFAULT_FRAME_STYLE) > self.frame = frame > self.cwd = os.getcwd() > > self.html = HtmlWindow(self,-1) > self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) > #this, of course, won't work > #if the main script is called from somewhere else and not the > directory where the main script > #is located > > Any ideas what I could use instead of os.getcwd to construct a relative > path which will work even if I port the script to an other machine? > > Cheers > Christian > Hi Christian, try self.cwd = os.path.abspath(sys.path[0]) sys.path[0] is the directory of your main program file, with os.path.abspath() you can get rid of the "../../" stuff at the beginning of the path if the program is called from a link. I hope this helps Michael From reederk at comcast.net Thu Jun 9 10:17:20 2005 From: reederk at comcast.net (Kevin Reeder) Date: Thu, 9 Jun 2005 01:17:20 -0700 Subject: [Tutor] Calling a function In-Reply-To: <20050608234559.33fc32d9.reederk@comcast.net> References: <20050608234559.33fc32d9.reederk@comcast.net> Message-ID: <20050609011720.2ac8b62c.reederk@comcast.net> Ewald & John, thanks for the help. i'll work on it some more with your ideas in mind (after getting some sleep). Kevin From jhe13586 at bigpond.net.au Thu Jun 9 10:50:53 2005 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Thu, 09 Jun 2005 18:50:53 +1000 Subject: [Tutor] Calling a function In-Reply-To: References: Message-ID: <42A802ED.2000909@bigpond.net.au> Kevin Reeder said: >def do_timing(num_times, *funcs): Took me a while to work out what went wrong, but the first part occurs here. The *funcs bit means that any extra arguments passed to do_timing will be put into a tuple called funcs. So do_timing(100, dosomething, dosomethingelse) will pass the following arguments to the body of the function: num_times = 100 funcs = (dosomething, dosomethingelse) > totals = {} > for func in funcs: totals[func] = 0.0 You may want to recode this bit as well. I'll cover that in the PS. > for x in range(num_times): > for func in funcs: > starttime = time.time() > apply(func) > stoptime = time.time() > elapsed = stoptime-starttime > totals[func] = totals[func] + elapsed > for func in funcs: > print "Running %s %d times took %.3f seconds" % >(func.__name__, num_times, totals[func]) > >do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) And here's the next part of the problem. Instead of letting do_timing wrap the extra arguments up into a tuple for you: do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) You are wrapping your two functions up as a tuple. So the do_timing function recieves the following when it starts: num_times = 100 funcs = ((makezeros.lots_of_appends, makezeros.one_multiply),) I.e. one entry which is a tuple. >Here's the outcome I get: > >$ python ./Python/timings.py >Traceback (most recent call last): > File "./Python/timings.py", line 17, in ? > do_timing(100, (lots_of_appends, one_multiply)) > File "./Python/timings.py", line 10, in do_timing > apply(func) >TypeError: 'tuple' object is not callable And that is why you get this TypeError. When you pass the first component of funcs to the apply(funcs) bit, you're asking python to do the following: apply((makezeros.lots_of_appends, makezeros.one_multiply)) Which python can't/won't do. *grins* P.S. You ask the code to set all total[funcs] = 0.0 Then you ask the code to calculate the timings of each function. Then you ask the code to print the timings for eac function. You're looping through the same data set three times. Even if you want the timings to print last, you can optimize you're code a little bit by doing the following: def do_timing(num_times, *funcs): totals = {} for func in funcs: totals[func] = 0.0 for x in range(num_times): starttime = time.time() apply(func) stoptime = time.time() elapsed = stoptime-starttime totals[func] = totals[func] + elapsed for func in funcs: print "Running %s %d times took %.3f seconds" % (func.__name__, num_times, totals[func]) Have fun! From meesters at uni-mainz.de Thu Jun 9 12:43:42 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 9 Jun 2005 12:43:42 +0200 Subject: [Tutor] finding path to resource files in a GUI In-Reply-To: References: Message-ID: <4428f59cf3d9c036e3d75d5436508174@uni-mainz.de> On 9 Jun 2005, at 12:00, Michael Lange wrote: > Hi Christian, > > try > > self.cwd = os.path.abspath(sys.path[0]) > > sys.path[0] is the directory of your main program file, with > os.path.abspath() you can > get rid of the "../../" stuff at the beginning of the path if the > program is called from a link. > > I hope this helps It does! Actually I tried abspath, but didn't think of this very combination with sys.path ... Thanks a lot! Danke, Christian From albertito_g at hotmail.com Thu Jun 9 15:21:40 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 09 Jun 2005 13:21:40 +0000 Subject: [Tutor] Just a Python formatting question In-Reply-To: <7175b2cc050608094826afaf1c@mail.gmail.com> Message-ID: Kristiano Don't worry about it. I'm sure everyone passed over this before. The identation errors are errors in the tabulation of a line Let's take your code in example >number=78 >guess=0 > >while guess != number: > guess=input ("Guess a number:") > if guess > number: > print "Too High" > elif guess < number: > print "Too low" The last line has to belong to the elif clause, right? so if you are working with a single tab or 4 spaces (default identation in Python) that means that for every loop statement, try , functions, classes or any line that ends with ":", the next line has to be 4 spaces forward. And all the lines that belong to the statement also. It does not matter if is a nested sequence. Let me lighten you: for i in somelist: do_something do_something_else if x==y: inside the if clause all statements go with 4 spaces after the if line elif x>y: the same here You ended an identation when you went back the spaces and typed elif so you don't acumulate the identations, you just keep using 4 spaces after the line with the ":" so Python knows what's inside and what's outside I hope to be clear, and if you don't understand it (probably because of my English) you can always read in the tutorial or in the Python help Best Regards Alberto > > print "Just right" > > >I just can't get it to run and I get some indentation error. > > I'm pretty new to this so I'm sorry if this question(s) sound(s) >amateurish. Do help. > >Thanks. >-Kristiano Ang >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From davholla2002 at yahoo.co.uk Thu Jun 9 17:54:23 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 9 Jun 2005 16:54:23 +0100 (BST) Subject: [Tutor] keylogger In-Reply-To: Message-ID: <20050609155423.61738.qmail@web25404.mail.ukl.yahoo.com> You might want to write a keylogger because you have Children living in your house and you might want to protect them or yourself from their stupidity. (Ie downloading music illegally or giving out their address in a chat room, ideally the logger would sit there and send you an email if someone enters keys words like "music", "film", "your road name" etc. --------------------------------- Does your mail provider give you FREE antivirus protection? Get Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050609/ba62c6e1/attachment.htm From alan.gauld at freenet.co.uk Thu Jun 9 18:46:27 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 9 Jun 2005 17:46:27 +0100 Subject: [Tutor] finding path to resource files in a GUI application References: <6c58aba9519c4645e41d1c13abd8452e@uni-mainz.de> Message-ID: <019701c56d12$c8178270$c7a58851@xp> > The class Goals is in a file called Help.py, located in '/gui_lib/' as > seen from my main script. > > class Goals(wx.Frame): > def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition): > wx.Frame.__init__(self,parent, > -1,title,size,style=wx.DEFAULT_FRAME_STYLE) > self.frame = frame > self.cwd = os.getcwd() > > self.html = HtmlWindow(self,-1) > self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) > Any ideas what I could use instead of os.getcwd to construct a relative > path which will work even if I port the script to an other machine? The normal way to do this on Unix is to use an environment variable. MYAPPHOME or somesuch that points to te root directory for your data. An alternative is to use a resource file .mapprc that lives in each users home directory and can thus be found with ~/.myapprc Within that file you define any settings you need including folder locations. Usually a combination of the above techniques is used, and a default myapprc(no dot) held someplace like /etc/myapp used if no environment variable is set or no valid local user file exists. Alan G. From Goofball223 at wmconnect.com Thu Jun 9 18:50:52 2005 From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com) Date: Thu, 9 Jun 2005 12:50:52 EDT Subject: [Tutor] learning how to use python Message-ID: <204.353152d.2fd9cd6c@wmconnect.com> I am new to programming and this is the first language that I will be learning. I am trying to get the shell to print "hello world". I followed all of the steps to save it and then run the file to get it to print in the shell. the shell gives me an error and also says that personal firewall software is blocking the connection. does anyone have any suggestions on how i could fix this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050609/f1ae1ca7/attachment.htm From dsa at unilestemg.br Thu Jun 9 16:19:33 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Thu, 9 Jun 2005 14:19:33 +0000 Subject: [Tutor] learning how to use python In-Reply-To: <204.353152d.2fd9cd6c@wmconnect.com> References: <204.353152d.2fd9cd6c@wmconnect.com> Message-ID: <200506091419.33500.dsa@unilestemg.br> Hi ! This is the text idle says when you open it: **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** Is this your problem ? See ya ! Em Quinta 09 Junho 2005 16:50, Goofball223 at wmconnect.com escreveu: > I am new to programming and this is the first language that I will be > learning. I am trying to get the shell to print "hello world". I followed > all of the steps to save it and then run the file to get it to print in the > shell. the shell gives me an error and also says that personal firewall > software is blocking the connection. does anyone have any suggestions on > how i could fix this problem? -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From leec03273 at mac.com Thu Jun 9 19:55:28 2005 From: leec03273 at mac.com (Lee Cullens) Date: Thu, 9 Jun 2005 13:55:28 -0400 Subject: [Tutor] Newsreader list name? Message-ID: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> I'm switching over from email digests to a newsreader and I can't find a reference for this tutor list. For example, I have the lists comp.lang.python and comp.lang.python.announce setup, but can't find something like comp.lang.python.tutor? There must be others on this list using a newsreader and I would appreciate the list name used. Thanks, Lee C From sigurd at 12move.de Thu Jun 9 22:12:44 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Thu, 09 Jun 2005 22:12:44 +0200 Subject: [Tutor] Newsreader list name? In-Reply-To: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> (Lee Cullens's message of "Thu, 9 Jun 2005 13:55:28 -0400") References: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> Message-ID: On 9 Jun 2005, leec03273 at mac.com wrote: > I'm switching over from email digests to a newsreader and I can't > find a reference for this tutor list. > > For example, I have the lists comp.lang.python and > comp.lang.python.announce setup, but can't find something like > comp.lang.python.tutor? > > There must be others on this list using a newsreader and I would > appreciate the list name used. The server is: news.gmane.org and the group name is: gmane.comp.python.tutor In the WWW you can find the site of Gmane where all is explained. Gmane is great, since it hosts a lot of mailing lists. Karl -- Please do *not* send copies of replies to me. I read the list From cyresse at gmail.com Fri Jun 10 00:16:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri, 10 Jun 2005 10:16:34 +1200 Subject: [Tutor] keylogger In-Reply-To: <20050609155423.61738.qmail@web25404.mail.ukl.yahoo.com> References: <20050609155423.61738.qmail@web25404.mail.ukl.yahoo.com> Message-ID: That is true. For what it's worth, I wouldn't write a keylogger in Python. C, C++ or Assembly would be the best option. On 6/10/05, David Holland wrote: > > You might want to write a keylogger because you have Children living in > your house and you might want to protect them or yourself from their > stupidity. (Ie downloading music illegally or giving out their address in a > chat room, ideally the logger would sit there and send you an email if > someone enters keys words like "music", "film", "your road name" etc. > > ------------------------------ > Does your mail provider give you FREE antivirus protection? > *Get Yahoo! Mail* > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050610/908a7a08/attachment.html From leec03273 at mac.com Fri Jun 10 01:37:59 2005 From: leec03273 at mac.com (Lee Cullens) Date: Thu, 9 Jun 2005 19:37:59 -0400 Subject: [Tutor] Newsreader list name? In-Reply-To: References: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> Message-ID: Thanks for the reply Karl. In the last couple days I have carefully read through the Gmane site several times. I'm on OS X 10.4.1 and downloaded Hogwasher to try. Using my ISPs news server I found the two lists I mentioned, but I can't get anything nntp://news.gmane.org alone or in combination with a group (e.g. + gmane.comp.python.tutor), or alone (server) with the group in the subscription window to work. Are you using Gmane successfully? Thanks Lee C On Jun 9, 2005, at 4:12 PM, Karl Pfl?sterer wrote: > On 9 Jun 2005, leec03273 at mac.com wrote: > > >> I'm switching over from email digests to a newsreader and I can't >> find a reference for this tutor list. >> >> For example, I have the lists comp.lang.python and >> comp.lang.python.announce setup, but can't find something like >> comp.lang.python.tutor? >> >> There must be others on this list using a newsreader and I would >> appreciate the list name used. >> > > The server is: news.gmane.org > and the group name is: gmane.comp.python.tutor > > In the WWW you can find the site of Gmane where all is explained. > Gmane > is great, since it hosts a lot of mailing lists. > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ryanpublic at foxracing.com Fri Jun 10 01:49:14 2005 From: ryanpublic at foxracing.com (Ryan Parrish) Date: Thu, 9 Jun 2005 16:49:14 -0700 Subject: [Tutor] Dynamically calling a class Message-ID: example - list_of_classes = ['A', 'B', B', 'A'] class A: doingsomething class B: doing something for x in list_of_classes: x() my problem is that i get 'TypeError: 'str' object is not callable', of which i understand what the error is saying, i just want to know how to dynamically call the class. i have been trying to search google, but im not exactly sure what i should be searching for :-/ I'm not really asking for someone to hold my hand through it, just some pointers on where i need to start looking. thanks. From jfouhy at paradise.net.nz Fri Jun 10 02:12:41 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 10 Jun 2005 12:12:41 +1200 (NZST) Subject: [Tutor] Dynamically calling a class In-Reply-To: References: Message-ID: <1118362361.42a8daf979617@www.paradise.net.nz> Quoting Ryan Parrish : > example - > > list_of_classes = ['A', 'B', B', 'A'] > > class A: > doingsomething > class B: > doing something > > for x in list_of_classes: > x() > > my problem is that i get 'TypeError: 'str' object is not callable', of > which i understand what the error is saying, i just want to know how to > dynamically call the class. Just put the class object in the list! >>> class A: ... pass ... >>> class B: ... pass ... >>> class C: ... pass ... >>> classes = [A, B, C] >>> for cls in classes: ... x = cls() ... print x.__class__ ... __main__.A __main__.B __main__.C You can do some black magic to go from the string 'A' to the class A (eg, use eval()), but it's generally better to avoid that if you can. -- John. From as.20.schellenberg at spamgourmet.com Fri Jun 10 02:16:59 2005 From: as.20.schellenberg at spamgourmet.com (as.20.schellenberg@spamgourmet.com) Date: Thu, 9 Jun 2005 18:16:59 -0600 Subject: [Tutor] Can't figure out syntax error Message-ID: <13282db4041afe729e76aec754b46589@gmail.com> Hi there, I'm in the process of learning Python, and need some help deciphering the reason why the following code doesn't work: import sys, string def dec2bin(decNum): # validate the input as a postive integer number for char in decNum: if str(char).isdigit() == False: print "Not a postive integer number given when calling the dec2bin function." sys.exit() bin = "" # initialize the new binary result (as a string) num = int(decNum) if num == 0: # take care of the zero case bin = "0" while int(num) != 0: # the rest of the cases nextBin = int(num) % 2 # check if this column should be a 0 or 1 bin = str(nextBin) + bin # add the result to the front of the result string int(num) = int(num) / 2 # this is integer division, so we truncate the decimal part return bin # return the binary result # testing x = "13" print dec2bin(x) I get the following error: > File "convert.py", line 42 > int(num) = int(num) / 2 # this is integer division, so > we truncate the decimal part > SyntaxError: can't assign to function call Any help anyone can provide would be greatly appreciated. Dan From zamb at saudi.net.sa Fri Jun 10 03:32:19 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Fri, 10 Jun 2005 04:32:19 +0300 Subject: [Tutor] Can't figure out syntax error In-Reply-To: <13282db4041afe729e76aec754b46589@gmail.com> References: <13282db4041afe729e76aec754b46589@gmail.com> Message-ID: <1118367139.11608.5.camel@localhost.localdomain> On Thu, 2005-06-09 at 18:16 -0600, as.20.schellenberg at spamgourmet.com wrote: > Hi there, > > I'm in the process of learning Python, and need some help deciphering > the reason why the following code doesn't work: > int(num) = int(num) / 2 # this is integer division, so we truncate the decimal part Here's your problem! "int(num)" will try to interpret "num" as an integer and return that (if possible) as an "int" object, but you're trying to assign it to the value of "int(num)/2" which doesn't make sense! What you want, probably, is: num = int(num) / 2 Here, "num" will be assigned the value (object actually) of the resulting of "int(num)/2" which will be an object of type "int". Ziyad. From kent37 at tds.net Fri Jun 10 04:29:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Jun 2005 22:29:55 -0400 Subject: [Tutor] Can't figure out syntax error In-Reply-To: <13282db4041afe729e76aec754b46589@gmail.com> References: <13282db4041afe729e76aec754b46589@gmail.com> Message-ID: <42A8FB23.20402@tds.net> as.20.schellenberg at spamgourmet.com wrote: > Hi there, > > I'm in the process of learning Python, and need some help deciphering > the reason why the following code doesn't work: Ziyad has answered your immediate question but I have a few more comments. > > import sys, string > > def dec2bin(decNum): > # validate the input as a postive integer number > for char in decNum: > if str(char).isdigit() == False: char is already a string so you don't have to call str(char), just use char directly: if char.isdigit() == False: but you don't have to compare to False, either, just say if not char.isdigit(): in fact you can call isdigit() on the whole string, it will test if all the characters are digits. So instead of the loop just write if not decNum.isdigit(): > print "Not a postive integer number given when calling the dec2bin > function." > sys.exit() > > bin = "" # initialize the new binary result (as a string) > num = int(decNum) OK, num is an integer now. > > if num == 0: # take care of the zero case > bin = "0" > > while int(num) != 0: # the rest of the cases > nextBin = int(num) % 2 # check if this column should be a 0 or 1 > bin = str(nextBin) + bin # add the result to the front of the result > string > int(num) = int(num) / 2 # this is integer division, so we truncate > the decimal part You don't have to keep saying int(num), num is already an int and dividing by 2 gives a new int. You can just use num directly. > > return bin # return the binary result > > # testing > x = "13" > print dec2bin(x) Kent From chuck at freshsources.com Fri Jun 10 04:59:36 2005 From: chuck at freshsources.com (Chuck Allison) Date: Thu, 9 Jun 2005 20:59:36 -0600 Subject: [Tutor] Word COM interface In-Reply-To: References: Message-ID: <1189398617.20050609205936@freshsources.com> Hello, Does anyone know how to get the Microsoft Word 11.0 Object library working in ActiveState Python 2.4.1? When I go into PythonWin and try to load it under makePy, I get the following error: >>> Generating to C:\Python24\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x3.py Failed to execute command: from win32com.client import makepy;makepy.main() Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\toolmenu.py", line 103, in HandleToolCommand exec "%s\n" % pyCmd File "", line 1, in ? File "C:\Python24\Lib\site-packages\win32com\client\makepy.py", line 362, in main GenerateFromTypeLibSpec(arg, f, verboseLevel = verboseLevel, bForDemand = bForDemand, bBuildHidden = hiddenSpec) File "C:\Python24\Lib\site-packages\win32com\client\makepy.py", line 273, in GenerateFromTypeLibSpec gencache.AddModuleToCache(info.clsid, info.lcid, info.major, info.minor) File "C:\Python24\Lib\site-packages\win32com\client\gencache.py", line 550, in AddModuleToCache mod = _GetModule(fname) File "C:\Python24\Lib\site-packages\win32com\client\gencache.py", line 629, in _GetModule mod = __import__(mod_name) File "C:\Python24\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x3\__init__.py", line 2831 '{00020960-0000-0000-C000-000000000046}' : 'Pane', '{00020961-0000-0000-C000-000000000046}' : 'Windows', ^ SyntaxError: invalid syntax Any clue? -- Best regards, Chuck From schellenberg at gmail.com Fri Jun 10 03:42:59 2005 From: schellenberg at gmail.com (Dan Schellenberg) Date: Thu, 9 Jun 2005 19:42:59 -0600 Subject: [Tutor] Can't figure out syntax error In-Reply-To: <1118367139.11608.5.camel@localhost.localdomain> References: <13282db4041afe729e76aec754b46589@gmail.com> <1118367139.11608.5.camel@localhost.localdomain> Message-ID: <04a724af15d58ed075373f7a1e733cc8@gmail.com> Phew -- thanks, Ziyad. That did the trick all right. In my frustration to figure out the problem, I just began explicitly type-casting as many variables as I could, and missed the fact that I had done the same to this as well. Thanks again, Dan On 9-Jun-05, at 7:32 PM, ZIYAD A. M. AL-BATLY - zamb at saudi.net.sa wrote: > On Thu, 2005-06-09 at 18:16 -0600, as.20.schellenberg at spamgourmet.com > wrote: >> Hi there, >> >> I'm in the process of learning Python, and need some help deciphering >> the reason why the following code doesn't work: > >> int(num) = int(num) / 2 # this is integer division, so we >> truncate the decimal part > Here's your problem! "int(num)" will try to interpret "num" as an > integer and return that (if possible) as an "int" object, but you're > trying to assign it to the value of "int(num)/2" which doesn't make > sense! > > What you want, probably, is: > num = int(num) / 2 > > Here, "num" will be assigned the value (object actually) of the > resulting of "int(num)/2" which will be an object of type "int". > > Ziyad. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Fri Jun 10 05:38:26 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 10 Jun 2005 04:38:26 +0100 Subject: [Tutor] Calling a function In-Reply-To: <20050608234559.33fc32d9.reederk@comcast.net> References: <20050608234559.33fc32d9.reederk@comcast.net> Message-ID: On Jun 9, 2005, at 07:45, Kevin Reeder wrote: > I'm having trouble with this code which is meant to run a time > comparison between two similar functions. The first module is > makezeros.py > > def lots_of_appends(): > zeros = [] > for i in range(10000): > zeros.append(0) > > def one_multiply(): > zeros = [0] * 10000 Note that your functions don't do the same thing. The first one builds the list properly, but the second builds a list out of references to the same object -- that is, the 10000 zeros in your resulting second list are actually the same object. As long as you're working with immutable types (numbers, strings) you won't notice there's a problem, but consider the following: >>> a = [[0]] * 10 >>> a[0].append(1) >>> a [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [0] is a list -- therefore, a mutable object: you can apply modifications to it. So, the list is actually a list of ten references to the same object -- [0]. When you run one of its methods that modifies it, since all references point to it, all members of the list seem to be modified as well -- but they're actually one single object that's present 10 times in the list. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Fri Jun 10 09:31:34 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 10 Jun 2005 08:31:34 +0100 Subject: [Tutor] Just a Python formatting question References: Message-ID: <01d201c56d8e$6df67860$c7a58851@xp> > And all the lines that belong to the statement also. It does not matter if > is a nested sequence. Let me lighten you: > > for i in somelist: > do_something > do_something_else > if x==y: > inside the if clause > all statements go > with 4 spaces after the if line > elif x>y: > the same here While this is good advice Python doesn't mind if the elif uses different indentation to the if. Indeed each elif block could be different, so long as its consistent within the block. But that could lead to very wierd code: if something: do a thing and this elif another : do another thing and that elif what: something here and here else: pass Now visually that's a mess but Python won't complain because each block is consistent. So to please Python be consistent inside a block, but to make it readable be consistent across all blocks! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jun 10 09:36:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 10 Jun 2005 08:36:59 +0100 Subject: [Tutor] learning how to use python References: <204.353152d.2fd9cd6c@wmconnect.com> Message-ID: <01ec01c56d8f$2fc88af0$c7a58851@xp> Hi and welcome. > I am new to programming and this is the first language that I will be > learning. I am trying to get the shell to print "hello world". > I followed all of the steps to save it and then run the file Which tutorial are you following? > to get it to print in the shell. the shell gives me an error and > also says that personal firewall software is blocking the connection. That sounds like a known problem with the latest version of IDLE. I haven't upgraded to 2.4 yet so hopefully someone else can point you at the solution. But in general when you post a message here it's worth including the code - if it's not hundreds of lines long! And also a cut n paste of the actual error message because, although they may not look friendly initially, Python errors are actually very informative once you know how to read them! Take care, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jun 10 10:17:04 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 10 Jun 2005 09:17:04 +0100 Subject: [Tutor] Newsreader list name? References: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> Message-ID: <025a01c56d94$c9291f70$c7a58851@xp> > I'm switching over from email digests to a newsreader and I can't > find a reference for this tutor list. > > For example, I have the lists comp.lang.python and > comp.lang.python.announce setup, but can't find something like > comp.lang.python.tutor? > > There must be others on this list using a newsreader and I would > appreciate the list name used. The trick is that you need to set up a new news account not the standard feed your ISP provides. The news server required is news.gmane.org And the news group you need to look for is comp.python.tutor HTH, Alan G. From alan.gauld at freenet.co.uk Fri Jun 10 10:16:36 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 10 Jun 2005 09:16:36 +0100 Subject: [Tutor] Can't figure out syntax error References: <13282db4041afe729e76aec754b46589@gmail.com><1118367139.11608.5.camel@localhost.localdomain> <04a724af15d58ed075373f7a1e733cc8@gmail.com> Message-ID: <025501c56d94$b9319930$c7a58851@xp> > frustration to figure out the problem, I just began explicitly > type-casting as many variables as I could, and missed the fact that I Must be something about the mornings but I seem to be pickier then... When you say type-casting that is a C term used to describe a horrible operation that fools the C compiler into treating an arbitrary block of bits in memory as some other type from that by which it was defined. It doesn't actually change the bits at all. What Python provides is type conversion where it actually tries to convert the data into a new value. Very different things. This is best illustrated by a character. char c = '5'; // ascii value 53 int n; n = (int)c; // type cast makes n hold 53 n = atoi(c) // type convert makes n hold 5 Sorry for splitting hairs but clearing the terminology might help someone... Alan G. From alan.gauld at freenet.co.uk Fri Jun 10 10:19:18 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 10 Jun 2005 09:19:18 +0100 Subject: [Tutor] Newsreader list name? References: <477C2D57-241C-4E28-B3C8-AEBA2622F564@mac.com> Message-ID: <026901c56d95$19534750$c7a58851@xp> > I'm on OS X 10.4.1 and downloaded Hogwasher to try. Using my ISPs > news server I found the two lists I mentioned, but I can't get > anything nntp://news.gmane.org alone or in combination with a group THe point is that you must add news.gname.org to your list of news servers. It is a new news service not available on your ISP news server. It is not just a new group. Alan G. From kabads at gmail.com Fri Jun 10 12:12:08 2005 From: kabads at gmail.com (Adam Cripps) Date: Fri, 10 Jun 2005 11:12:08 +0100 Subject: [Tutor] New pet project - stripping down html content. Message-ID: I've been working through some of the early python challenges [1] and feel enthused to scratch a current itch. However, I want to sound out my idea for the itch before I start coding to get a perspective on the direction I should take. I've recently bought a media player that also displays .txt files. My itch is to write a script that periodically goes to a news website and 'scrapes' all the relevant information from this. One of my favourites would the Guardian [2]. The Guardian provide RSS feeds and so I would like to grab an RSS list and then proceed to download the content for those 10 or so items. However, here's where the direction is needed. Obviously, my preferred delivery is .txt without all the tags. Is there a quick and easy way to strip out html tags and remain with just the content? And, to be even more pickier, would it be possible to strip out navigation content and just remain with the bare bones of the story? Any pointers for particular libraries I should be looking at would be very helpful. I've already had a quick play with feedparser [3], which was intuitive and easy to program with. What about stripping the html? TIA Adam [1] http://www.pythonchallenge.com [2] http://www.guardian.co.uk [3] http://feedparser.org/ -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Fri Jun 10 14:15:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Jun 2005 08:15:04 -0400 Subject: [Tutor] New pet project - stripping down html content. In-Reply-To: References: Message-ID: <42A98448.9000609@tds.net> Adam Cripps wrote: > Is there a quick and easy way to strip out html tags and remain with > just the content? And, to be even more pickier, would it be possible > to strip out navigation content and just remain with the bare bones of > the story? If you search comp.lang.python for 'strip html' you will find much discussion of this. http://groups-beta.google.com/group/comp.lang.python/search?hl=en&group=comp.lang.python&q=strip+html&qt_g=1&searchnow=Search+this+group Kent From typetext at gmail.com Fri Jun 10 16:45:50 2005 From: typetext at gmail.com (typetext) Date: Fri, 10 Jun 2005 07:45:50 -0700 Subject: [Tutor] Running range scripts in IDE Message-ID: <9414809805061007453d6355a5@mail.gmail.com> I am using I. Langingham's Teach yourself Python in 24 hours, and up to chapter 4 I had no problem. I have installed the IDE , and as far as I know, all the other programs associated with Python, and had been batting along with no problem, using simple scripts such as "hello world" in notepad or notetab (another text processor) until I hit the range function. Then I tried to save and run a script with the following content. range(10) which returns the expected output when I type the command directly on the prompt line of IDE, but just returns either nothing or the words range(10) when I use the run command and try to do it as script, saved as r10.py or a number of other names ending with the extention .py. I realize this might be an elementary question, but I am stuck. What am I doing wrong? I am using Windows XP. Michael Riggs Seattle From ajikoe at gmail.com Fri Jun 10 17:00:59 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 10 Jun 2005 17:00:59 +0200 Subject: [Tutor] Running range scripts in IDE In-Reply-To: <9414809805061007453d6355a5@mail.gmail.com> References: <9414809805061007453d6355a5@mail.gmail.com> Message-ID: On 6/10/05, typetext wrote: > I am using I. Langingham's Teach yourself Python in 24 hours, and up > to chapter 4 I had no problem. I have installed the IDE , and as far > as I know, all the other programs associated with Python, and had been > batting along with no problem, using simple scripts such as "hello > world" in notepad or notetab (another text processor) until I hit the > range function. What IDE do you use ? Then I tried to save and run a script with the > following content. > > range(10) > > which returns the expected output when I type the command directly on > the prompt line of IDE, but just returns either nothing or the words > range(10) Can you show us what your input and output. Don't forget to type print to show something in the console. print range(10) # will give [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] good luck pujo when I use the run command and try to do it as script, saved > as r10.py or a number of other names ending with the extention .py. I > realize this might be an elementary question, but I am stuck. What am > I doing wrong? I am using Windows XP. > > Michael Riggs > Seattle > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Jun 10 17:20:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Jun 2005 11:20:34 -0400 Subject: [Tutor] Running range scripts in IDE In-Reply-To: <9414809805061007453d6355a5@mail.gmail.com> References: <9414809805061007453d6355a5@mail.gmail.com> Message-ID: <42A9AFC2.9090002@tds.net> typetext wrote: > I am using I. Langingham's Teach yourself Python in 24 hours, and up > to chapter 4 I had no problem. I have installed the IDE , and as far > as I know, all the other programs associated with Python, and had been > batting along with no problem, using simple scripts such as "hello > world" in notepad or notetab (another text processor) until I hit the > range function. Then I tried to save and run a script with the > following content. > > range(10) > > which returns the expected output when I type the command directly on > the prompt line of IDE, but just returns either nothing or the words > range(10) when I use the run command and try to do it as script, saved > as r10.py or a number of other names ending with the extention .py. I > realize this might be an elementary question, but I am stuck. What am > I doing wrong? I am using Windows XP. When you type an expression to the interactive interpreter, it evaluates the expression and prints the result, so you get >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] This is called the read-eval-print loop or REPL; it is a feature of the interpreter. In a program, you have to make the print explicit: print range(10) Kent From typetext at gmail.com Fri Jun 10 18:37:01 2005 From: typetext at gmail.com (typetext) Date: Fri, 10 Jun 2005 09:37:01 -0700 Subject: [Tutor] Running range scripts in IDE In-Reply-To: <42A9AFC2.9090002@tds.net> References: <9414809805061007453d6355a5@mail.gmail.com> <42A9AFC2.9090002@tds.net> Message-ID: <9414809805061009376ec6aeed@mail.gmail.com> Thank you all. Print range(10) completely solved this beginner problem. On 6/10/05, Kent Johnson wrote: > typetext wrote: > > I am using I. Langingham's Teach yourself Python in 24 hours, and up > > to chapter 4 I had no problem. I have installed the IDE , and as far > > as I know, all the other programs associated with Python, and had been > > batting along with no problem, using simple scripts such as "hello > > world" in notepad or notetab (another text processor) until I hit the > > range function. Then I tried to save and run a script with the > > following content. > > > > range(10) > > > > which returns the expected output when I type the command directly on > > the prompt line of IDE, but just returns either nothing or the words > > range(10) when I use the run command and try to do it as script, saved > > as r10.py or a number of other names ending with the extention .py. I > > realize this might be an elementary question, but I am stuck. What am > > I doing wrong? I am using Windows XP. > > When you type an expression to the interactive interpreter, it evaluates the expression and prints the result, so you get > >>> range(10) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > This is called the read-eval-print loop or REPL; it is a feature of the interpreter. > > In a program, you have to make the print explicit: > print range(10) > > Kent > > From carroll at tjc.com Fri Jun 10 21:59:08 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Jun 2005 12:59:08 -0700 (PDT) Subject: [Tutor] Newsreader list name? In-Reply-To: <026901c56d95$19534750$c7a58851@xp> Message-ID: > > I'm on OS X 10.4.1 and downloaded Hogwasher to try. Using my ISPs > > news server I found the two lists I mentioned, but I can't get > > anything nntp://news.gmane.org alone or in combination with a group Try news://news.gmane.org , if your reader requires specifying the protocol. From ismaelgf at adinet.com.uy Sat Jun 11 05:56:51 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat, 11 Jun 2005 00:56:51 -0300 Subject: [Tutor] Web browser Message-ID: <42AA6103.9010901@adinet.com.uy> Hello. I've been looking around for a web browser either written in python, or with python bindings. What I need to do is load a web-page, enter a password-protected site and follow certain links, it needs to have frames and follow the refresh meta. I'm running winxp, python 2.4 At first I thought about using a python web browser, but none I could find had frames support. The most promising ones were quite old too. And one that was completly written in Python used and old version and just kept crashing in python 2.4. Then, I thought about using some browser with bindings. I've looked all over and found about nothing. Mozilla and its xpcom just seems quite hard and I'm not sure if that does the job I want. I tried finding COM bindings in other browsers, but I coudn't understand them and make them work... Any suggestion would be greatly appreciated. Ismael From list at ohtogo.com Sat Jun 11 06:48:39 2005 From: list at ohtogo.com (Trey Beck) Date: Fri, 10 Jun 2005 22:48:39 -0600 Subject: [Tutor] Web browser In-Reply-To: <42AA6103.9010901@adinet.com.uy> References: <42AA6103.9010901@adinet.com.uy> Message-ID: Why do you need to use a web browser rather than doing this programmatically? On Jun 10, 2005, at 9:56 PM, Ismael Garrido wrote: > Hello. > > I've been looking around for a web browser either written in > python, or > with python bindings. > What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the > refresh > meta. I'm running winxp, python 2.4 > > At first I thought about using a python web browser, but none I could > find had frames support. The most promising ones were quite old > too. And > one that was completly written in Python used and old version and just > kept crashing in python 2.4. > Then, I thought about using some browser with bindings. I've looked > all > over and found about nothing. Mozilla and its xpcom just seems quite > hard and I'm not sure if that does the job I want. I tried finding COM > bindings in other browsers, but I coudn't understand them and make > them > work... > > Any suggestion would be greatly appreciated. > Ismael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > --- Trey Beck, Director of Covert Operations Ohtogo My hCard: http://www.ohtogo.com/hcard.htm AIM: samuelbeckt From webdev at matheteuo.org Sat Jun 11 09:52:13 2005 From: webdev at matheteuo.org (Don Parris) Date: Sat, 11 Jun 2005 03:52:13 -0400 Subject: [Tutor] Counting MySQL Fields Message-ID: <20050611035213.1aa9d406@luke.matheteuo.rel> Greetings, I've dabbled in programming/scripting a little, but never really seem to get the hang of it. I thought I'd try out Python for a front-end to my SQL database project. I've worked through the tutorial, and a few others to some extent. At the moment, I'm really just tinkering, but have succesfully connected Python to MySQL and performed a simple query. I'd like to use the result.numfields() function to count the fields on a given table, but apparently don't quite grasp how to implement it. Below is my lame attempt. I searched the comp.lang.python group via Google, but didn't find any relevant info. The MySQLdb User Guide didn't give an example, nor does the module source. My attempt here was to retrieve a single row, and count the fields. That obviously didn't work. If there's a good example of this, I'd appreciate a pointer. If you can explain this operation a bit, that would be useful also. I'm running SUSE Linux 9.2 Pro on an AMD box. --------- My Test Script ------------ sql = "SELECT * FROM person order by lst_name" Cursor.execute(sql) # Fetch all results from the cursor into a sequence and close the connection result = Cursor.fetchone() Con.close() # Count the fields result.num_fields() ------ Relevant info from the resulting Traceback --------- result.num_fields() AttributeError: 'Tuple' object has no attribute 'num_fields' Using variations of this gives errors to the effect that "result" or num_fields" is "undefined". Thanks, Don -- DC Parris GNU Evangelist http://matheteuo.org/ http://lulu.com/dcparris Read the highly rated, widely recommended "Penguin in the Pew"! From alan.gauld at freenet.co.uk Sat Jun 11 10:01:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 11 Jun 2005 09:01:38 +0100 Subject: [Tutor] Web browser References: <42AA6103.9010901@adinet.com.uy> Message-ID: <042201c56e5b$cbd2b430$c7a58851@xp> > What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the refresh > meta. I'm running winxp, python 2.4 Do you need to do this interactively in a browser? It sounds like scripting the process using urlib might be a better solution? > Then, I thought about using some browser with bindings. I've looked all > over and found about nothing. Mozilla and its xpcom just seems quite > hard and I'm not sure if that does the job I want. I tried finding COM > bindings in other browsers, but I coudn't understand them and make them > work... You can use COM to script IE but navigating the mysteries of COM is not easy, especoially if you haven't done it before. I suggest you look at urlib before going any further, but if you really need to have a real browser open IE may be your best bet. Alan G From alan.gauld at freenet.co.uk Sat Jun 11 10:07:58 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 11 Jun 2005 09:07:58 +0100 Subject: [Tutor] Counting MySQL Fields References: <20050611035213.1aa9d406@luke.matheteuo.rel> Message-ID: <042901c56e5c$ae71b020$c7a58851@xp> > I'd like to use the result.numfields() function to count the fields on a > given table, but apparently don't quite grasp how to implement it. Below is > my lame attempt. OK, I've never use the numfields function so have no idea how it works nor why I'd want to use it but... > sql = "SELECT * FROM person order by lst_name" Oh OK, I see why - you are using * instead of named fields... > Cursor.execute(sql) > > # Fetch all results from the cursor into a sequence and close the connection > result = Cursor.fetchone() > Con.close() > > # Count the fields > result.num_fields() First of all this seems odd since, although you call the function, you aren't storing the result anywhere, even if it worked! > ------ Relevant info from the resulting Traceback --------- > result.num_fields() > AttributeError: 'Tuple' object has no attribute 'num_fields' If results is a tuple then presumably the number of fields is just the len() of the tuple? HTH, Alan G. From kent37 at tds.net Sat Jun 11 12:59:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Jun 2005 06:59:32 -0400 Subject: [Tutor] Web browser In-Reply-To: <42AA6103.9010901@adinet.com.uy> References: <42AA6103.9010901@adinet.com.uy> Message-ID: <42AAC414.5090400@tds.net> Ismael Garrido wrote: > Hello. > > I've been looking around for a web browser either written in python, or > with python bindings. > What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the refresh > meta. I'm running winxp, python 2.4 take a look at Pamie: http://pamie.sourceforge.net Kent From kent37 at tds.net Sat Jun 11 13:04:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Jun 2005 07:04:39 -0400 Subject: [Tutor] Counting MySQL Fields In-Reply-To: <20050611035213.1aa9d406@luke.matheteuo.rel> References: <20050611035213.1aa9d406@luke.matheteuo.rel> Message-ID: <42AAC547.30508@tds.net> Don Parris wrote: > I'd like to use the result.numfields() function to count the fields on a > given table, but apparently don't quite grasp how to implement it. Below is > my lame attempt. I searched the comp.lang.python group via Google, but > didn't find any relevant info. The MySQLdb User Guide didn't give an > example, nor does the module source. > > My attempt here was to retrieve a single row, and count the fields. That > obviously didn't work. If there's a good example of this, I'd appreciate a > pointer. If you can explain this operation a bit, that would be useful > also. I'm running SUSE Linux 9.2 Pro on an AMD box. >From a look at the DB-API docs I would think len(result) would give you what you want, or len(list(cursor.description)) Kent From c.m.booth at durham.ac.uk Sat Jun 11 13:53:00 2005 From: c.m.booth at durham.ac.uk (Craig Booth) Date: Sat, 11 Jun 2005 12:53:00 +0100 (BST) Subject: [Tutor] Web browser In-Reply-To: <42AA6103.9010901@adinet.com.uy> References: <42AA6103.9010901@adinet.com.uy> Message-ID: Hi, As was recommended to me in a previous thread if you're on a Windows machine with IE installed then PAMIE (http://www.pamie.sourceforge.net) can simplify using the IE COM and does nearly everything you need. Pamie doesn't support frames correctly yet, but it is very easy to hack in support as and where it is needed. --Craig On Sat, 11 Jun 2005, Ismael Garrido wrote: > Hello. > > I've been looking around for a web browser either written in python, or > with python bindings. > What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the refresh > meta. I'm running winxp, python 2.4 > > At first I thought about using a python web browser, but none I could > find had frames support. The most promising ones were quite old too. And > one that was completly written in Python used and old version and just > kept crashing in python 2.4. > Then, I thought about using some browser with bindings. I've looked all > over and found about nothing. Mozilla and its xpcom just seems quite > hard and I'm not sure if that does the job I want. I tried finding COM > bindings in other browsers, but I coudn't understand them and make them > work... > > Any suggestion would be greatly appreciated. > Ismael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sat Jun 11 16:00:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 12 Jun 2005 02:00:07 +1200 Subject: [Tutor] Web browser In-Reply-To: References: <42AA6103.9010901@adinet.com.uy> Message-ID: Ai, for the frames you just call the win32 methods directly. Easy enough, just got to deal with the DOM! On 6/11/05, Craig Booth wrote: > > Hi, > > As was recommended to me in a previous thread if you're on a > Windows machine with IE installed then PAMIE > (http://www.pamie.sourceforge.net) can simplify using the IE COM and does > nearly everything you need. > > Pamie doesn't support frames correctly yet, but it is very easy to hack > in support as and where it is needed. > > > --Craig > > On Sat, 11 Jun 2005, Ismael Garrido wrote: > > > Hello. > > > > I've been looking around for a web browser either written in python, or > > with python bindings. > > What I need to do is load a web-page, enter a password-protected site > > and follow certain links, it needs to have frames and follow the refresh > > meta. I'm running winxp, python 2.4 > > > > At first I thought about using a python web browser, but none I could > > find had frames support. The most promising ones were quite old too. And > > one that was completly written in Python used and old version and just > > kept crashing in python 2.4. > > Then, I thought about using some browser with bindings. I've looked all > > over and found about nothing. Mozilla and its xpcom just seems quite > > hard and I'm not sure if that does the job I want. I tried finding COM > > bindings in other browsers, but I coudn't understand them and make them > > work... > > > > Any suggestion would be greatly appreciated. > > Ismael > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050612/716f06a1/attachment.html From nequeo at gmail.com Sun Jun 12 01:42:27 2005 From: nequeo at gmail.com (Simon Gerber) Date: Sun, 12 Jun 2005 09:42:27 +1000 Subject: [Tutor] "Print" behaviour inside a loop? Message-ID: <42AB76E3.90107@gmail.com> Hullo, Firstly, thanks to everyone who helped me find my own IP address. That was a big help. That bit is working now, and working very nicely. I am now stuck on something purely aesthetic - printing a few dots across the screen to provide a bit of feedback while the VPN tunnel is being established. def vpn_connect(choice): import time ip_addr = "" tries = 0 retries = 10 print "Connecting to %s" % (choice), os.system("pon %s" % (choice)) while ip_addr == "" and tries < retries: print "...", # This is the line causing problems time.sleep(0.5) ip_addr = get_addr() if ip_addr != '': #create the route! pass else: tries += 1 sys.exit() It works. The problem is, nothing is displayed on screen until after the connection occurs - at which point we see: "Connecting to Prodigi ... ... ... ... ... ... ... " If I remove the comma at the end of the marked line, the ellipses print every .5 seconds as desired, except they print down the screen of course! After googling around a little, I found a post that seemed to say Python won't draw the results of 'print' statements until it hits a newline. I tried using sys.stout.write('...'), but had the same problem there, too. I've also found a few progress bar classes around the web, but I not exactly want a progress bar. I just want to print '...' every few seconds until connected. Any hints? I looked up the python reference manual, but couldn't find any way to force print statements to draw. Should I be looking into threads, perhaps? Regards, From maxnoel_fr at yahoo.fr Sun Jun 12 01:50:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun, 12 Jun 2005 00:50:40 +0100 Subject: [Tutor] "Print" behaviour inside a loop? In-Reply-To: <42AB76E3.90107@gmail.com> References: <42AB76E3.90107@gmail.com> Message-ID: <2903461D-ED30-4830-9785-CE447A9F8700@yahoo.fr> On Jun 12, 2005, at 00:42, Simon Gerber wrote: > Any hints? I looked up the python reference manual, but couldn't find > any way to force print statements to draw. Should I be looking into > threads, perhaps? I/O in Python is buffered -- that is, it uses RAM whenever possible to delay the actual reading/writing operations, which in turn speeds them up. For example, when you read a character from a file, a larger part of the file is stored in a RAM buffer so as to speed up subsequent calls. In the same way, whenever you write to stdout (or to a file), everything is stored in a buffer until a newline is reached or the buffer is manually flushed. The latter is what you're looking for, it's done by calling the file object's (in your case, stdout -- remember, on UNIX everything is a file) flush method. Here's a small example: #!/usr/bin/env python import time, sys for i in xrange(20): sys.stdout.write(".") sys.stdout.flush() time.sleep(0.2) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Sun Jun 12 03:58:04 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 11 Jun 2005 18:58:04 -0700 (PDT) Subject: [Tutor] Web browser In-Reply-To: <42AA6103.9010901@adinet.com.uy> Message-ID: On Sat, 11 Jun 2005, Ismael Garrido wrote: > I've been looking around for a web browser either written in python, or > with python bindings. MozPython? http://www.thomas-schilz.de/MozPython/README.html > What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the refresh > meta. I'm running winxp, python 2.4 Why not write a scraper, using something like Beautiful Soup? From webdev at matheteuo.org Sun Jun 12 05:21:13 2005 From: webdev at matheteuo.org (Don Parris) Date: Sat, 11 Jun 2005 23:21:13 -0400 Subject: [Tutor] Counting MySQL Fields In-Reply-To: <043d01c56ed3$423a02a0$c7a58851@xp> References: <20050611035213.1aa9d406@luke.matheteuo.rel> <042901c56e5c$ae71b020$c7a58851@xp> <20050611170954.117f06e2@luke.matheteuo.rel> <043d01c56ed3$423a02a0$c7a58851@xp> Message-ID: <20050611232113.7d273c74@luke.matheteuo.rel> Oops! Didn't mean to reply off-list. On Sat, 11 Jun 2005 23:16:47 +0100 "Alan G" wrote: > HI Don, > > > > > result = Cursor.fetchone() > > > > Con.close() > > > > > > > > # Count the fields > > > > result.num_fields() > > > Should I have done something more like this? > > a = result > > the DB code > > a.num_fields() > > No I'd have expected something like: > > n = result.num_fields() > > Although taking a guess I susprect num_fields may be a method > of the cursor object? After all it knows how many felds each row > has... > > So it may be you need: > > n = Cursor.num_fields() > > But thats pure guesswork based on how I would have designed it! > I'm gonna be getting into some Python DB programming soon so I'll > need to find out then I guess. > > Alan G. > -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From chinook.nr at tds.net Sun Jun 12 07:16:00 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 12 Jun 2005 01:16:00 -0400 Subject: [Tutor] "Print" behaviour inside a loop? References: <42AB76E3.90107@gmail.com> Message-ID: <0001HW.BED13D500013F213F0407550@news.gmane.org> On Sat, 11 Jun 2005 19:42:27 -0400, Simon Gerber wrote (in article <42AB76E3.90107 at gmail.com>): > Hullo, > > Firstly, thanks to everyone who helped me find my own IP address. That > was a big help. That bit is working now, and working very nicely. I am > now stuck on something purely aesthetic - printing a few dots across the > screen to provide a bit of feedback while the VPN tunnel is being > established. > > def vpn_connect(choice): > import time > ip_addr = "" > tries = 0 > retries = 10 > print "Connecting to %s" % (choice), > os.system("pon %s" % (choice)) > while ip_addr == "" and tries < retries: > print "...", # This is the line causing problems > time.sleep(0.5) > ip_addr = get_addr() > if ip_addr != '': > #create the route! > pass > else: > tries += 1 > sys.exit() > > It works. The problem is, nothing is displayed on screen until after the > connection occurs - at which point we see: > > "Connecting to Prodigi ... ... ... ... ... ... ... " > > If I remove the comma at the end of the marked line, the ellipses print > every .5 seconds as desired, except they print down the screen of course! > > After googling around a little, I found a post that seemed to say > Python won't draw the results of 'print' statements until it hits a > newline. I tried using sys.stout.write('...'), but had the same problem > there, too. I've also found a few progress bar classes around the web, > but I not exactly want a progress bar. I just want to print '...' every > few seconds until connected. > > Any hints? I looked up the python reference manual, but couldn't find > any way to force print statements to draw. Should I be looking into > threads, perhaps? > > Regards, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Just use sys.stdout.writelines(' ... ') Example: >>> import sys >>> sys.stdout.writelines ('... '); sys.stdout.writelines ('... ') ... ... >>> That what your looking for? Lee C From nequeo at gmail.com Sun Jun 12 11:07:03 2005 From: nequeo at gmail.com (Simon Gerber) Date: Sun, 12 Jun 2005 19:07:03 +1000 Subject: [Tutor] "Print" behaviour inside a loop? In-Reply-To: <0001HW.BED13D500013F213F0407550@news.gmane.org> References: <42AB76E3.90107@gmail.com> <0001HW.BED13D500013F213F0407550@news.gmane.org> Message-ID: <42ABFB37.4000800@gmail.com> >Just use sys.stdout.writelines(' ... ') > >Example: > >>> import sys > >>> sys.stdout.writelines ('... '); sys.stdout.writelines ('... ') > ... ... >>> > > Thank you for the suggestion Lee, but I'm afraid that doesn't work either. Same problems as described before. Max Noel hit the nail right on the head, though. I got it working with while ip_addr == "": sys.stdout.writelines("...") sys.stdout.flush() time.sleep(0.5) ip_addr = get_addr() if ip_addr != '': ... Script works like a charm now! Still rife with bugs and problems that would make it more or less useless for anyone except me - but a perfectly good, pptp config program already exists. I just made my own for education reasons. Anyone curious can view the whole thing here: http://members.optusnet.com.au/~sger/pytp I'd welcome any constructive criticism. Also, I'm storing a lot of passwords in plain text files. I hope I got all the permissions stuff right, but again, if anyone happens to spot any obvious flaws please do share. Regards, -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber nequeo at gmail.com From kent37 at tds.net Sun Jun 12 14:52:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 12 Jun 2005 08:52:44 -0400 Subject: [Tutor] "Print" behaviour inside a loop? In-Reply-To: <42ABFB37.4000800@gmail.com> References: <42AB76E3.90107@gmail.com> <0001HW.BED13D500013F213F0407550@news.gmane.org> <42ABFB37.4000800@gmail.com> Message-ID: <42AC301C.6040508@tds.net> Simon Gerber wrote: > I got it working with > > while ip_addr == "": > sys.stdout.writelines("...") > sys.stdout.flush() > time.sleep(0.5) > ip_addr = get_addr() > if ip_addr != '': > ... You should use sys.stdout.write(), not writelines(). writelines() expects a sequence of strings so what you wrote is roughly equivalent to sys.stdout.write(".") sys.stdout.write(".") sys.stdout.write(".") Kent From kristiano7 at gmail.com Sun Jun 12 16:17:33 2005 From: kristiano7 at gmail.com (Kristiano Ang) Date: Sun, 12 Jun 2005 22:17:33 +0800 Subject: [Tutor] Python Books Message-ID: <7175b2cc05061207174c092170@mail.gmail.com> Hey guys, On and off, I've been looking through the Python tutorials and I've been following the Josh Cogliati tutorial. While good for the basics, I find them to be a little incomplete (i.e: Lack of answers/followups for the excercises, etc). While this might not be a major issue, I am new to Python and it is a little offputting. So, I'm prepared to invest in a Python book of some sort that will help me master the language. Does anyone have any recommendations? Or perhaps tutorials? I have limited programming experience (a little dabbling in C++). -Kristiano Ang ~Macintosh addict~ From carroll at tjc.com Sun Jun 12 17:00:34 2005 From: carroll at tjc.com (Terry Carroll) Date: Sun, 12 Jun 2005 08:00:34 -0700 (PDT) Subject: [Tutor] Python Books In-Reply-To: <7175b2cc05061207174c092170@mail.gmail.com> Message-ID: On Sun, 12 Jun 2005, Kristiano Ang wrote: > So, I'm prepared to invest in a Python book of some sort that will > help me master the language. Does anyone have any recommendations? Or > perhaps tutorials? I have limited programming experience (a little > dabbling in C++). For a how-to-learn Python book, it's hard to beat "Learning Python" From cpu.crazy at gmail.com Sun Jun 12 13:58:26 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 12 Jun 2005 11:58:26 +0000 Subject: [Tutor] Jimage reader. How to find the pixels? Message-ID: <42AC2362.1070709@gmail.com> I have finally made my very first GUI program!! It needs some work before I would ever consider putting it on sourceforge (ha ha ha). I have a problem though. I can't find an image lib that will detect the picture's height and width automatically. I can use wave to detect mono or stereo but that's another story. Oh, one more thing, how can I make it so that I can type: python jimagereader.py /home/joe/pic.jpeg instead of the prompt within the program: Image name: Here's my code: from livewires import games image_nm = raw_input("Image name: ") SCREEN_WIDTH = int(raw_input("Image height: ")) SCREEN_HEIGHT = int(raw_input("Image width: ")) the_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) bckgrnd_image = games.load_image(image_nm, transparent = False) the_screen.set_background(bckgrnd_image) the_screen.mainloop() Thanks. Joe -- Unix Love, Linux Pride -----BEGIN GEEK CODE BLOCK----- Version 3.12 GU d- s-:- a---- C++++ UL++++ P L++ !E W+ N+ !o !K w !O !M V- PS-- !PE Y+ PGP- t- !5 !X !R !tv b+++ DI+ !D G e- h! !r y? k F ------END GEEK CODE BLOCK------ From kabads at gmail.com Sun Jun 12 20:52:21 2005 From: kabads at gmail.com (Adam Cripps) Date: Sun, 12 Jun 2005 19:52:21 +0100 Subject: [Tutor] Python Books In-Reply-To: <7175b2cc05061207174c092170@mail.gmail.com> References: <7175b2cc05061207174c092170@mail.gmail.com> Message-ID: On 6/12/05, Kristiano Ang wrote: > Hey guys, > On and off, I've been looking through the Python tutorials and I've > been following the Josh Cogliati tutorial. While good for the basics, > I find them to be a little incomplete (i.e: Lack of answers/followups > for the excercises, etc). While this might not be a major issue, I am > new to Python and it is a little offputting. > > So, I'm prepared to invest in a Python book of some sort that will > help me master the language. Does anyone have any recommendations? Or > perhaps tutorials? I have limited programming experience (a little > dabbling in C++). > > > -Kristiano Ang > ~Macintosh addict~ I'm a fan of the O'Reilly books - Learning Python - http://www.oreilly.com/catalog/lpython2/ Python Standard Library - http://www.oreilly.com/catalog/pythonsl/ (of which an online PDF version is available at http://www.effbot.org/librarybook/) HTH Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Sun Jun 12 21:39:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 12 Jun 2005 15:39:30 -0400 Subject: [Tutor] Jimage reader. How to find the pixels? In-Reply-To: <42AC2362.1070709@gmail.com> References: <42AC2362.1070709@gmail.com> Message-ID: <42AC8F72.4010708@tds.net> Joseph Quigley wrote: > I have finally made my very first GUI program!! It needs some work > before I would ever consider putting it on sourceforge (ha ha ha). I > have a problem though. I can't find an image lib that will detect the > picture's height and width automatically. I can use wave to detect mono > or stereo but that's another story. Oh, one more thing, how can I make > it so that I can type: python jimagereader.py /home/joe/pic.jpeg > instead of the prompt within the program: Image name: The Python Imaging Library can detect how big the image is and open a window to display it. The size is also available as the 'size' attribute of a PIL Image. To get the input from the command line look at sys.argv. PIL installs a simple image viewer as Python/Scripts/pilview.py. PIL is here: http://www.pythonware.com/products/pil/ Kent From chuck at freshsources.com Mon Jun 13 02:45:40 2005 From: chuck at freshsources.com (Chuck Allison) Date: Sun, 12 Jun 2005 18:45:40 -0600 Subject: [Tutor] Python Books In-Reply-To: References: Message-ID: <404586729.20050612184540@freshsources.com> Hello Terry, Practical Python is really good too, although I chose Learning Python over it to teach my class this month. Sunday, June 12, 2005, 9:00:34 AM, you wrote: TC> On Sun, 12 Jun 2005, Kristiano Ang wrote: >> So, I'm prepared to invest in a Python book of some sort that will >> help me master the language. Does anyone have any recommendations? Or >> perhaps tutorials? I have limited programming experience (a little >> dabbling in C++). TC> For a how-to-learn Python book, it's hard to beat "Learning Python" TC> _______________________________________________ TC> Tutor maillist - Tutor at python.org TC> http://mail.python.org/mailman/listinfo/tutor -- Best regards, Chuck From cyresse at gmail.com Mon Jun 13 07:10:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 13 Jun 2005 17:10:52 +1200 Subject: [Tutor] Web browser In-Reply-To: References: <42AA6103.9010901@adinet.com.uy> Message-ID: For what Ismael wants, you'd need to use PyXPCOM. IMAO, on a Win32 box, if you're not browsing dubious sites, it's not really worth the effort of trying to grasp XPCOM, when ActiveX/COM & IE are sitting there ready to use with a simpler interface. My $0.02. On 6/12/05, Terry Carroll wrote: > > On Sat, 11 Jun 2005, Ismael Garrido wrote: > > > I've been looking around for a web browser either written in python, or > > with python bindings. > > MozPython? http://www.thomas-schilz.de/MozPython/README.html > > > What I need to do is load a web-page, enter a password-protected site > > and follow certain links, it needs to have frames and follow the refresh > > meta. I'm running winxp, python 2.4 > > Why not write a scraper, using something like Beautiful Soup? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050613/8b71aaf8/attachment.html From cyresse at gmail.com Mon Jun 13 07:12:40 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 13 Jun 2005 17:12:40 +1200 Subject: [Tutor] Web browser In-Reply-To: References: <42AA6103.9010901@adinet.com.uy> Message-ID: Can Beautiful Soup execute scripts? I was trying to scrape using urllib2, and the Javascripts messed my navigation up something chronic. On 6/13/05, Liam Clarke wrote: > > For what Ismael wants, you'd need to use PyXPCOM. > > IMAO, on a Win32 box, if you're not browsing dubious sites, it's not > really worth the effort of trying to grasp XPCOM, when ActiveX/COM & IE are > sitting there ready to use with a simpler interface. > > My $0.02. > > > On 6/12/05, Terry Carroll wrote: > > > > On Sat, 11 Jun 2005, Ismael Garrido wrote: > > > > > I've been looking around for a web browser either written in python, > > or > > > with python bindings. > > > > MozPython? http://www.thomas-schilz.de/MozPython/README.html > > > > > What I need to do is load a web-page, enter a password-protected site > > > and follow certain links, it needs to have frames and follow the > > refresh > > > meta. I'm running winxp, python 2.4 > > > > Why not write a scraper, using something like Beautiful Soup? > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050613/e7cdb98e/attachment.htm From kent37 at tds.net Mon Jun 13 12:05:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Jun 2005 06:05:57 -0400 Subject: [Tutor] Web browser In-Reply-To: References: <42AA6103.9010901@adinet.com.uy> Message-ID: <42AD5A85.5070508@tds.net> Liam Clarke wrote: > Can Beautiful Soup execute scripts? I was trying to scrape using > urllib2, and the Javascripts messed my navigation up something chronic. No, Beautiful Soup won't run scripts. AFAIK the only way to access the web from Python and execute JavaScripts is to automate a browser and use the browser's JavaScript engine. (e.g. Pamie, COM, Selenium http://confluence.public.thoughtworks.org/display/SEL/Home) If Java/Jython is an option you could try HttpUnit which includes a JS interpreter. http://httpunit.sourceforge.net/ Kent From w.richert at gmx.net Mon Jun 13 23:44:16 2005 From: w.richert at gmx.net (Willi Richert) Date: Mon, 13 Jun 2005 23:44:16 +0200 Subject: [Tutor] Strange IndexError In-Reply-To: References: Message-ID: <200506132344.17160.w.richert@gmx.net> Hi, I used the same Pyro code, but this time with the release versions of player and stage. This time python crashed with a segfault: Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1273599056 (LWP 27633)] tupleiter_next (it=0xb6393cec) at Objects/tupleobject.c:797 797 Py_INCREF(item); (gdb) bt #0 tupleiter_next (it=0xb6393cec) at Objects/tupleobject.c:797 #1 0x00ada39f in PyIter_Next (iter=0x9) at Objects/abstract.c:2225 #2 0x00b2d6f0 in eval_frame (f=0x815840c) at Python/ceval.c:2091 #3 0x00b3197b in eval_frame (f=0x814dcdc) at Python/ceval.c:3518 #4 0x00b3197b in eval_frame (f=0x815665c) at Python/ceval.c:3518 #5 0x00b3197b in eval_frame (f=0x81561e4) at Python/ceval.c:3518 #6 0x00b3209e in PyEval_EvalCodeEx (co=0xb7c0a4a0, globals=0x9, locals=0x0, args=0xb637e218, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #7 0x00aede2e in function_call (func=0xb7c03d84, arg=0xb637e20c, kw=0x0) at Objects/funcobject.c:504 #8 0x00ada607 in PyObject_Call (func=0xb0b4f1, arg=0x0, kw=0x0) at Objects/abstract.c:1755 #9 0x00ae1d98 in instancemethod_call (func=0xb7c03d84, arg=0xb637e20c, kw=0x0) at Objects/classobject.c:2433 #10 0x00ada607 in PyObject_Call (func=0xb0b4f1, arg=0x0, kw=0x0) at Objects/abstract.c:1755 #11 0x00b2fb7f in eval_frame (f=0x811bbc4) at Python/ceval.c:3644 #12 0x00b3197b in eval_frame (f=0x8079b34) at Python/ceval.c:3518 #13 0x00b3197b in eval_frame (f=0x80fda8c) at Python/ceval.c:3518 #14 0x00b3209e in PyEval_EvalCodeEx (co=0xb7cdf220, globals=0x9, locals=0x0, args=0xb7bffb98, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #15 0x00aede2e in function_call (func=0xb7ceca3c, arg=0xb7bffb8c, kw=0x0) at Objects/funcobject.c:504 #16 0x00ada607 in PyObject_Call (func=0xb0b4f1, arg=0x0, kw=0x0) at Objects/abstract.c:1755 #17 0x00ae1d98 in instancemethod_call (func=0xb7ceca3c, arg=0xb7bffb8c, kw=0x0) at Objects/classobject.c:2433 #18 0x00ada607 in PyObject_Call (func=0xb0b4f1, arg=0x0, kw=0x0) at Objects/abstract.c:1755 #19 0x00b2c1b0 in PyEval_CallObjectWithKeywords (func=0x0, arg=0xb7fa202c, kw=0x0) at Python/ceval.c:3346 #20 0x00b54072 in t_bootstrap (boot_raw=0x8119840) at ./Modules/threadmodule.c:180 #21 0x00baa341 in start_thread () from /lib/tls/libpthread.so.0 #22 0x00a29fee in clone () from /lib/tls/libc.so.6 Is this Python-related or some other application's problem? wr Am Donnerstag, 2. Juni 2005 21:00 schrieb Danny Yoo: > On Thu, 2 Jun 2005, Willi Richert wrote: > > my app is a Pyrobot (http://emergent.brynmawr.edu/~dblank/pyro/) > > simulation which connects to PlayerStage (playerstage.sf.net) to > > simulate three Pioneer robots. These are controlled using NeedBrain.py. > > In parallel to the three NeedBrains there is one MonitorBrain running > > for some management tasks, so I have > > four parallel running classes. > > Hi Willi, > > I think you may want to bring this up on comp.lang.python: I have a strong > feeling I'm in over my head. *grin* The experts on comp.lang.python > should be able to better pinpoint the exact problem. > > > The code that prints that peculiar error message is at the very core of > Python's object implementation in doing object equality checking: > > /*** Objects/object.c, about line 441 in Python 2.4 source ***/ > /* Helper to warn about deprecated tp_compare return values. Return: > -2 for an exception; > -1 if v < w; > 0 if v == w; > 1 if v > w. > (This function cannot return 2.) > */ > static int > adjust_tp_compare(int c) > { > if (PyErr_Occurred()) { > if (c != -1 && c != -2) { > PyObject *t, *v, *tb; > PyErr_Fetch(&t, &v, &tb); > if (PyErr_Warn(PyExc_RuntimeWarning, > "tp_compare didn't return -1 or -2 " > "for exception") < 0) { > Py_XDECREF(t); > Py_XDECREF(v); > Py_XDECREF(tb); > } > else > PyErr_Restore(t, v, tb); > /******/ > > > We can reason that PyErr_Occurred() somehow returned true, and that the > error information is being captured in C code throught the 't', 'v' and > 'tb' variables. Those three variables are ultimately responsible for > what's printing out: > > IndexError: tuple assignment index out of range > > and the output that talks about 'tp_compare' shows up because of the > PyErr_Warn call. That explains why we see both error messages. > > > > I'm staring at the code a little more; there's a bit of code around line > 229 that bothers me a bit: > > ###### > try: > self._markerObject = self.get("robot/fiducial/id")(self.marker) > finally: > if not self._markerObject: > self._markerDist = 1000.0 > else: > self._markerDist = self._markerObject.range > ###### > > My hypothesis now is that the equality check against the type of > self._markerDist is raising an error, which would require self._markerDist > to be something unusual. I know, I'm reaching, but let me see how far > this goes. *grin* > > I don't see anything else that assigns to self._markerDist in any other > part of the code. In the code above, I see in the 'else' block that > self._markerDist is being assigned to 'self._markerObject.range'. What > type is 'self._markerObject', and what type is 'self._markerObject.range? > Do you mind adding some code to print those out? > > > > > I can't assume that 'range' is a number, since 'range' is being used in > all sorts of contexts, especially in the pyro source code. For example, > pyro.PyroHierarchy has the following comment: > > ###### > class PyroHierarchy (object): > """ > A wrapper class for the pyro devices hierarchy. > An instance of this class represents a node of the hierarchy, > with an attribute for every subnode. > Getting an attribute is equivalent to using robot.get . > Setting an attribute is equivalent to using robot.set . > Numeric nodes can be accessed as list elements. > > Examples of use: > h.robot.range.all # returns another PyroHierarchy > object > h.robot.range.name # return a string > h.robot.range.all.value # return a list of numbers > h.robot.range[1].value # returns a number > h.robot.range[1:4] # returns a list of PyroHierarchy > objects > h.devices.gripper.command = "open" # issues command "open" to > gripper0 > """ > ###### > > > so I strongly suspect that this 'range' object is something much richer > than a float. > > > > Something like: > > print self._markerDist, type(self._markerDist) > > might help us see what's going on better. > > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Jun 14 01:03:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 13 Jun 2005 16:03:42 -0700 (PDT) Subject: [Tutor] Strange IndexError In-Reply-To: <200506132344.17160.w.richert@gmx.net> Message-ID: On Mon, 13 Jun 2005, Willi Richert wrote: > I used the same Pyro code, but this time with the release versions of > player and stage. This time python crashed with a segfault: Hi Willi, If you see a segfault like this, it's almost definitely a bug in a third-party module. It is possible that the bug is in Python itself, but since the Python core has been so well-tested, this is unlikely. Bring this up to the Pyro folks so they can trace what looks like an incorrect refcount problem somewhere in their C code or SWIG bindings. I don't think there's much else that you can do at this point, unless you have written your code to use some substitute to Pyro. If I had time, I'd be willing to look at the Pyro code and see what's going on. But the Pyro folks are probably the people to pester about this, since this looks like a problem in their extension code. From squeaky at sdf.lonestar.org Tue Jun 14 05:27:56 2005 From: squeaky at sdf.lonestar.org (Gary Taylor) Date: Mon, 13 Jun 2005 20:27:56 -0700 Subject: [Tutor] Passing command line argument in function Message-ID: <20050614032756.GA3050@SDF.LONESTAR.ORG> I'm trying to pass the name of a file as the first argument to the ftp.storbinary function(?) below. The only thing I can get to work is the real file name hard coded as the argument. I've tried parenthesis, single quotes, double quotes, and many combinations of the previous. I've tried passing sys.argv[1] directly as well, although with fewer experiments. I invoke this as below and the output is what I would expect, but the file name on the ftp server is never correct. What is the correct way to do this? $ ./garyftp.py align.ps align.ps --- Python 2.3.4 on Linux. --- #!/usr/bin/python import sys from ftplib import FTP file_to_transfer = sys.argv[1] ftp = FTP() ftp.connect("myserver") ftp.login("myusername", "mypasswd") ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) print file_to_transfer ftp.quit() -- Thanks, Gary squeaky at sdf.lonestar.org From cyresse at gmail.com Tue Jun 14 07:40:16 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 14 Jun 2005 17:40:16 +1200 Subject: [Tutor] Passing command line argument in function In-Reply-To: <20050614032756.GA3050@SDF.LONESTAR.ORG> References: <20050614032756.GA3050@SDF.LONESTAR.ORG> Message-ID: What path is the file? On 6/14/05, Gary Taylor wrote: > > I'm trying to pass the name of a file as the first argument > to the ftp.storbinary function(?) below. The only thing I > can get to work is the real file name hard coded as the > argument. I've tried parenthesis, single quotes, double > quotes, and many combinations of the previous. I've tried > passing sys.argv[1] directly as well, although with fewer > experiments. > > I invoke this as below and the output is what I would > expect, but the file name on the ftp server is never > correct. > > > What is the correct way to do this? > > > $ ./garyftp.py align.ps > align.ps > > > > --- > Python 2.3.4 on Linux. > > > --- > #!/usr/bin/python > import sys > from ftplib import FTP > > file_to_transfer = sys.argv[1] > > ftp = FTP() > ftp.connect("myserver") > ftp.login("myusername", "mypasswd") > > > ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) > > print file_to_transfer > ftp.quit() > -- > > Thanks, > Gary > > squeaky at sdf.lonestar.org > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050614/5a9e31d6/attachment.htm From w.richert at gmx.net Tue Jun 14 10:07:56 2005 From: w.richert at gmx.net (Willi Richert) Date: Tue, 14 Jun 2005 10:07:56 +0200 Subject: [Tutor] Strange IndexError In-Reply-To: References: Message-ID: <200506141007.58373.w.richert@gmx.net> Hi Danny, I've posted the bug at the pyro ML. However the old IndexError annoys me more and more. Although I have encapsulated it with try/except blocks and that works ok for what I want, I really want to understand how an exception like Traceback (most recent call last): File "NeedBrain.py", line 257, in update assert type(self.STAY_MIN_DIST)==type(1.0), str(self.STAY_MIN_DIST)+"is not float" IndexError: tuple assignment index out of range is thrown. I mean, this line of code must be some Python related stuff. The only alternativ would be that self has some __getattr__ methods that were invoked. But then, the exception would have bin in that method, wouldn't it? The only place where STAY_MIN_DIST is set is as a class variable: class ApproachMarkerAction(State): STAY_MIN_DIST = 2.0 def __init__(self, markerType=None, status = 0, name = ''): ... Thanks for any clarification, wr Am Dienstag, 14. Juni 2005 01:03 schrieb Danny Yoo: > On Mon, 13 Jun 2005, Willi Richert wrote: > > I used the same Pyro code, but this time with the release versions of > > player and stage. This time python crashed with a segfault: > > Hi Willi, > > If you see a segfault like this, it's almost definitely a bug in a > third-party module. It is possible that the bug is in Python itself, but > since the Python core has been so well-tested, this is unlikely. > > > Bring this up to the Pyro folks so they can trace what looks like an > incorrect refcount problem somewhere in their C code or SWIG bindings. I > don't think there's much else that you can do at this point, unless you > have written your code to use some substitute to Pyro. > > If I had time, I'd be willing to look at the Pyro code and see what's > going on. But the Pyro folks are probably the people to pester about > this, since this looks like a problem in their extension code. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ajikoe at gmail.com Tue Jun 14 10:38:32 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 14 Jun 2005 10:38:32 +0200 Subject: [Tutor] is this a bug global i ??? Message-ID: I have code like this: class A: def __init__(self,j): self.j = j def something(self): print self.j print i # PROBLEM is here there is no var i in class A but it works ??? if __name__ == '__main__': i = 10 a = A(5) a.something() I don't define global i but it will takes var i from outside of class A. Can somebody explain this ??? pujo From kent37 at tds.net Tue Jun 14 12:10:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jun 2005 06:10:11 -0400 Subject: [Tutor] Passing command line argument in function In-Reply-To: <20050614032756.GA3050@SDF.LONESTAR.ORG> References: <20050614032756.GA3050@SDF.LONESTAR.ORG> Message-ID: <42AEAD03.8010408@tds.net> Gary Taylor wrote: > I'm trying to pass the name of a file as the first argument > to the ftp.storbinary function(?) below. The only thing I > can get to work is the real file name hard coded as the > argument. I've tried parenthesis, single quotes, double > quotes, and many combinations of the previous. I've tried > passing sys.argv[1] directly as well, although with fewer > experiments. > > I invoke this as below and the output is what I would > expect, but the file name on the ftp server is never > correct. > > > What is the correct way to do this? > > > $ ./garyftp.py align.ps > align.ps > > > > --- > Python 2.3.4 on Linux. > > > --- > #!/usr/bin/python > import sys > from ftplib import FTP > > file_to_transfer = sys.argv[1] > > ftp = FTP() > ftp.connect("myserver") > ftp.login("myusername", "mypasswd") > > > ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) You need to create the command as a string: ftp.storbinary("stor " + file_to_transfer, open(file_to_transfer,"r")) Kent > > print file_to_transfer > ftp.quit() > -- > > Thanks, > Gary > > squeaky at sdf.lonestar.org > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Jun 14 12:16:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jun 2005 06:16:05 -0400 Subject: [Tutor] is this a bug global i ??? In-Reply-To: References: Message-ID: <42AEAE65.9060001@tds.net> Pujo Aji wrote: > I have code like this: > > class A: > def __init__(self,j): > self.j = j > > def something(self): > print self.j > print i # PROBLEM is here there is no var i in class A > but it works ??? > > if __name__ == '__main__': > i = 10 > a = A(5) > a.something() > > I don't define global i but it will takes var i from outside of class A. This is normal behavior. When Python needs to resolve a bare name it looks it up first in the local scope (the current function), then in any enclosing lexical scopes (for nested functions), then the global scope and finally the builtins. In this case the binding for i is found in the global scope. Note that *assigning* to a name always happens in the local scope unless the name is declared global. There is no (clean) way to assign to a name in an enclosing lexical scope or the builtins. These might help a little: http://docs.python.org/tut/node11.html#SECTION0011200000000000000000 http://docs.python.org/ref/naming.html Kent From squeaky at sdf.lonestar.org Tue Jun 14 16:14:59 2005 From: squeaky at sdf.lonestar.org (Gary Taylor) Date: Tue, 14 Jun 2005 07:14:59 -0700 Subject: [Tutor] Passing command line argument in function In-Reply-To: <20050614032756.GA3050@SDF.LONESTAR.ORG> References: <20050614032756.GA3050@SDF.LONESTAR.ORG> Message-ID: <20050614141459.GA13770@SDF.LONESTAR.ORG> >> >> >> ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) >> > >You need to create the command as a string: >ftp.storbinary("stor " + file_to_transfer, >open(file_to_transfer,"r")) > >Kent That worked perfectly, I was way off. Thank-you! Gary p.s. sorry for the out of thread message, my mail seems to be having problems. -- squeaky at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From John.Gooch at echostar.com Tue Jun 14 17:07:56 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Tue, 14 Jun 2005 09:07:56 -0600 Subject: [Tutor] Which Popen For Win32? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D493@riv-excha5.echostar.com> I am using the Winzip 9.0 Command Line Add-on to archive very large files ( 1GB and over ) that are too large to be handled by Zipfile( this bug has been reported but not resolved ). I tried calling the external program using os.system(), but something about the output crashes my IDE ( Eclipse ), so I started looking for a way to run the external application without capturing the output, as I only care about the exit code ( 0 is good, anything else is bad ). Here is what I have to far: myCmd = os.popen( "%s %s %s %s" % ( zipCommand, zipParameters, archive,fpath ), 'w' ) return myCmd.close() Currently, I have no idea what is being returned by the "close()" method, it doesn't appear to be the exit code, so perhaps it is the output of the command. If so, how can I capture and return the exit code? Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Gary Taylor Sent: Tuesday, June 14, 2005 8:15 AM To: tutor at python.org Subject: Re: [Tutor] Passing command line argument in function >> >> >> ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) >> > >You need to create the command as a string: ftp.storbinary("stor " + >file_to_transfer, >open(file_to_transfer,"r")) > >Kent That worked perfectly, I was way off. Thank-you! Gary p.s. sorry for the out of thread message, my mail seems to be having problems. -- squeaky at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Tue Jun 14 19:06:28 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 14 Jun 2005 10:06:28 -0700 (PDT) Subject: [Tutor] is this a bug global i ??? In-Reply-To: Message-ID: On Tue, 14 Jun 2005, Pujo Aji wrote: > I have code like this: > > class A: > def __init__(self,j): > self.j = j > > def something(self): > print self.j > print i # PROBLEM is here there is no var i in class A > but it works ??? > > if __name__ == '__main__': > i = 10 > a = A(5) > a.something() > > I don't define global i but it will takes var i from outside of class A. > > Can somebody explain this ??? The i is 'global' by placement so it can be read. But you can't assign it in a.something(). If you do: class A: def __init__(self,j): self.j = j def something(self): print self.j i = 11 # makes a new local i in something print i if __name__ == '__main__': i = 10 a = A(5) a.something() print 'i = ', i # prints the same old global i = 10 You'll find you made a new i in something and your i = 10 remains the same. But, if you want to change the global i, in something, then it's time for the global declaration: def something(self): global i print self.j i = 11 # changes the global i print i Hope this helps. I had the same confusion long ago and this list helped me. Marilyn Davis > > pujo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- From carroll at tjc.com Tue Jun 14 19:11:36 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 14 Jun 2005 10:11:36 -0700 (PDT) Subject: [Tutor] Trying Ruby... In-Reply-To: Message-ID: My original question: > I vaguely recall a post a few months ago, I don't know if it was in this > forum, where someone had a problem in Python, and it turns out it was > because a Ruby install messed with some setting, perhaps in the Windows > registry.... Anyway, I'd like to install Ruby, but want to make very > sure I don't impair my Python environment. On Tue, 7 Jun 2005, Premshree Pillai wrote: > I have Python and Ruby -- not ActiveState -- installed on an XP box. No > issues. On Tue, 7 Jun 2005, Christian Wyglendowski wrote: > If I remember correctly, it had to do with Tk getting messed up. But > that's all I recall :-) Sorry for the late acknowledgement. My computer fried not long after I posted the message, and I haven't been reading much email since. Thanks to you both. I found the problem I recalled; Ruby sets some environment variables assuming that it's the only user of Tk, and hoses the Python usage: https://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=824756 https://sourceforge.net/tracker/?func=detail&atid=105470&aid=922914&group_id=5470 or http://makeashorterlink.com/?G4DC1624B and http://makeashorterlink.com/?T1EC2124B I'll just be careful when I install Ruby and take corrective action if needed. From alan.gauld at freenet.co.uk Tue Jun 14 19:45:04 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 14 Jun 2005 18:45:04 +0100 Subject: [Tutor] is this a bug global i ??? References: Message-ID: <0bb301c57108$cbeef780$c7a58851@xp> class A: def __init__(self,j): self.j = j def something(self): print self.j print i # PROBLEM is here there is no var i in class A but it works ??? if __name__ == '__main__': i = 10 a = A(5) a.something() > I don't define global i but it will takes var i from outside of class A. > Can somebody explain this ??? You only need to declare global if you are modifying data if you only read it there is no need for explicit global statements. Alan G. From ajikoe at gmail.com Tue Jun 14 23:56:48 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 14 Jun 2005 23:56:48 +0200 Subject: [Tutor] can't see emacs timer in action Message-ID: Hello, I tried this code in emacs. for i in range(3): time.sleep(1) print i It shows the result but total result not second per second. Any one experiance this problem pujo From maxnoel_fr at yahoo.fr Wed Jun 15 00:02:21 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 14 Jun 2005 23:02:21 +0100 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: Message-ID: <4A98C13F-DFBC-44DA-8211-C7BC18B61DF0@yahoo.fr> On Jun 14, 2005, at 22:56, Pujo Aji wrote: > Hello, > > I tried this code in emacs. > for i in range(3): > time.sleep(1) > print i > > It shows the result but total result not second per second. > > Any one experiance this problem > > pujo Works for me... How do you run it? Do you use a separate terminal window, or do you use some kind of "run with Python" command in emacs? (not sure how it's done, I'm a vim user myself) Did you make sure you import time before that code is run? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Wed Jun 15 00:19:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 14 Jun 2005 23:19:40 +0100 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: <4A98C13F-DFBC-44DA-8211-C7BC18B61DF0@yahoo.fr> Message-ID: On Jun 14, 2005, at 23:17, Pujo Aji wrote: > I just use Ctrl+C Ctrl+C to run the code. > The code wait for 3 second and show all i all together. > > I can't feel every second pass. > > pujo Try running your script from a terminal (outside of emacs, that is). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Wed Jun 15 00:21:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Jun 2005 15:21:00 -0700 (PDT) Subject: [Tutor] can't see emacs timer in action In-Reply-To: Message-ID: On Tue, 14 Jun 2005, Pujo Aji wrote: > I tried this code in emacs. > for i in range(3): > time.sleep(1) > print i > > It shows the result but total result not second per second. Hi Pujo, In Emacs, you may want to first start up a Python subprocess by using the keystroke: C-c ! and then run Python buffers with: C-c C-c Best of wishes! From dyoo at hkn.eecs.berkeley.edu Wed Jun 15 01:32:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Jun 2005 16:32:20 -0700 (PDT) Subject: [Tutor] can't see emacs timer in action In-Reply-To: Message-ID: On Wed, 15 Jun 2005, Pujo Aji wrote: > Thanks Danny, > > Btw, I use xemacs now does it has folding class and method capabilities? Hi Pujo, [Note: in replies, please make sure to put tutor at python.org in CC.] According to: http://groups.google.ca/group/comp.lang.python/msg/956f1c2d37f93995?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=2 Yes. *grin* From webdev at matheteuo.org Wed Jun 15 02:59:24 2005 From: webdev at matheteuo.org (DC Parris) Date: Wed, 15 Jun 2005 00:59:24 -0000 Subject: [Tutor] Controlling Where My Program Ends Message-ID: <20050615005916.D2EF64152F@mail01.powweb.com> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20050615/6b1589f9/attachment.diff From webdev at matheteuo.org Wed Jun 15 05:03:59 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 14 Jun 2005 23:03:59 -0400 Subject: [Tutor] Controlling Where My Program Ends In-Reply-To: <20050615005916.D2EF64152F@mail01.powweb.com> References: <20050615005916.D2EF64152F@mail01.powweb.com> Message-ID: <20050614230359.413b36c3@luke.matheteuo.rel> On Wed, 15 Jun 2005 00:59:24 -0000 "DC Parris" wrote: > Never mind. I found it - sys.exit() > > Sorry to have wasted the bandwidth/time. > -- This was in reference to a post about exiting from a program. I couldn't figure out why my program wouldn't let me exit from within a sub-menu of the console interface. Since my webmail client goofed up the "from" header, it never showed up, and I've cancelled it to avoid wasting everyone's time further. I found sys.exit() in the library reference, which allows me to do what I want. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From ajikoe at gmail.com Wed Jun 15 11:11:14 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 15 Jun 2005 11:11:14 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: Message-ID: Hallo Danny, If we always start interpreter everytime we want to run python in emacs/xemacs, is it counter productive? I usually have to clean the buffer/output pane before running my program, so I always do this to start my program: C-c ! to start the interpreter C-c o to change my windows C-c C-c to run the program C-x k ENTER to close it C-c o to change my editor again C-c ! to start the interpreter again This is one cycle of running. Is that normal ??? What is the difference between running C-c C-c directly and running it after the interpreter? I need to make shortcut for starting interpreter do you have any idea. For this moment I use SciTE and I want to learn using xemacs. Thanks in advance, pujo On 6/15/05, Danny Yoo wrote: > > > On Wed, 15 Jun 2005, Pujo Aji wrote: > > > Thanks Danny, > > > > Btw, I use xemacs now does it has folding class and method capabilities? > > Hi Pujo, > > [Note: in replies, please make sure to put tutor at python.org in CC.] > > > According to: > > http://groups.google.ca/group/comp.lang.python/msg/956f1c2d37f93995?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=2 > > Yes. *grin* > > > From ajikoe at gmail.com Wed Jun 15 15:05:31 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 15 Jun 2005 15:05:31 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: <4A98C13F-DFBC-44DA-8211-C7BC18B61DF0@yahoo.fr> Message-ID: thanks Noel, It is great idea. pujo On 6/15/05, Max Noel wrote: > > On Jun 14, 2005, at 23:17, Pujo Aji wrote: > > > I just use Ctrl+C Ctrl+C to run the code. > > The code wait for 3 second and show all i all together. > > > > I can't feel every second pass. > > > > pujo > > Try running your script from a terminal (outside of emacs, that > is). > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From mhansen at cso.atmel.com Wed Jun 15 15:46:40 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 15 Jun 2005 07:46:40 -0600 Subject: [Tutor] Controlling Where My Program Ends In-Reply-To: References: Message-ID: <42B03140.1020003@cso.atmel.com> > Subject: > Re: [Tutor] Controlling Where My Program Ends > From: > Don Parris > Date: > Tue, 14 Jun 2005 23:03:59 -0400 > To: > tutor at python.org > > To: > tutor at python.org > > > On Wed, 15 Jun 2005 00:59:24 -0000 > "DC Parris" wrote: > > >>Never mind. I found it - sys.exit() >> >>Sorry to have wasted the bandwidth/time. >>-- > > > This was in reference to a post about exiting from a program. I couldn't > figure out why my program wouldn't let me exit from within a sub-menu of the > console interface. Since my webmail client goofed up the "from" header, it > never showed up, and I've cancelled it to avoid wasting everyone's time > further. I found sys.exit() in the library reference, which allows me to do > what I want. > > Don > If you use the if __name__ == '__main__': idiom, then you can just use return instead of sys.exit() def main(): lotsa interesting python code if somethinorother: # sys.exit() return more interesting python code if __name__ == '__main__': main() From John.Gooch at echostar.com Wed Jun 15 15:55:42 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Wed, 15 Jun 2005 07:55:42 -0600 Subject: [Tutor] Popen4 and Paths Containing Spaces Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D49E@riv-excha5.echostar.com> I am having problems with using the Winzip command line tools and Python. Here is an example of the several dozen different ways I have tried to execute the Wzzip.exe utility with arguments using popen2 - This works (just runs the utility with not arguments ): cmd = "\"d:/program files/winzip/wzzip.exe\"" results = popen2.popen4( cmd ) However this fails miserably: testpath = "D:/Program Files/WebTrends/SmartSource Data Collector/weblog/*.log" cmd = "\"d:/program files/winzip/wzzip.exe\" -ma test.zip \"" + testpath + "\"" results = popen2.popen4( cmd ) If I set the script to print out the value stored in the variable "cmd" it says this: "d:/program files/winzip/wzzip.exe\" -ma test.zip "D:/Program Files/WebTrends/SmartSource Data Collector/weblog/*.log" Which if I paste it onto the command line, does exactly what I intend it to do. But for some reason, popen2.popen4(cmd) gives this as output ( from stderr ): 'd:/program' is not a file or command My only guess is that popen2.popen4 is parsing the string differently than the "print" command does, because print recognizes that the backslash is escaping the double quotes ( e.g. "\"" ) in the string, and popen does not. On the other hand, it appears to be recognizing it in my first example, so that is what is really confusing me. It isn't consistent at all. Any ideas? John A. Gooch "May the Python-force be with you...always." Systems Administrator EchoStar Satellite L.L.C. Desk: 720-514-5708 -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo Sent: Tuesday, June 14, 2005 4:21 PM To: Pujo Aji Cc: Tutor Subject: Re: [Tutor] can't see emacs timer in action On Tue, 14 Jun 2005, Pujo Aji wrote: > I tried this code in emacs. > for i in range(3): > time.sleep(1) > print i > > It shows the result but total result not second per second. Hi Pujo, In Emacs, you may want to first start up a Python subprocess by using the keystroke: C-c ! and then run Python buffers with: C-c C-c Best of wishes! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From albertito_g at hotmail.com Wed Jun 15 16:42:26 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 15 Jun 2005 14:42:26 +0000 Subject: [Tutor] Process problem Message-ID: Hey all I have a problem with a program You see, I have a python script made in Python 2.2 that runs every 15 minutes on Linux Red Hat 9.0 This program (which code is attached below) named levantamuertos.py (spanish for death weakener) has to check in a database if the pids stored are running (note that it will be more than one pid) and if they are not it has to start again the process and it will store the new pid on the database The problem is that when I call it it runs and weaks all dead process but when it dies, he takes all his sons with him. How can I make that the cotascamon.py keep running although levantamuertos.py die? Thanks in advanced and here is the code Alberto ################## ### levantamuertos.py ### ################## import os import sys import MySQLdb import time class conexion(object): def __init__(self): self.db = MySQLdb.connect(host="localhost", user="administrador", passwd="123456",db="seguridad") def consulta(self,query,args=None): try: self.cursor=self.db.cursor() self.sql=self.cursor.execute(query,args) except: self.cerrar() else: self.cerrar() def cerrar(self): self.db.close() query="SELECT PID,user,cam,ruta from proceso where user='DMALAKIAN'" cur=conexion() cur.consulta(query) res=cur.cursor.fetchall() if len(res)>0: for elem in res: pi=elem[0] ps_command = 'ps -p %s' % pi pidchk = os.popen(ps_command).readlines() count = 0 for line in pidchk: count +=1 if count > 1: print "Encontre el proceso" else: query="update proceso set PID=%s where user='DMALAKIAN'" p=os.getpid() args=(p) cur=conexion() cur.consulta(query,args) query="SELECT PID,user,cam,ruta from proceso where user <> 'DMALAKIAN'" cur=conexion() cur.consulta(query) res=cur.cursor.fetchall() if len(res)>0: for elem in res: pid=elem[0] user=elem[1] cam=elem[2] ruta=str(elem[3]) ps_command = 'ps -p %s' % pid pidchk = os.popen(ps_command).readlines() count = 0 for line in pidchk: count +=1 if count > 1: pass else: os.system("python2.2 /root/cotascamon.py "+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) else: pass else: query="insert into proceso values('DMALAKIAN',0,%s,'NO HAY RUTA PARA ESTE USUARIO')" p=os.getpid() args=(p) cur=conexion() cur.consulta(query,args) query="SELECT PID,user,cam,ruta from proceso where user <> 'DMALAKIAN'" cur=conexion() cur.consulta(query) res=cur.cursor.fetchall() if len(res)>0: for elem in res: pid=elem[0] user=elem[1] cam=elem[2] ruta=str(elem[3]) ps_command = 'ps -p %s' % pid pidchk = os.popen(ps_command).readlines() count = 0 for line in pidchk: count +=1 if count > 1: pass else: os.system("python2.2 /root/cotascamon.py "+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) else: pass From hugonz-lists at h-lab.net Wed Jun 15 17:01:48 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Jun 2005 10:01:48 -0500 Subject: [Tutor] Which Popen For Win32? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D493@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D493@riv-excha5.echostar.com> Message-ID: <42B042DC.7030608@h-lab.net> Hi, maybe you'll want to give a try to: import commands stat, outp = commands.getstatusoutput ("%s %s %s %s"%(zipCommand, zipParameters, archive, fpath)) This will give you the exit code in stat and the whole text of the putput in outp, so you may take a look at it. It's way simpler than popen. Hugo Gooch, John wrote: > I am using the Winzip 9.0 Command Line Add-on to archive very large files ( > 1GB and over ) that are too large to be handled by Zipfile( this bug has > been reported but not resolved ). I tried calling the external program using > os.system(), but something about the output crashes my IDE ( Eclipse ), so I > started looking for a way to run the external application without capturing > the output, as I only care about the exit code ( 0 is good, anything else is > bad ). Here is what I have to far: > > myCmd = os.popen( "%s %s %s %s" % ( zipCommand, zipParameters, > archive,fpath ), 'w' ) > return myCmd.close() > > Currently, I have no idea what is being returned by the "close()" method, it > doesn't appear to be the exit code, so perhaps it is the output of the > command. If so, how can I capture and return the exit code? > > Thank You, > > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > > > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Gary Taylor > Sent: Tuesday, June 14, 2005 8:15 AM > To: tutor at python.org > Subject: Re: [Tutor] Passing command line argument in function > > > >>> >>>ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) >>> >> >>You need to create the command as a string: ftp.storbinary("stor " + >>file_to_transfer, >>open(file_to_transfer,"r")) >> >>Kent > > > That worked perfectly, I was way off. > > Thank-you! > > Gary > > p.s. sorry for the out of thread message, my mail seems to > be having problems. > From kent37 at tds.net Wed Jun 15 17:16:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jun 2005 11:16:14 -0400 Subject: [Tutor] Which Popen For Win32? In-Reply-To: <42B042DC.7030608@h-lab.net> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D493@riv-excha5.echostar.com> <42B042DC.7030608@h-lab.net> Message-ID: <42B0463E.5080609@tds.net> Hugo Gonz?lez Monteverde wrote: > Hi, maybe you'll want to give a try to: > > import commands > stat, outp = commands.getstatusoutput ("%s %s %s %s"%(zipCommand, > zipParameters, archive, fpath)) > > This will give you the exit code in stat and the whole text of the > putput in outp, so you may take a look at it. It's way simpler than popen. According to the docs commands is Unix-only. Kent > > Hugo > > > Gooch, John wrote: > >>I am using the Winzip 9.0 Command Line Add-on to archive very large files ( >>1GB and over ) that are too large to be handled by Zipfile( this bug has >>been reported but not resolved ). I tried calling the external program using >>os.system(), but something about the output crashes my IDE ( Eclipse ), so I >>started looking for a way to run the external application without capturing >>the output, as I only care about the exit code ( 0 is good, anything else is >>bad ). Here is what I have to far: >> >> myCmd = os.popen( "%s %s %s %s" % ( zipCommand, zipParameters, >>archive,fpath ), 'w' ) >> return myCmd.close() >> >>Currently, I have no idea what is being returned by the "close()" method, it >>doesn't appear to be the exit code, so perhaps it is the output of the >>command. If so, how can I capture and return the exit code? >> >>Thank You, >> >> >>John A. Gooch >>Systems Administrator >>IT - Tools >>EchoStar Satellite L.L.C. >>9601 S. Meridian Blvd. >>Englewood, CO 80112 >>Desk: 720-514-5708 >> >> >> >> >>-----Original Message----- >>From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf >>Of Gary Taylor >>Sent: Tuesday, June 14, 2005 8:15 AM >>To: tutor at python.org >>Subject: Re: [Tutor] Passing command line argument in function >> >> >> >> >>>>ftp.storbinary(stor file_to_transfer, open(file_to_transfer,"r")) >>>> >>> >>>You need to create the command as a string: ftp.storbinary("stor " + >>>file_to_transfer, >>>open(file_to_transfer,"r")) >>> >>>Kent >> >> >>That worked perfectly, I was way off. >> >>Thank-you! >> >>Gary >> >>p.s. sorry for the out of thread message, my mail seems to >>be having problems. >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From webdev at matheteuo.org Wed Jun 15 18:11:34 2005 From: webdev at matheteuo.org (Don Parris) Date: Wed, 15 Jun 2005 12:11:34 -0400 Subject: [Tutor] Controlling Where My Program Ends In-Reply-To: <42B03140.1020003@cso.atmel.com> References: <42B03140.1020003@cso.atmel.com> Message-ID: <20050615121134.6baca18b@luke.matheteuo.rel> On Wed, 15 Jun 2005 07:46:40 -0600 Mike Hansen wrote: > > Subject: > > Re: [Tutor] Controlling Where My Program Ends > > From: > > Don Parris > > Date: > > Tue, 14 Jun 2005 23:03:59 -0400 > > To: > > tutor at python.org > > > > To: > > tutor at python.org > > > > > > On Wed, 15 Jun 2005 00:59:24 -0000 > > "DC Parris" wrote: > > > > > >>Never mind. I found it - sys.exit() > >> > >>Sorry to have wasted the bandwidth/time. > >>-- > > > > > > This was in reference to a post about exiting from a program. I > > couldn't figure out why my program wouldn't let me exit from within a > > sub-menu of the console interface. Since my webmail client goofed up > > the "from" header, it never showed up, and I've cancelled it to avoid > > wasting everyone's time further. I found sys.exit() in the library > > reference, which allows me to do what I want. > > > > Don > > > > If you use the if __name__ == '__main__': idiom, then you can just use > return instead of sys.exit() > > def main(): > lotsa interesting python code > if somethinorother: > # sys.exit() > return > more interesting python code > > if __name__ == '__main__': > main() > > _______________________________________________ Thanks. I'll try that out a little later (when I get back to this). Incidentally, my menu system started off quite klunky, but I've thrown my menu items into dictionaries and iterate through them to display the menu. Thus, instead of: print 'menuitem' print 'menuitem' etc., etc., etc. I now have: for i in menu.iteritems(): print repr(key), '', 'value' Now if I can figure out how to iterate through the if --> elif statements, I'll be able to shorten the code a bit further. First things first though. Let me just understand these basic things, and then I'll see if I can get a little smarter. Maybe I'll start a thread "trials of a Python newbie". It'll be hilarious for the old timers, I'm sure. It might help other newbies as well. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From hugonz-lists at h-lab.net Wed Jun 15 20:20:37 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Jun 2005 13:20:37 -0500 Subject: [Tutor] Popen4 and Paths Containing Spaces In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D49E@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D49E@riv-excha5.echostar.com> Message-ID: <42B07175.50105@h-lab.net> Hi John, Read the Python gotchas page at: http://www.ferg.org/projects/python_gotchas.html This problem is explained there. Also, why are you using those forward slashes in your Windows paths???? Meaning: d:/program files/winzip/wzzip.exe Hugo Gooch, John wrote: > I am having problems with using the Winzip command line tools and Python. > > Here is an example of the several dozen different ways I have tried to > execute the Wzzip.exe utility with arguments using > popen2 - > > This works (just runs the utility with not arguments ): > cmd = "\"d:/program files/winzip/wzzip.exe\"" > results = popen2.popen4( cmd ) > > However this fails miserably: > testpath = "D:/Program Files/WebTrends/SmartSource Data > Collector/weblog/*.log" > cmd = "\"d:/program files/winzip/wzzip.exe\" -ma test.zip \"" + testpath > + "\"" > results = popen2.popen4( cmd ) > > If I set the script to print out the value stored in the variable "cmd" it > says this: > "d:/program files/winzip/wzzip.exe\" -ma test.zip "D:/Program > Files/WebTrends/SmartSource Data Collector/weblog/*.log" > > Which if I paste it onto the command line, does exactly what I intend it to > do. But for some reason, popen2.popen4(cmd) gives this as output ( from > stderr ): > 'd:/program' is not a file or command > > My only guess is that popen2.popen4 is parsing the string differently than > the "print" command does, because print recognizes that the backslash is > escaping the double quotes ( e.g. "\"" ) in the string, and popen does not. > On the other hand, it appears to be recognizing it in my first example, so > that is what is really confusing me. It isn't consistent at all. > > Any ideas? > > > > John A. Gooch > "May the Python-force be with you...always." > Systems Administrator > EchoStar Satellite L.L.C. > Desk: 720-514-5708 > > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Danny Yoo > Sent: Tuesday, June 14, 2005 4:21 PM > To: Pujo Aji > Cc: Tutor > Subject: Re: [Tutor] can't see emacs timer in action > > > > > On Tue, 14 Jun 2005, Pujo Aji wrote: > > >>I tried this code in emacs. >>for i in range(3): >> time.sleep(1) >> print i >> >>It shows the result but total result not second per second. > > > Hi Pujo, > > > In Emacs, you may want to first start up a Python subprocess by using the > keystroke: > > C-c ! > > and then run Python buffers with: > > C-c C-c > > Best of wishes! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Wed Jun 15 20:30:30 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Jun 2005 13:30:30 -0500 Subject: [Tutor] Process problem In-Reply-To: References: Message-ID: <42B073C6.5070006@h-lab.net> Hi Alberto, Mmm I'm not sure if I get this all right. Why do you want to keep cotascamon running after levantamuertos dies?? If you're using system(), levantamuertos is waiting for cotascamon to finish completion before it continues running, there should be no point where levantamuertos *runs* while cotascamon also does (levantamuertos is sleeping) One advice though: it is easier and more elegant if you, instead of parsing the output of "ps" for a single process, you send it signal 0. This will do nothing to the process itself, but will complain with a traceback (OSError) if the pid does not exist. Like this: from os import kill from signals import SIG_DFL pid = 16 try: kill(pid, SIG_DFL) except OSError: print "Process does not exist..." Please note this is untested as I'm os a Windows machine right now.... =/ Hope it helps, Hugo Alberto Troiano wrote: > Hey all > > I have a problem with a program > > You see, I have a python script made in Python 2.2 that runs every 15 > minutes on Linux Red Hat 9.0 > This program (which code is attached below) named levantamuertos.py (spanish > for death weakener) has to check in a database if the pids stored are > running (note that it will be more than one pid) and if they are not it has > to start again the process and it will store the new pid on the database > > The problem is that when I call it it runs and weaks all dead process but > when it dies, he takes all his sons with him. > > How can I make that the cotascamon.py keep running although > levantamuertos.py die? > > Thanks in advanced and here is the code > > Alberto > > ################## > ### levantamuertos.py ### > ################## > import os > import sys > import MySQLdb > import time > > class conexion(object): > def __init__(self): > self.db = MySQLdb.connect(host="localhost", user="administrador", > passwd="123456",db="seguridad") > > def consulta(self,query,args=None): > try: > self.cursor=self.db.cursor() > self.sql=self.cursor.execute(query,args) > except: > self.cerrar() > else: > self.cerrar() > > def cerrar(self): > self.db.close() > > query="SELECT PID,user,cam,ruta from proceso where user='DMALAKIAN'" > cur=conexion() > cur.consulta(query) > res=cur.cursor.fetchall() > if len(res)>0: > for elem in res: > pi=elem[0] > ps_command = 'ps -p %s' % pi > pidchk = os.popen(ps_command).readlines() > count = 0 > for line in pidchk: > count +=1 > if count > 1: > print "Encontre el proceso" > else: > query="update proceso set PID=%s where user='DMALAKIAN'" > p=os.getpid() > args=(p) > cur=conexion() > cur.consulta(query,args) > query="SELECT PID,user,cam,ruta from proceso where user <> > 'DMALAKIAN'" > cur=conexion() > cur.consulta(query) > res=cur.cursor.fetchall() > if len(res)>0: > for elem in res: > pid=elem[0] > user=elem[1] > cam=elem[2] > ruta=str(elem[3]) > ps_command = 'ps -p %s' % pid > pidchk = os.popen(ps_command).readlines() > count = 0 > for line in pidchk: > count +=1 > if count > 1: > pass > else: > os.system("python2.2 /root/cotascamon.py > "+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) > else: > pass > else: > query="insert into proceso values('DMALAKIAN',0,%s,'NO HAY RUTA PARA > ESTE USUARIO')" > p=os.getpid() > args=(p) > cur=conexion() > cur.consulta(query,args) > query="SELECT PID,user,cam,ruta from proceso where user <> 'DMALAKIAN'" > cur=conexion() > cur.consulta(query) > res=cur.cursor.fetchall() > if len(res)>0: > for elem in res: > pid=elem[0] > user=elem[1] > cam=elem[2] > ruta=str(elem[3]) > ps_command = 'ps -p %s' % pid > pidchk = os.popen(ps_command).readlines() > count = 0 > for line in pidchk: > count +=1 > if count > 1: > pass > else: > os.system("python2.2 /root/cotascamon.py > "+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) > else: > pass > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Wed Jun 15 20:39:03 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Jun 2005 13:39:03 -0500 Subject: [Tutor] check PID In-Reply-To: References: Message-ID: <42B075C7.6010401@h-lab.net> Hi Alberto, Since then I've come across the very neat kill(pid, 0) trick, which I replied to you in another post. Hugo Alberto Troiano wrote: > Hey all > > I want to check if a PID number is running > I have the pid number from other program and I want to check if it's alive > Using Python 2.2 over Linux Red Hat 9 > > I tried to google but find how to know process of the app but not check for > other pids > > Thanks ina dvanced > > Alberto > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From phillip.hart at gmail.com Wed Jun 15 21:31:55 2005 From: phillip.hart at gmail.com (Phillip Hart) Date: Wed, 15 Jun 2005 14:31:55 -0500 Subject: [Tutor] Buttons automatically executing Message-ID: <560fda42050615123127e0dfd@mail.gmail.com> Thanks for taking the time to read this. Excuse me if this falls under the boundaries of a "newbie" question, as I am a self-taught programmer. While using Tkinter to create buttons, something unexpected happens when the button commands call functions. Namely, when I run the following, it immediately executes the print statements without the button ever being pressed. Additionally, pressing the button once the Tk window is up will not activate the button. #!usr/bin/python from Tkinter import * def location(x,y): print "I am in row ",x," and column ",y root=Tk() root.geometry('300x300') can=Canvas(root,width=250, height=250) bimage=PhotoImage(file='sq1.gif') b1=Button(can,bg="black",image=bimage,command=location(0,0)).grid(row=0,column=0) can.pack() root.mainloop() Lastly, when I change the command to be anything other than a function, such as a print statement, it works fine. What am I doing wrong here? thanks again for your time and help, green python user (no pun intended), -Phillip -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050615/262de50b/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Jun 15 23:33:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 15 Jun 2005 14:33:04 -0700 (PDT) Subject: [Tutor] Buttons automatically executing In-Reply-To: <560fda42050615123127e0dfd@mail.gmail.com> Message-ID: On Wed, 15 Jun 2005, Phillip Hart wrote: > Thanks for taking the time to read this. > > Excuse me if this falls under the boundaries of a "newbie" question, as > I am a self-taught programmer. Hi Phillip, It's a "newbie" question. But that's perfectly ok. *grin* > While using Tkinter to create buttons, something unexpected happens when > the button commands call functions. Namely, when I run the following, it > immediately executes the print statements without the button ever being > pressed. Additionally, pressing the button once the Tk window is up will > not activate the button. The issue is that there's a difference between calling a function, and getting a function value. Let's go through an example to get started: For example, let's say that we do have that 'location' function defined: ####### >>> def location(x, y): ... print "I am in row", x, "and column", y ... ####### A function value is what we get when we don't use parentheses: ####### >>> location ####### And this thing can be handled just like any other value in Python: we can pass it around and put it in lists: ####### >>> somelist = [location, location, location] >>> somelist [, , ] ####### One neat thing that you already know about functions is that they can be called. You're used to doing something like this: ####### >>> location(3, 4) I am in row 3 and column 4 ####### but we can also do something like this: ####### >>> somelist[0] >>> somelist[0](2, 3) I am in row 2 and column 3 ####### That is, 'somelist[0]' is a function value, and when we use parens next to it '(2, 3)', then we fire off that function value with those two arguments. Does this make sense so far? When we're constructing a button: b1=Button(can,bg="black",image=bimage,command=location(0,0)) we should be careful to pass a function value as the 'command': if we use parens prematurely, what ends up happening is that command gets set to the return value of calling 'location(0, 0)'. It looks we want to set 'command' to a function value that, when called, does a 'location(0,0)'. We can do that: ####### def reset(): location(0, 0) b1 = Button(can,bg="black",image=bimage,command=reset) ####### 'reset' is a function that, when called, does location(0, 0). Please feel free to ask more questions about this. Good luck to you! From klappnase at freenet.de Wed Jun 15 23:43:26 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 15 Jun 2005 23:43:26 +0200 Subject: [Tutor] Buttons automatically executing In-Reply-To: <560fda42050615123127e0dfd@mail.gmail.com> References: <560fda42050615123127e0dfd@mail.gmail.com> Message-ID: <20050615234326.6d6e0c31.klappnase@freenet.de> On Wed, 15 Jun 2005 14:31:55 -0500 Phillip Hart wrote: Hi Phillip, > #!usr/bin/python > > from Tkinter import * > > def location(x,y): > print "I am in row ",x," and column ",y > > > root=Tk() > root.geometry('300x300') > can=Canvas(root,width=250, height=250) > > bimage=PhotoImage(file='sq1.gif') > > b1=Button(can,bg="black",image=bimage,command=location(0,0)).grid(row=0,column=0) That's an error which frequently happens to Tkinter beginners. When you assign the button's command like this the command is executed immediately after button creation, the correct usage is: b1 = Button(can, command=location) without the parentheses; however if you need to pass arguments to the callback, you can use a lambda expression like this: b1 = Button(can, command = lambda x=0, y=0 : location(x, y)) Another problem in this line that doesn't matter here, but might cause confusion later on is the use of grid() ; note that grid() returns None, so actually you set your variable b1 to None which is probably not what you intended; if you need to keep a reference to the Button object you need to split the above into two statements: b1 = Button(can, ) b1.grid() If you don't need a reference you can simply do: Button(can,).grid(row=0,column=0) without creating a (quite useless) variable. I hope this helps Michael From albertito_g at hotmail.com Thu Jun 16 00:04:48 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 15 Jun 2005 22:04:48 +0000 Subject: [Tutor] Process problem In-Reply-To: <42B073C6.5070006@h-lab.net> Message-ID: Hey Let me make you understand I need that levantamuertos.py run cotascamon.py (every script with it differents arguments that are passed) and then die letting the cotascamon.py scripts running independently Now, I don't know if my code is right, and thinking now you're right, levantamuertos.py waits until cotascamon.py finish. What can I do since cotascamon will never die (and it doesn't have to die)? Maybe a different approach will be the solution but I can't find a way to do it Best Regards Alberto >From: Hugo Gonz?lez Monteverde >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Process problem >Date: Wed, 15 Jun 2005 13:30:30 -0500 > >Hi Alberto, > >Mmm I'm not sure if I get this all right. Why do you want to keep >cotascamon running after levantamuertos dies?? If you're using system(), >levantamuertos is waiting for cotascamon to finish completion before it >continues running, there should be no point where levantamuertos *runs* >while cotascamon also does (levantamuertos is sleeping) > >One advice though: it is easier and more elegant if you, instead of >parsing the output of "ps" for a single process, you send it signal 0. >This will do nothing to the process itself, but will complain with a >traceback (OSError) if the pid does not exist. Like this: > >from os import kill >from signals import SIG_DFL > >pid = 16 >try: > kill(pid, SIG_DFL) >except OSError: > print "Process does not exist..." > >Please note this is untested as I'm os a Windows machine right now.... =/ > > >Hope it helps, > >Hugo > > > >Alberto Troiano wrote: >>Hey all >> >>I have a problem with a program >> >>You see, I have a python script made in Python 2.2 that runs every 15 >>minutes on Linux Red Hat 9.0 >>This program (which code is attached below) named levantamuertos.py >>(spanish for death weakener) has to check in a database if the pids stored >>are running (note that it will be more than one pid) and if they are not >>it has to start again the process and it will store the new pid on the >>database >> >>The problem is that when I call it it runs and weaks all dead process but >>when it dies, he takes all his sons with him. >> >>How can I make that the cotascamon.py keep running although >>levantamuertos.py die? >> >>Thanks in advanced and here is the code >> >>Alberto >> >>################## >>### levantamuertos.py ### >>################## >>import os >>import sys >>import MySQLdb >>import time >> >>class conexion(object): >> def __init__(self): >> self.db = MySQLdb.connect(host="localhost", user="administrador", >>passwd="123456",db="seguridad") >> >> def consulta(self,query,args=None): >> try: >> self.cursor=self.db.cursor() >> self.sql=self.cursor.execute(query,args) >> except: >> self.cerrar() >> else: >> self.cerrar() >> >> def cerrar(self): >> self.db.close() >> >>query="SELECT PID,user,cam,ruta from proceso where user='DMALAKIAN'" >>cur=conexion() >>cur.consulta(query) >>res=cur.cursor.fetchall() >>if len(res)>0: >> for elem in res: >> pi=elem[0] >> ps_command = 'ps -p %s' % pi >> pidchk = os.popen(ps_command).readlines() >> count = 0 >> for line in pidchk: >> count +=1 >> if count > 1: >> print "Encontre el proceso" >> else: >> query="update proceso set PID=%s where user='DMALAKIAN'" >> p=os.getpid() >> args=(p) >> cur=conexion() >> cur.consulta(query,args) >> query="SELECT PID,user,cam,ruta from proceso where user <> >>'DMALAKIAN'" >> cur=conexion() >> cur.consulta(query) >> res=cur.cursor.fetchall() >> if len(res)>0: >> for elem in res: >> pid=elem[0] >> user=elem[1] >> cam=elem[2] >> ruta=str(elem[3]) >> ps_command = 'ps -p %s' % pid >> pidchk = os.popen(ps_command).readlines() >> count = 0 >> for line in pidchk: >> count +=1 >> if count > 1: >> pass >> else: >> os.system("python2.2 /root/cotascamon.py >>"+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) >> else: >> pass >>else: >> query="insert into proceso values('DMALAKIAN',0,%s,'NO HAY RUTA PARA >>ESTE USUARIO')" >> p=os.getpid() >> args=(p) >> cur=conexion() >> cur.consulta(query,args) >> query="SELECT PID,user,cam,ruta from proceso where user <> >>'DMALAKIAN'" >> cur=conexion() >> cur.consulta(query) >> res=cur.cursor.fetchall() >> if len(res)>0: >> for elem in res: >> pid=elem[0] >> user=elem[1] >> cam=elem[2] >> ruta=str(elem[3]) >> ps_command = 'ps -p %s' % pid >> pidchk = os.popen(ps_command).readlines() >> count = 0 >> for line in pidchk: >> count +=1 >> if count > 1: >> pass >> else: >> os.system("python2.2 /root/cotascamon.py >>"+str(ruta[19:len(ruta)])+" "+user+" "+str(cam)) >> else: >> pass >> >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > Gaucho From chuck at freshsources.com Thu Jun 16 00:55:44 2005 From: chuck at freshsources.com (Chuck Allison) Date: Wed, 15 Jun 2005 16:55:44 -0600 Subject: [Tutor] Popen4 and Paths Containing Spaces In-Reply-To: <42B07175.50105@h-lab.net> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D49E@riv-excha5.echostar.com> <42B07175.50105@h-lab.net> Message-ID: <92445514.20050615165544@freshsources.com> Hello Hugo, Wednesday, June 15, 2005, 12:20:37 PM, you wrote: HGM> This problem is explained there. Also, why are you using those forward HGM> slashes in your Windows paths???? Meaning: d:/program HGM> files/winzip/wzzip.exe Windows doesn't care. The only place you can't use forward slashes in path names is in a command prompt. It's been that way since DOS 2.0 in the 80s. I prefer using the forward slashes in file name strings since they're fairly portable. -- Best regards, Chuck From typetext at gmail.com Thu Jun 16 05:19:00 2005 From: typetext at gmail.com (typetext) Date: Wed, 15 Jun 2005 20:19:00 -0700 Subject: [Tutor] A newbie question about running python scripts Message-ID: <941480980506152019319eebde@mail.gmail.com> I am trying to run my first python scripts from a windows XP command line, and using Ivan Langhan's book Teach yourself python in 24 hours. I have installed Active Python 2.4 and have had no trouble running the scripts in the IDE . Following the instructions for running from a command line, I type, for instance, Python, which brings up the correct info and the ">> line". Then I type, for example, helloworld.py., the name of the first script. Here is input, followed by what happens: >>>helloworld.py Traceback (most recent call last) File "", line 1 in ? NameError:name 'helloworld' is not defined >>> I know this must be a simple problem, but none of my saved scripts work . They all work in the IDE mode. Would appreciate any help. Michael Riggs Seattle From chuck at freshsources.com Thu Jun 16 05:23:13 2005 From: chuck at freshsources.com (Chuck Allison) Date: Wed, 15 Jun 2005 21:23:13 -0600 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <941480980506152019319eebde@mail.gmail.com> References: <941480980506152019319eebde@mail.gmail.com> Message-ID: <42B0F0A1.4060303@freshsources.com> Dear Tutors, Here is a query from a student from a corporate class I'm teaching. Do you know of any such modules of the top of your head? Thanks! === Quick question since the next class isn't until Monday. Do you know of any modules in Python that can convert a bitmap from one format to another, specifically .BMPs to .JPGs? We have a need to do this conversion. Our developers have grown fond of screen shots as they give much information that may not be written up in a bug. However, our most common tool for getting a screen shot is a screen capture in VMWare which only does .BMP format files. They are about 2.3 Mb apiece. Where as a .JPG of the same thing is only about 34 - 175 Kb. The space savings is significant. So, we need a way of efficiently convert these screenshots. This class presents me an opportunity to create a utility to do this for us. Hence, the question. === -- Chuck Allison From zamb at saudi.net.sa Thu Jun 16 06:43:44 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 16 Jun 2005 07:43:44 +0300 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <42B0F0A1.4060303@freshsources.com> References: <941480980506152019319eebde@mail.gmail.com> <42B0F0A1.4060303@freshsources.com> Message-ID: <1118897024.12585.8.camel@localhost.localdomain> On Wed, 2005-06-15 at 21:23 -0600, Chuck Allison wrote: > Dear Tutors, > > Here is a query from a student from a corporate class I'm teaching. Do > you know of any such modules of the top of your head? Thanks! > > === > Quick question since the next class isn't until Monday. Do you know of > any modules in Python that can convert a bitmap from one format to > another, specifically .BMPs to .JPGs? > > We have a need to do this conversion. Our developers have grown fond of > screen shots as they give much information that may not be written up in > a bug. However, our most common tool for getting a screen shot is a > screen capture in VMWare which only does .BMP format files. They are > about 2.3 Mb apiece. Where as a .JPG of the same thing is only about > 34 - 175 Kb. The space savings is significant. So, we need a way of > efficiently convert these screenshots. This class presents me an > opportunity to create a utility to do this for us. Hence, the question. > === > > -- Chuck Allison PIL? (Portable Image Library) will do what you want. However, I have some humble advice to give. It appears to me that you're using those screen shots to read (as in Humans reading English) some info from the application. Using JPEG format in these situations is not recommended as JPEG is a lossy format (in other words, it introduce some artifacts to the image) which make it very hard for reading (especially, small fonts). I recommend using either PNG or BMP after compressing it with zip, gzip, or bz2. Links: 1. http://www.pythonware.com/products/pil/ Just my humble answer. Ziyad. From zamb at saudi.net.sa Thu Jun 16 06:49:57 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 16 Jun 2005 07:49:57 +0300 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <941480980506152019319eebde@mail.gmail.com> References: <941480980506152019319eebde@mail.gmail.com> Message-ID: <1118897397.12762.1.camel@localhost.localdomain> On Wed, 2005-06-15 at 20:19 -0700, typetext wrote: > I am trying to run my first python scripts from a windows XP command > line, and using Ivan Langhan's book Teach yourself python in 24 hours. > I have installed Active Python 2.4 and have had no trouble running the > scripts in the IDE . Following the instructions for running from a > command line, I type, for instance, Python, which brings up the > correct info and the ">> line". Then I type, for example, > helloworld.py., the name of the first script. Here is input, followed > by what happens: > > >>>helloworld.py > Traceback (most recent call last) > File "", line 1 in ? > NameError:name 'helloworld' is not defined > >>> > > I know this must be a simple problem, but none of my saved scripts > work . They all work in the IDE mode. Would appreciate any help. > > Michael Riggs > Seattle Within the directory where ?helloworld.py? is: 1. Either from a Windows command prompt type: ?python helloworld.py? (this is the recommended/right way to run Python applications/scripts), or 2. From the Python interactive shell after the ?>>> ? prompt, type: ?import helloworld? (very useful in some situations). Ziyad. From klappnase at freenet.de Thu Jun 16 12:19:12 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu, 16 Jun 2005 12:19:12 +0200 Subject: [Tutor] Process problem In-Reply-To: References: <42B073C6.5070006@h-lab.net> Message-ID: <20050616121912.0eecac20.klappnase@freenet.de> On Wed, 15 Jun 2005 22:04:48 +0000 "Alberto Troiano" wrote: Hi Alberto, > Hey > > Let me make you understand > > I need that levantamuertos.py run cotascamon.py (every script with it > differents arguments that are passed) and then die letting the cotascamon.py > scripts running independently > > Now, I don't know if my code is right, and thinking now you're right, > levantamuertos.py waits until cotascamon.py finish. > What can I do since cotascamon will never die (and it doesn't have to die)? > > Maybe a different approach will be the solution but I can't find a way to do > it > > Best Regards > > Alberto > I didn't follow the thread completely, so maybe I missed something, but if the problem is that python waits until the os.system() calls are finished, I think adding a "&" to the command to make it run in the background should do the trick. Best regards Michael From albertito_g at hotmail.com Thu Jun 16 14:45:17 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 16 Jun 2005 12:45:17 +0000 Subject: [Tutor] Process problem In-Reply-To: <20050616121912.0eecac20.klappnase@freenet.de> Message-ID: Thanks for the reply That was one of the problems Now the other problem is that when the script finishes all processes (runing in the background or not) finishes with him. levantamuertos.py is supoosed to be a process manager for cotascamon.py I need levantamuertos.py run, start the cotascamons.py that are dead, let them running and then die letting the others alive How can I do this? Best Regards Alberto >From: Michael Lange >To: tutor at python.org >Subject: Re: [Tutor] Process problem >Date: Thu, 16 Jun 2005 12:19:12 +0200 > >On Wed, 15 Jun 2005 22:04:48 +0000 >"Alberto Troiano" wrote: > >Hi Alberto, > > > Hey > > > > Let me make you understand > > > > I need that levantamuertos.py run cotascamon.py (every script with it > > differents arguments that are passed) and then die letting the >cotascamon.py > > scripts running independently > > > > Now, I don't know if my code is right, and thinking now you're right, > > levantamuertos.py waits until cotascamon.py finish. > > What can I do since cotascamon will never die (and it doesn't have to >die)? > > > > Maybe a different approach will be the solution but I can't find a way >to do > > it > > > > Best Regards > > > > Alberto > > > >I didn't follow the thread completely, so maybe I missed something, but if >the problem >is that python waits until the os.system() calls are finished, I think >adding a "&" to >the command to make it run in the background should do the trick. > >Best regards > >Michael > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From albertito_g at hotmail.com Thu Jun 16 15:09:08 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 16 Jun 2005 13:09:08 +0000 Subject: [Tutor] Process problem In-Reply-To: <20050616121912.0eecac20.klappnase@freenet.de> Message-ID: Hey all Nevermind, it worked with the & trick. I just posted because the first 2 times didn't do anything but there was an error in the crontab so... Thanks to all who helped Best regards Alberto >Thanks for the reply > >That was one of the problems >Now the other problem is that when the script finishes all processes >(runing in the background or >not) finishes with him. levantamuertos.py is >supoosed to be a process manager for cotascamon.py > >I need levantamuertos.py run, start the cotascamons.py that are dead, let >them running and then >die letting the others alive > >How can I do this? > >Best Regards > >Alberto >From: Michael Lange >To: tutor at python.org >Subject: Re: [Tutor] Process problem >Date: Thu, 16 Jun 2005 12:19:12 +0200 > >On Wed, 15 Jun 2005 22:04:48 +0000 >"Alberto Troiano" wrote: > >Hi Alberto, > > > Hey > > > > Let me make you understand > > > > I need that levantamuertos.py run cotascamon.py (every script with it > > differents arguments that are passed) and then die letting the >cotascamon.py > > scripts running independently > > > > Now, I don't know if my code is right, and thinking now you're right, > > levantamuertos.py waits until cotascamon.py finish. > > What can I do since cotascamon will never die (and it doesn't have to >die)? > > > > Maybe a different approach will be the solution but I can't find a way >to do > > it > > > > Best Regards > > > > Alberto > > > >I didn't follow the thread completely, so maybe I missed something, but if >the problem >is that python waits until the os.system() calls are finished, I think >adding a "&" to >the command to make it run in the background should do the trick. > >Best regards > >Michael > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From arcege at gmail.com Thu Jun 16 15:18:51 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Thu, 16 Jun 2005 09:18:51 -0400 Subject: [Tutor] Process problem In-Reply-To: References: <20050616121912.0eecac20.klappnase@freenet.de> Message-ID: <7e5ba92205061606187fe59622@mail.gmail.com> On 6/16/05, Alberto Troiano wrote: > > Hey all > > Nevermind, it worked with the & trick. > I just posted because the first 2 times didn't do anything but there was > an > error in the crontab so... > Alberto, If you are going to use put the processes in the background with the ampersand ('&'), then you probably want to use 'nohup' as well in the os.system() call: os.system("nohup %s >/dev/null 2>&1 &" % cmd) This may save some headaches later. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050616/2226337b/attachment.htm From webdev at matheteuo.org Thu Jun 16 17:02:37 2005 From: webdev at matheteuo.org (Don Parris) Date: Thu, 16 Jun 2005 11:02:37 -0400 Subject: [Tutor] Clearing the Console Screen Message-ID: <20050616110237.3de41ed9@luke.matheteuo.rel> With the console-based menu system I'm building, I'd like to clear the screen for each menu call - something like: def main_menu(): clear #start with a fresh console screen, menu at top print menuitems This way, the users won't have to get too confused by all the previous screens. I haven't found the correct way to do this so far. You can point me to the documentation, and I'll play with that. Thanks, Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From zamb at saudi.net.sa Thu Jun 16 16:55:36 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 16 Jun 2005 17:55:36 +0300 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <94148098050616072319c7eb01@mail.gmail.com> References: <941480980506152019319eebde@mail.gmail.com> <1118897397.12762.1.camel@localhost.localdomain> <94148098050616072319c7eb01@mail.gmail.com> Message-ID: <1118933736.12987.2.camel@localhost.localdomain> On Thu, 2005-06-16 at 07:23 -0700, typetext wrote: > Thank you for responding. Here is what happens when I type python > helloworld.py without any quotation marks into the command line:1. > The prompt line reads > 1.C:\Documents and Settings\Micky > 2. I type "python" > 3. the python prompt comes up Active Python 2.4.1 > 4. then I type "helloworld.py" > 5. Then I get " Traceback (most recent call last) > > > File "", line 1 in ? > > > NameError:name 'helloworld' is not defined" > > Do you have any ideas on this? It looks to me as if that ought to > work, but it doesn't. I would really appreciate some help. Perhaps I > need to put in a file path name, or reinstall Python 2.4.1? > Michael Riggs No. You don't need to go into Python's interactive shell (the one with the ">>> " prompt) to run the script. Just type the following two lines exactly: cd "C:\Documents and Settings\Micky" python helloworld.py And that's all! Tell us what you get. Ziyad. From cyresse at gmail.com Thu Jun 16 17:05:20 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri, 17 Jun 2005 03:05:20 +1200 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <20050616110237.3de41ed9@luke.matheteuo.rel> References: <20050616110237.3de41ed9@luke.matheteuo.rel> Message-ID: One way is to - print * 25 but that's probably not the best. You could check out Pythoncard for a simple GUI builder - pythoncard.sourceforge.net - but it's a leap into the OO stuff. On 6/17/05, Don Parris wrote: > > With the console-based menu system I'm building, I'd like to clear the > screen for each menu call - something like: > > def main_menu(): > clear #start with a fresh console screen, menu at top > print menuitems > > > This way, the users won't have to get too confused by all the previous > screens. > > I haven't found the correct way to do this so far. You can point me to the > documentation, and I'll play with that. > > Thanks, > Don > -- > evangelinux GNU Evangelist > http://matheteuo.org/ http://chaddb.sourceforge.net/ > "Free software is like God's love - you can share it with anyone anytime > anywhere." > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050617/848ba0d2/attachment.htm From kent37 at tds.net Thu Jun 16 17:16:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 11:16:37 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <20050616110237.3de41ed9@luke.matheteuo.rel> References: <20050616110237.3de41ed9@luke.matheteuo.rel> Message-ID: <42B197D5.60904@tds.net> Don Parris wrote: > With the console-based menu system I'm building, I'd like to clear the > screen for each menu call - something like: > > def main_menu(): > clear #start with a fresh console screen, menu at top > print menuitems There is no nice portable way to do this. On Windows running in a DOS window (not in IDLE or another GUI environment) you can use import os os.system('cls') Kent From zamb at saudi.net.sa Thu Jun 16 18:03:05 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 16 Jun 2005 19:03:05 +0300 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <94148098050616080839c6c47f@mail.gmail.com> References: <941480980506152019319eebde@mail.gmail.com> <1118897397.12762.1.camel@localhost.localdomain> <94148098050616072319c7eb01@mail.gmail.com> <1118933736.12987.2.camel@localhost.localdomain> <94148098050616080839c6c47f@mail.gmail.com> Message-ID: <1118937785.13106.27.camel@localhost.localdomain> On Thu, 2005-06-16 at 08:08 -0700, typetext wrote: > I get exactly the same error message as below. What could be going on > here? To check that I am not misspelling the name, I also wrote a > script that says print "helloworld" and saved it as hello.py. The same > message comes up then, as well. Any input is appreciated.. > Michael Riggs, Seattle. > There seems to be some miss-understanding on what's going on! It seems to me that you're typing "python", hitting Enter key, then typing "helloworkd.py" *inside* the Python interactive shell and that's *not* what I said! All you need to type is "python helloworld.py", then hit the Enter key. Of course, you need to be inside the directory that holds that file. Just start a command prompt, type "cd C:\Documents and Settings\Micky", hit Enter, type "python helloworld.py", hit Enter and your script should run fine. If you get anything else, just repost here again. Do *not* let this get in your way of learning! If I (or anyone else on this list) didn't want to help you, we wouldn't responded to your questions in the first place. Ziyad. From CKOSTYN at Indygov.org Thu Jun 16 18:03:35 2005 From: CKOSTYN at Indygov.org (Catherine Kostyn) Date: Thu, 16 Jun 2005 11:03:35 -0500 Subject: [Tutor] A newbie question about running python scripts (Out of the Office June 16) Message-ID: I will be out of the office on June 16, to return on June 17. I will reply to your message at that time. Catherine Kostyn Transportation Planner Indianapolis MPO 200 E. Washington St., Ste. 1821 Indianapolis, IN 46204 (317)327-5142 From webdev at matheteuo.org Thu Jun 16 18:27:18 2005 From: webdev at matheteuo.org (Don Parris) Date: Thu, 16 Jun 2005 12:27:18 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <42B197D5.60904@tds.net> References: <20050616110237.3de41ed9@luke.matheteuo.rel> <42B197D5.60904@tds.net> Message-ID: <20050616122718.562c6c47@luke.matheteuo.rel> On Thu, 16 Jun 2005 11:16:37 -0400 Kent Johnson wrote: > Don Parris wrote: > > With the console-based menu system I'm building, I'd like to clear the > > screen for each menu call - something like: > > > > def main_menu(): > > clear #start with a fresh console screen, menu at top > > print menuitems > > There is no nice portable way to do this. On Windows running in a DOS > window (not in IDLE or another GUI environment) you can use import os > os.system('cls') > > Kent > > > _______________________________________________ Thanks! I thought there had to be a way to call the OS' clear screen command, but was going about it the wrong way. I was trying to use sys.clear instead of os.system. Would it be difficult to test the OS, store the result in a variable, and call the comand based on the variable result? Or would it be simpler to have users edit the script for their OS? Mind you, there may be other areas where I need an OS-specific command. I'm beginning to get an idea of the challenges of portability though. ;) Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From kent37 at tds.net Thu Jun 16 18:24:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 12:24:32 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <20050616122718.562c6c47@luke.matheteuo.rel> References: <20050616110237.3de41ed9@luke.matheteuo.rel> <42B197D5.60904@tds.net> <20050616122718.562c6c47@luke.matheteuo.rel> Message-ID: <42B1A7C0.5030207@tds.net> Don Parris wrote: > Thanks! I thought there had to be a way to call the OS' clear screen > command, but was going about it the wrong way. I was trying to use > sys.clear instead of os.system. Would it be difficult to test the OS, > store the result in a variable, and call the comand based on the variable > result? Or would it be simpler to have users edit the script for their OS? You could try this (from http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3edf6589c533f78e): import os if os.name == "nt": os.system("cls") # Works in w2k else: os.system("clear") # Works in cygwin's Bash > Mind you, there may be other areas where I need an OS-specific command. I'm > beginning to get an idea of the challenges of portability though. ;) Python actually gets a lot of this right, you may find it's easier than you think to write portable Python. Kent From typetext at gmail.com Thu Jun 16 18:28:35 2005 From: typetext at gmail.com (typetext) Date: Thu, 16 Jun 2005 09:28:35 -0700 Subject: [Tutor] A newbie question about running python scripts In-Reply-To: <1118937785.13106.27.camel@localhost.localdomain> References: <941480980506152019319eebde@mail.gmail.com> <1118897397.12762.1.camel@localhost.localdomain> <94148098050616072319c7eb01@mail.gmail.com> <1118933736.12987.2.camel@localhost.localdomain> <94148098050616080839c6c47f@mail.gmail.com> <1118937785.13106.27.camel@localhost.localdomain> Message-ID: <9414809805061609282d2c8075@mail.gmail.com> . Here's what happened. I had forgotten to specify the following, and therefore was not inside the proper directory. What worked was cd c:\documents and settings\my documents\ then enter, then python helloworld.py. Success! Onward and upward. I was missing the "my documents" part, and therefore was not inside the proper directory. Michael Riggs On 6/16/05, ZIYAD A. M. AL-BATLY wrote: > On Thu, 2005-06-16 at 08:08 -0700, typetext wrote: > > I get exactly the same error message as below. What could be going on > > here? To check that I am not misspelling the name, I also wrote a > > script that says print "helloworld" and saved it as hello.py. The same > > message comes up then, as well. Any input is appreciated.. > > Michael Riggs, Seattle. > > > There seems to be some miss-understanding on what's going on! It seems > to me that you're typing "python", hitting Enter key, then typing > "helloworkd.py" *inside* the Python interactive shell and that's *not* > what I said! > > All you need to type is "python helloworld.py", then hit the Enter key. > Of course, you need to be inside the directory that holds that file. > > Just start a command prompt, type "cd C:\Documents and Settings\Micky", > hit Enter, type "python helloworld.py", hit Enter and your script should > run fine. > > > If you get anything else, just repost here again. Do *not* let this get > in your way of learning! If I (or anyone else on this list) didn't want > to help you, we wouldn't responded to your questions in the first place. > > Ziyad. > From arcege at gmail.com Thu Jun 16 18:38:29 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Thu, 16 Jun 2005 12:38:29 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <20050616122718.562c6c47@luke.matheteuo.rel> References: <20050616110237.3de41ed9@luke.matheteuo.rel> <42B197D5.60904@tds.net> <20050616122718.562c6c47@luke.matheteuo.rel> Message-ID: <7e5ba9220506160938718eaef3@mail.gmail.com> On 6/16/05, Don Parris wrote: > > > Thanks! I thought there had to be a way to call the OS' clear screen > command, but was going about it the wrong way. I was trying to use > sys.clear instead of os.system. Would it be difficult to test the OS, > store the result in a variable, and call the comand based on the variable > result? Or would it be simpler to have users edit the script for their OS? > > Mind you, there may be other areas where I need an OS-specific command. > I'm > beginning to get an idea of the challenges of portability though. ;) > > Don > You might want to use the tput command. It returns control sequences for the terminal that are used by all programs, e.g. emacs, vi(m). Your could capture the output with the commands module and send it to the terminal with stdout.write (instead of print). import commands clear_str = None def clearscreen(): global clear_str from sys import stdout if not clear_str: clear_str = commands.getoutput('tput clear') stdout.write(clear_str) clearscreen() If you wanted, you could encapsulate this into a module or a class. This would work on just about any UNIX/Linux/BSD system, and might work on Mac OS/X (I don't know if they use terminfo). You can use the other tput subcommands in your program if you wished as well. (Hide the cursor, go to column X row Y, etc.) -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050616/0a9b4d2e/attachment.htm From webdev at matheteuo.org Thu Jun 16 18:54:09 2005 From: webdev at matheteuo.org (Don Parris) Date: Thu, 16 Jun 2005 12:54:09 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <42B1A7C0.5030207@tds.net> References: <20050616110237.3de41ed9@luke.matheteuo.rel> <42B197D5.60904@tds.net> <20050616122718.562c6c47@luke.matheteuo.rel> <42B1A7C0.5030207@tds.net> Message-ID: <20050616125409.62c5d19a@luke.matheteuo.rel> On Thu, 16 Jun 2005 12:24:32 -0400 Kent Johnson wrote: > > Mind you, there may be other areas where I need an OS-specific command. > > I'm beginning to get an idea of the challenges of portability though. ;) > > Python actually gets a lot of this right, you may find it's easier than > you think to write portable Python. > Hmmm, I'm using Python 2.3 on SUSE Linux 9.2 at home, and the latest Python on WinXP at my job (I get to do some non-work-related stuff during my downtime at work). So far, I haven't had any problems running my script on either box. Frankly, I'm finding Python to be quite easy to learn. With a little help from the standard tutorials, this list, and my co-worker (experienced developer), I've managed to get my menu system functioning rather well, and can even connect to the MySQL database to print off a member roster to the console. All this in less than two weeks. I even found a better way to print the menus to the console. These successes are what makes developing a program exciting. Meanwhile, I'll check out that site/code. Again, I appreciate the help. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From albertito_g at hotmail.com Thu Jun 16 22:21:53 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 16 Jun 2005 20:21:53 +0000 Subject: [Tutor] Process problem In-Reply-To: <7e5ba9220506160740631f7e7a@mail.gmail.com> Message-ID: Hey You weren't pedantic at all I needed the explanation 'cause I don't like to make things I don't understand so now I will add the code to mine Thanks Alberto
 Gaucho
>From: "Michael P. Reilly" >Reply-To: "Michael P. Reilly" >To: Alberto Troiano >Subject: Re: [Tutor] Process problem >Date: Thu, 16 Jun 2005 10:40:09 -0400 > >On 6/16/05, Alberto Troiano wrote: > > > > Hey > > > > What its that for? > > > > can you explain me what it does? and the way to implementing it here: > > os.system("python2.2 /root/levantamuertos.py &") > > and what headaches are you talking about? > > > >Hi, > >The 'nohup' command is to make sure that the child process sticks around >after the parent (and grandparents) have died. > >When a process creates a child, the child is tied to the parent and when >the >parent exits, all the child processes get sent a specific signal (with >os.kill()) telling them that the parent has died. The default procedure >when >they receive this signal is to exit. > >A little history: back in the days of only modems, you would dial into a >UNIX mainframe from a terminal and if the modem disconnected, the system >(or >you) would not want all your processes hanging around afterward. For this >reason, the UNIX system would send a "hangup" signal (SIGHUP) to the login >shell and all its child processes. Shells added a "nohup" (no hangup) >command so certain processes could survive if the user wanted. > >When you say "nohup" it tells the process to ignore the default procedure >and to ignore the SIGHUP (hangup signal). It does not put the process in >the >background so you still need the "&" and it does not change stdout and >stderr (that is why I put those in my e-mail too). > >In python, you would just say: >os.system("nohup python2.2 /root/levantamuertos.py >/dev/null 2>&1 &") > >This should handle most headaches. The headaches that I mentioned are going >to be very subtle. > > 1. One is that sometimes developers have changed shells without > telling users. It has happened in the past that "&" has had an implicit > "nohup" in one version of a shell and in the next release, the implict > "nohup" is no longer there. It is better to be explicit and clear... it >also > helps readability. > 2. A second headache comes from the output streams (stdout and > stderr). You want to be running a number of these >levantamuertos.pyprocess at the same time. Did you know that the >output of your cron job is > captured and e-mailed to you? And by default, the output of child >processes > (levantamuertos.py) would be the same as cron job, usually only on > error? So you might get a lot of mixed output from the different > levantamuertos.py processes running at the same time. If you send all > the output to /dev/null. Or to specific log files (based on PID), then >you > may not have this headache. > >I hope this helps and wasn't too pedantic. I get that way sometimes. >-Arcege >-- >There's so many different worlds, >So many different suns. >And we have just one world, >But we live in different ones. From alan.gauld at freenet.co.uk Thu Jun 16 22:53:30 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 16 Jun 2005 21:53:30 +0100 Subject: [Tutor] Controlling Where My Program Ends References: <42B03140.1020003@cso.atmel.com> Message-ID: <005101c572b5$73d7b290$97a28651@xp> > >>Never mind. I found it - sys.exit() You can do the same thing by raise SystemExit This avoids the need to import sys... Alan G. > >> > >>Sorry to have wasted the bandwidth/time. > >>-- > > > > > > This was in reference to a post about exiting from a program. I couldn't > > figure out why my program wouldn't let me exit from within a sub-menu of the > > console interface. Since my webmail client goofed up the "from" header, it > > never showed up, and I've cancelled it to avoid wasting everyone's time > > further. I found sys.exit() in the library reference, which allows me to do > > what I want. > > > > Don > > > > If you use the if __name__ == '__main__': idiom, then you can just use return > instead of sys.exit() > > def main(): > lotsa interesting python code > if somethinorother: > # sys.exit() > return > more interesting python code > > if __name__ == '__main__': > main() > > > From alan.gauld at freenet.co.uk Thu Jun 16 23:00:06 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 16 Jun 2005 22:00:06 +0100 Subject: [Tutor] can't see emacs timer in action References: Message-ID: <006a01c572b6$60684e30$97a28651@xp> > buffer/output pane before running my program, so I always do > this to start my program: > ... > ...6 steps listed > ... > This is one cycle of running. > Is that normal ??? I doubt it, I've never user python mode in emacs but I have used SQL and C++ modes and usually you just call C-c C-c from the code window and the rest all happens magically. But even if you do have to do all of that the sionple solution is to record it as a macro C-x ( keys to press here C-x ) You can execute it again with C-x e And you can save it so that it will be available next time you start emacs. You can also bind it to a shortcut of your own - after all this is emacs you can do anything! :-) > I need to make shortcut for starting interpreter do you have any idea. record and save a macro M-x apropos macro is your friend... Alan G. A one time emacs user... From alan.gauld at freenet.co.uk Thu Jun 16 23:09:31 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 16 Jun 2005 22:09:31 +0100 Subject: [Tutor] Clearing the Console Screen References: <20050616110237.3de41ed9@luke.matheteuo.rel> Message-ID: <00aa01c572b7$b0b8cd50$97a28651@xp> > I haven't found the correct way to do this so far. There is no correct way. Every console is different so you have to adapt. That having been said Fred Lundh has written a console module that tries to hide the diffeent trminal types in a common set of commands - you can download it from his site. The other ways are: Unix/LInux/MacOS/BSD: os.system('clear') DOS/Windows console: os.system('CLS') Generic: print '\n' * 100 # a 100 line screen... Or you could find the control codes for your screen and print them as octal character codes... HTH, Alan G. From alan.gauld at freenet.co.uk Thu Jun 16 23:40:49 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 16 Jun 2005 22:40:49 +0100 Subject: [Tutor] Clearing the Console Screen References: <20050616110237.3de41ed9@luke.matheteuo.rel> <42B197D5.60904@tds.net><20050616122718.562c6c47@luke.matheteuo.rel> <42B1A7C0.5030207@tds.net> Message-ID: <00bf01c572bc$1018dc50$97a28651@xp> > Don Parris wrote: > > Thanks! I thought there had to be a way to call the OS' clear screen > > command, but was going about it the wrong way. I was trying to use > > sys.clear instead of os.system. Would it be difficult to test the OS, > > store the result in a variable, and call the comand based on the variable > > result? Or would it be simpler to have users edit the script for their OS? You can do that and I think thats what Fred Lundh's console program does but its not as simple as that either. Some terminals won't respond to the os clear - for example som Textronic displays only clear in text mode but when in graphics mode (and many folks use them thus to use nicer fonts) they won't clear with 'clear'. The only way to do it is send the graphics control characters... > beginning to get an idea of the challenges of portability though. ;) Portability is a real pain. You can achieve 95% portability with only minimal effort but complete portability (think Palm, Paper teletype, Mainframe 3270 terminal, embedded browser interpreter etc etc) is a very elusive goal indeed. On Unix(*) you do have one other option however which is to use curses. This is a pseudo windowing system which runs on character terminals. It has a default window of the whole screen and allows accurate cursor placement, character deletion, screen clearing, instant character reading etc etc. Its a bit irksome to set up but once initialised not too hard to use. If your app does a lot of screen control - like vim or emacs say, then curses is probably the right approach. (*) There is a DOS curses available for download but I couldn't get it to work properly. The *nix curses module is part of the standard library. (THere is also an O'Reilly book on ncurses - the C version, and several online tutorials for the C version too. The Python module is a pretty straight translation of the C API to Python.) Alan G. > > Python actually gets a lot of this right, you may find it's easier than you think to write portable Python. > > Kent > > > From kent37 at tds.net Fri Jun 17 01:52:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 19:52:24 -0400 Subject: [Tutor] Clearing the Console Screen In-Reply-To: <00aa01c572b7$b0b8cd50$97a28651@xp> References: <20050616110237.3de41ed9@luke.matheteuo.rel> <00aa01c572b7$b0b8cd50$97a28651@xp> Message-ID: <42B210B8.4060206@tds.net> Alan G wrote: >>I haven't found the correct way to do this so far. > > > There is no correct way. Every console is different so you have > to adapt. > That having been said Fred Lundh has written a console module > that tries to hide the diffeent trminal types in a common set > of commands - you can download it from his site. The only one I can find there is for Windows: http://www.effbot.org/zone/console-handbook.htm Kent From olli.rajala at gmail.com Fri Jun 17 08:48:02 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Fri, 17 Jun 2005 09:48:02 +0300 Subject: [Tutor] Checking if value exist in a '2D array' Message-ID: Hi again, I have a '2D array', I mean a list inside a list ([[][],[][],...]) and would need to check if the value exists in it. Of course I could do a for loop, but that just seem to be a little overkill, so is there any other way to do it? I have to check the first cell of every insider list. Here's a little pseudo code if that helps. if list[[x][0]] == 'value': # where x can be anything > 0 print 'found' So, is there a similar method like list.count('value') that I use for 1D lists? Regards, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From ajikoe at gmail.com Fri Jun 17 10:10:41 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 17 Jun 2005 10:10:41 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: <4A98C13F-DFBC-44DA-8211-C7BC18B61DF0@yahoo.fr> Message-ID: Hello Max, the problem with running in a dos console terminal is that I have to switch back and forth from terminal and my xemacs. and I found that in windows dos console we have to specify buffer page. I do need a dynamic buffer control so I don't need to specify the buffer if my program run big things. Do you have an advice? pujo On 6/15/05, Max Noel wrote: > > On Jun 14, 2005, at 23:17, Pujo Aji wrote: > > > I just use Ctrl+C Ctrl+C to run the code. > > The code wait for 3 second and show all i all together. > > > > I can't feel every second pass. > > > > pujo > > Try running your script from a terminal (outside of emacs, that > is). > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From ajikoe at gmail.com Fri Jun 17 10:13:33 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 17 Jun 2005 10:13:33 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: References: Message-ID: Hallo Danny, I tried the emacs folding customization, but it doesn't work. After I did it, my xemacs show tripple dot '...' near the method of class it should be folded. I don't know how to open my method. Sincerely Yours, pujo On 6/15/05, Danny Yoo wrote: > > > On Wed, 15 Jun 2005, Pujo Aji wrote: > > > Thanks Danny, > > > > Btw, I use xemacs now does it has folding class and method capabilities? > > Hi Pujo, > > [Note: in replies, please make sure to put tutor at python.org in CC.] > > > According to: > > http://groups.google.ca/group/comp.lang.python/msg/956f1c2d37f93995?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=2 > > Yes. *grin* > > > From ajikoe at gmail.com Fri Jun 17 10:17:24 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 17 Jun 2005 10:17:24 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: <006a01c572b6$60684e30$97a28651@xp> References: <006a01c572b6$60684e30$97a28651@xp> Message-ID: Hello Alan, thanks for the advice, but I don't understand why xemacs doesn't fix C-c C-c so we don't have to do such many things. in fact C-c C-c is fail to represent the well 'run' behaviour of python ? It would be nice to people who use python get the same benefit of typing C-c C-c and get the result it supposed to have in other languages. pujo On 6/16/05, Alan G wrote: > > buffer/output pane before running my program, so I always do > > this to start my program: > > ... > > ...6 steps listed > > ... > > > This is one cycle of running. > > Is that normal ??? > > I doubt it, I've never user python mode in emacs but I have > used SQL and C++ modes and usually you just call C-c C-c from > the code window and the rest all happens magically. > > But even if you do have to do all of that the sionple solution > is to record it as a macro > > C-x ( > keys to press here > C-x ) > > You can execute it again with > > C-x e > > And you can save it so that it will be available next time > you start emacs. You can also bind it to a shortcut of your > own - after all this is emacs you can do anything! :-) > > > I need to make shortcut for starting interpreter do you have any > idea. > > record and save a macro > > M-x apropos macro > > is your friend... > > Alan G. > A one time emacs user... > > From kent37 at tds.net Fri Jun 17 12:12:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 06:12:10 -0400 Subject: [Tutor] Checking if value exist in a '2D array' In-Reply-To: References: Message-ID: <42B2A1FA.9030200@tds.net> Olli Rajala wrote: > Hi again, > > I have a '2D array', I mean a list inside a list ([[][],[][],...]) and > would need to check if the value exists in it. Of course I could do a > for loop, but that just seem to be a little overkill, so is there any > other way to do it? I have to check the first cell of every insider > list. With Python 2.4: >>> l= [ [1], [2,3], [4,5], [6]] >>> 2 in (i[0] for i in l) True >>> 3 in (i[0] for i in l) False with Python 2.3 use [i[0] for i in l] instead which is a little less efficient. > > Here's a little pseudo code if that helps. > > if list[[x][0]] == 'value': # where x can be anything > 0 > print 'found' > > So, is there a similar method like list.count('value') that I use for 1D lists? I would use 'value' in list rather than list.count('value') because it will stop when it finds 'value'; list.count() will always inspect the whole list. Kent From janos.juhasz at VELUX.com Fri Jun 17 12:58:05 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 17 Jun 2005 12:58:05 +0200 Subject: [Tutor] max(len(item)) for cols In-Reply-To: Message-ID: Dear Guys, I have a 2D array: >>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] How can I get what is the max(len(item)) for the columns ? I would like to get a list with the max_col_width values. I hope that, it can wrote with some nice list comprehension, but I can't do that :( Yours sincerely, ______________________________ J?nos Juh?sz From maxnoel_fr at yahoo.fr Fri Jun 17 13:35:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 17 Jun 2005 12:35:54 +0100 Subject: [Tutor] max(len(item)) for cols In-Reply-To: References: Message-ID: On Jun 17, 2005, at 11:58, J?nos Juh?sz wrote: > > Dear Guys, > > I have a 2D array: > >>>> [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>>> > > > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. > > I hope that, it can wrote with some nice list comprehension, but I > can't do > that :( >>> a = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1]] >>> max(len(item) for item in a) 4 If you're running Python 2.3 or lower, add brackets in the last line: >>> max([len(item) for item in a]) 4 -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Fri Jun 17 13:43:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 07:43:48 -0400 Subject: [Tutor] max(len(item)) for cols In-Reply-To: References: Message-ID: <42B2B774.1020307@tds.net> Max Noel wrote: > On Jun 17, 2005, at 11:58, J?nos Juh?sz wrote: >>I have a 2D array: >> >> >>>>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>>>> >> >> >>How can I get what is the max(len(item)) for the columns ? >>I would like to get a list with the max_col_width values. > > >>> a = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1]] > >>> max(len(item) for item in a) > 4 > > If you're running Python 2.3 or lower, add brackets in the last > line: > >>> max([len(item) for item in a]) > 4 another way: >>> a = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1]] >>> max(map(len, a)) 4 From jfouhy at paradise.net.nz Fri Jun 17 14:35:24 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sat, 18 Jun 2005 00:35:24 +1200 (NZST) Subject: [Tutor] max(len(item)) for cols In-Reply-To: References: Message-ID: <1119011724.42b2c38cdd1d9@www.paradise.net.nz> Quoting J?nos Juh?sz : > > Dear Guys, > > I have a 2D array: > >>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] > > > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. > > I hope that, it can wrote with some nice list comprehension, but I can't > do that :( There is a magic trick: You can use zip(* ) to transpose a two-dimensional array. eg: >>> arr = [[1,2,3], [4,5,6]] >>> zip(*arr) [(1, 4), (2, 5), (3, 6)] >>> zip(*zip(*arr)) [(1, 2, 3), (4, 5, 6)] (if this is not obvious to you, I recommend spending the time to figure out how this works) You can use this to easily get at the columns of your array. And once you have the columns, you can use a list comprehension to get the lengths of the elements and find the max. eg: >>> arr = [['a'*random.randint(1, 10) for i in range(5)] for j in range(10)] >>> pprint.pprint(arr) [['aaaaaa', 'a', 'aaaaaaaaaa', 'aaaa', 'aaaaaaaa'], ['aaaaaaa', 'aaaaaa', 'aaaaaaaaaa', 'aaa', 'aaa'], ['aa', 'aaaaaaa', 'aaaaaaaa', 'aaaaaa', 'aaaaaaa'], ['aaaaaaaa', 'aaaaaa', 'aaaaaaaaaa', 'aa', 'aa'], ['aaaaaaaaaa', 'aaaaa', 'aaaaaa', 'a', 'aaaa'], ['aaaaaaa', 'aaaaaaaaa', 'aaaaaa', 'aaaaa', 'aaaaaaaaaa'], ['aaaa', 'aaaaaaaaa', 'aaaaa', 'aaaa', 'aaaaaaaaaa'], ['aaaaa', 'aaa', 'aaaaaaaaa', 'aa', 'aaaaaaa'], ['aaaaaaaa', 'aaaaaa', 'aaaaaa', 'a', 'aaaaa'], ['aaaaaaaaa', 'aaaaaa', 'aaaaaa', 'aaa', 'aaaaaa']] >>> [max([len(s) for s in l]) for l in zip(*arr)] [10, 9, 10, 6, 10] HTH! -- John. From kent37 at tds.net Fri Jun 17 15:01:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 09:01:27 -0400 Subject: [Tutor] max(len(item)) for cols In-Reply-To: References: Message-ID: <42B2C9A7.1040803@tds.net> J?nos Juh?sz wrote: > Dear Guys, > > I have a 2D array: > >>>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] > > > > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. > > I hope that, it can wrote with some nice list comprehension, but I can't do > that :( Ah, thanks jfouhy for correctly understanding the question! If you are doing this because you want to pretty-print a table, you may be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent From janos.juhasz at VELUX.com Fri Jun 17 15:16:30 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 17 Jun 2005 15:16:30 +0200 Subject: [Tutor] max(len(item)) for cols In-Reply-To: Message-ID: Thanks Max, it is sort, but it gives back the max(len(item)) for the rows > I have a 2D array: > >>>> [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>>> > > > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. > > I hope that, it can wrote with some nice list comprehension, but I > can't do > that :( Here is the array: [['1', '2 ', '3 '], [ 'longer ','longer ','sort'] ] it is len(item) for that: [[ 1, 2, 3], [ 10,10, 4] ] I would have that is the next: (10,10,4) or [10,10,4] As I remeneber it is somewhere in numpy, but I am not sure. I would like to have it simply. Yours sincerely, ______________________________ J?nos Juh?sz Max Noel To J?nos Juh?sz 2005.06.17 13:35 cc tutor at python.org Subject Re: [Tutor] max(len(item)) for cols On Jun 17, 2005, at 11:58, J?nos Juh?sz wrote: > > Dear Guys, > > I have a 2D array: > >>>> [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>>> > > > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. > > I hope that, it can wrote with some nice list comprehension, but I > can't do > that :( >>> a = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1]] >>> max(len(item) for item in a) 4 If you're running Python 2.3 or lower, add brackets in the last line: >>> max([len(item) for item in a]) 4 -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From iqbala-python at qwestip.net Fri Jun 17 16:13:04 2005 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Fri, 17 Jun 2005 10:13:04 -0400 Subject: [Tutor] test Message-ID: <20050617141304.GB28784@qwestip.net> Hi All I have a very simple problem and I am looking for the simplest solution. I have a list of elements in a file. I like to find the total occurance of each element in the list like this 10 string1 7 string2 1 string3 from a list which has only string1,string2 and string3 like this string1 .. string2 ... string1 .. string3 ... ... I have a list of 30000 lines and I think I have only 615 unique elements. So I like the script not to take too much memory of the system. I will be running it on Solaris 8 Thanks a lot -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu "..there are two kinds of people: those who work and those who take the credit...try to be in the first group;...less competition there." - Indira Gandhi From flaxeater at yahoo.com Fri Jun 17 16:36:22 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri, 17 Jun 2005 07:36:22 -0700 (PDT) Subject: [Tutor] Checking if value exist in a '2D array' Message-ID: <20050617143622.77311.qmail@web54310.mail.yahoo.com> Kent Johnson wrote: >Olli Rajala wrote: > > >>Hi again, >> >>I have a '2D array', I mean a list inside a list ([[][],[][],...]) and >>would need to check if the value exists in it. Of course I could do a >>for loop, but that just seem to be a little overkill, so is there any >>other way to do it? I have to check the first cell of every insider >>list. >> >> > >With Python 2.4: > >>> l= [ [1], [2,3], [4,5], [6]] > >>> 2 in (i[0] for i in l) >True > >>> 3 in (i[0] for i in l) >False > >with Python 2.3 use [i[0] for i in l] instead which is a little less efficient. > The second case you show should be true because I believe that's what he asked for. Here is I believe the correct way to do this. >>> l= [ [1], [2,3], [4,5], [6]] >>> def isin(test,alist): ... return bool([x for x in alist if test in x]) ... >>> isin(2,l) True >>> isin(3,l) True >>> isin(10,l) False >>> def isin2(test,alist): ... for x in alist: ... if test in x: ... return True ... return False >>> isin2(2,l) True >>> isin2(10,l) False >>> __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Fri Jun 17 16:41:17 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri, 17 Jun 2005 07:41:17 -0700 (PDT) Subject: [Tutor] test Message-ID: <20050617144117.9334.qmail@web54304.mail.yahoo.com> How about this. >>> from random import choice >>> alist=[choice(range(100)) for x in range(1000)] #just making a list to look at pretend this is a file >>> >>> counter={} >>> for item in alist: ... if item in counter.keys(): ... counter[item]+=1 ... else: ... counter[item]=1 ... >>> counter {0: 9, 1: 9, 2: 9, 3: 14, 4: 15, 5: 15, 6: 13, 7: 5, 8: 11, 9: 12, 10: 9, 11: 12, 12: 13, 13: 8, 14: 5, 15: 12, 16: 14, 17: 9, 18: 11, 19: 8, 20: 6, 21: 13, 22: 11, 23: 10, 24: 8, 25: 15, 26: 19, 27: 11, 28: 13, 29: 13, 30: 12, 31: 18, 32: 10, 33: 5, 34: 9, 35: 5, 36: 9, 37: 12, 38: 8, 39: 11, 40: 8, 41: 12, 42: 6, 43: 13, 44: 11, 45: 8, 46: 8, 47: 6, 48: 9, 49: 6, 50: 5, 51: 11, 52: 11, 53: 12, 54: 15, 55: 15, 56: 10, 57: 12, 58: 13, 59: 6, 60: 6, 61: 7, 62: 8, 63: 13, 64: 14, 65: 7, 66: 7, 67: 12, 68: 5, 69: 10, 70: 8, 71: 7, 72: 12, 73: 12, 74: 6, 75: 13, 76: 12, 77: 13, 78: 9, 79: 5, 80: 13, 81: 14, 82: 4, 83: 6, 84: 8, 85: 12, 86: 8, 87: 10, 88: 10, 89: 7, 90: 7, 91: 9, 92: 12, 93: 14, 94: 8, 95: 7, 96: 10, 97: 11, 98: 8, 99: 8} >>> Asif Iqbal wrote: >Hi All > >I have a very simple problem and I am looking for the simplest solution. > >I have a list of elements in a file. I like to find the total occurance >of each element in the list like this > >10 string1 >7 string2 >1 string3 > >from a list which has only string1,string2 and string3 like this > >string1 >.. >string2 >... >string1 >.. >string3 >... >... > > >I have a list of 30000 lines and I think I have only 615 unique >elements. So I like the script not to take too much memory of the >system. I will be running it on Solaris 8 > >Thanks a lot > > > ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From kent37 at tds.net Fri Jun 17 16:50:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 10:50:08 -0400 Subject: [Tutor] Checking if value exist in a '2D array' In-Reply-To: <20050617143622.77311.qmail@web54310.mail.yahoo.com> References: <20050617143622.77311.qmail@web54310.mail.yahoo.com> Message-ID: <42B2E320.2000800@tds.net> Chad Crabtree wrote: > The second case you show should be true because I believe that's what > he > asked for. Here is I believe the correct way to do this. > > >>>>l= [ [1], [2,3], [4,5], [6]] >>>>def isin(test,alist): > > ... return bool([x for x in alist if test in x]) I don't think so, the OP says "I have to check the first cell of every insider list." Kent From iqbala-python at qwestip.net Fri Jun 17 17:02:46 2005 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Fri, 17 Jun 2005 11:02:46 -0400 Subject: [Tutor] test In-Reply-To: <20050617144117.9334.qmail@web54304.mail.yahoo.com> References: <20050617144117.9334.qmail@web54304.mail.yahoo.com> Message-ID: <20050617150246.GA13238@qwestip.net> On Fri, Jun 17, 2005 at 07:41:17AM, Chad Crabtree wrote: > How about this. > >>> from random import choice > >>> alist=[choice(range(100)) for x in range(1000)] #just making a How do I do this in python? alist < /tmp/logfile The logfile has the list of entries. -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu "..there are two kinds of people: those who work and those who take the credit...try to be in the first group;...less competition there." - Indira Gandhi From janos.juhasz at VELUX.com Fri Jun 17 17:14:13 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 17 Jun 2005 17:14:13 +0200 Subject: [Tutor] max(len(item)) for cols In-Reply-To: Message-ID: Thanks for jfouhy and Kent! Both the zip and the recipe are suit for me. I looked for these. Yours sincerely, ______________________________ J?nos Juh?sz From alan.gauld at freenet.co.uk Fri Jun 17 19:49:32 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 17 Jun 2005 18:49:32 +0100 Subject: [Tutor] Clearing the Console Screen References: <20050616110237.3de41ed9@luke.matheteuo.rel><00aa01c572b7$b0b8cd50$97a28651@xp> <42B210B8.4060206@tds.net> Message-ID: <012701c57364$eb348a20$97a28651@xp> > > That having been said Fred Lundh has written a console module > > that tries to hide the diffeent trminal types in a common set > > of commands - you can download it from his site. > > The only one I can find there is for Windows: > http://www.effbot.org/zone/console-handbook.htm My bad. You are right. I've seen it used for windows console control and was told it worked for "any console", I assumed that included *nix but obviously not! Its not as impressive a feat as I thought in that case. Apologies for the bad steer. Alan G. From alan.gauld at freenet.co.uk Fri Jun 17 19:51:56 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 17 Jun 2005 18:51:56 +0100 Subject: [Tutor] can't see emacs timer in action References: <006a01c572b6$60684e30$97a28651@xp> Message-ID: <013001c57365$40ea3870$97a28651@xp> > but I don't understand why xemacs doesn't fix C-c C-c Neither do I. BTW Do you know if this is specific to xemacs? Or does it also apply to python mode in vanilla GNU emacs too? I really should get around to loading python-mode and trying it some day... Alan G. From alan.gauld at freenet.co.uk Fri Jun 17 19:59:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 17 Jun 2005 18:59:38 +0100 Subject: [Tutor] max(len(item)) for cols References: Message-ID: <014501c57366$54af4c00$97a28651@xp> I have a 2D array: >>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. >>> tda = [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>> mcw = [[len(r) for r in c] for c in tda] >>> mcw [[1, 2, 5], [11, 10, 4]] >>> mcw = [max([len(r) for r in c]) for c in tda] >>> mcw [5, 11] >>> widest = max(mcw) >>> widest 11 Is that what you mean? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From flaxeater at yahoo.com Fri Jun 17 20:26:21 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri, 17 Jun 2005 11:26:21 -0700 (PDT) Subject: [Tutor] test Message-ID: <20050617182622.86551.qmail@web54303.mail.yahoo.com> Asif Iqbal wrote: >On Fri, Jun 17, 2005 at 07:41:17AM, Chad Crabtree wrote: > > >>How about this. >> >>> from random import choice >> >>> alist=[choice(range(100)) for x in range(1000)] #just making a >> >> > >How do I do this in python? > alist < /tmp/logfile > >The logfile has the list of entries. > > > ok sorry filehandle=open('/tmp/logfile','r').readlines() Look here http://docs.python.org/lib/built-in-funcs.html#built-in-funcs and http://docs.python.org/lib/bltin-file-objects.html __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From Connor.Smith at huntington.com Fri Jun 17 22:30:39 2005 From: Connor.Smith at huntington.com (Connor.Smith@huntington.com) Date: Fri, 17 Jun 2005 16:30:39 -0400 Subject: [Tutor] Logging stdout and stderr Message-ID: Hi there - I'm trying to log the results of a command that I'm running via the popen2 module to a file, while at the same time displaying its progress on the screen. So, at the end of the run, I should have the entire output (stdout and stderr) on the screen, but also have two file objects each with the contents of one of stdout and stderr. I can figure out how to write the results to a file, and then process or log it, but what I can't do is figure out a way to simultaneously display it to the screen, kind of like how unix's "tee" utility works. Can anyone help? -Cs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050617/8acb546f/attachment.htm From ajikoe at gmail.com Sat Jun 18 00:02:01 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sat, 18 Jun 2005 00:02:01 +0200 Subject: [Tutor] can't see emacs timer in action In-Reply-To: <013001c57365$40ea3870$97a28651@xp> References: <006a01c572b6$60684e30$97a28651@xp> <013001c57365$40ea3870$97a28651@xp> Message-ID: Before I use xemacs I use emacs and both are the same. I don't know if there is connection between cpython and problem in showing real time console, because both use cpython. I also want to hear people who use python and emacs/xemacs concerning this problem. pujo On 6/17/05, Alan G wrote: > > but I don't understand why xemacs doesn't fix C-c C-c > > Neither do I. BTW Do you know if this is specific to xemacs? > Or does it also apply to python mode in vanilla GNU emacs too? > > I really should get around to loading python-mode and > trying it some day... > > Alan G. > From hugonz-lists at h-lab.net Sat Jun 18 05:27:44 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 17 Jun 2005 22:27:44 -0500 Subject: [Tutor] Logging stdout and stderr In-Reply-To: References: Message-ID: <42B394B0.2010904@h-lab.net> Hi, Why don't you print it while you get it..? import os, sys logfile = open("logfile.txt", "r") input, output = os.popen2("your command") while True: temp = output.read(1) #or whatever fits you, more bytes is faster if not temp: //EOF reached break logfile.write(temp) sys.stdout.write(temp) Connor.Smith at huntington.com wrote: > > Hi there - > > I'm trying to log the results of a command that I'm running via the > popen2 module to a file, while at the same time displaying its progress > on the screen. So, at the end of the run, I should have the entire > output (stdout and stderr) on the screen, but also have two file objects > each with the contents of one of stdout and stderr. I can figure out > how to write the results to a file, and then process or log it, but what > I can't do is figure out a way to simultaneously display it to the > screen, kind of like how unix's "tee" utility works. > > Can anyone help? > > -Cs > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat Jun 18 13:36:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Jun 2005 07:36:29 -0400 Subject: [Tutor] Logging stdout and stderr In-Reply-To: References: Message-ID: <42B4073D.5060906@tds.net> Connor.Smith at huntington.com wrote: > > Hi there - > > I'm trying to log the results of a command that I'm running via the > popen2 module to a file, while at the same time displaying its progress > on the screen. So, at the end of the run, I should have the entire > output (stdout and stderr) on the screen, but also have two file objects > each with the contents of one of stdout and stderr. You could do this with the logging package. Set up the logger to log to the screen and to a file. You could split the files by log level or (I think) by using two different loggers. For what you are doing this is probably overkill (Hugo's suggestion is simpler) but if you have output in many places in the file logging is a good solution. Also it lets you for example put debug messages in the file but not on screen. Kent From alan.gauld at freenet.co.uk Sat Jun 18 16:18:48 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 18 Jun 2005 15:18:48 +0100 Subject: [Tutor] Logging stdout and stderr References: Message-ID: <018d01c57410$a577ae70$97a28651@xp> > I'm trying to log the results of a command that I'm running via the popen2 > module to a file, while at the same time displaying its progress on the > screen. I think you need popen3... > figure out a way to simultaneously display it to the screen, kind of like > how unix's "tee" utility works. Use tee? It's designed for this kind of thing and there are versions for Windoze too. I personally prefer to leave this kind of logging as a user option rather than embed it into my code. Alan G. From nephish at xit.net Sat Jun 18 22:50:56 2005 From: nephish at xit.net (nephish) Date: Sat, 18 Jun 2005 13:50:56 -0700 Subject: [Tutor] database app Message-ID: <42B48930.6070404@xit.net> Hey there, i have used the cgi module and dig it. heres the deal, my employer wants me to build a dynamic website that will access a database and display customer information on web. ok, easy enough. heres the trick. the database is MS Access. - ick. what could i do to manipulate data in an access database ? can it be done ? all the research i have done just points me to sql, sqlite, etc... i wouldnt mind if i can find a way to push everything from access to another kind of database, but i dont know where to start. any ideas? -thanks From webdev at matheteuo.org Sat Jun 18 21:42:24 2005 From: webdev at matheteuo.org (Don Parris) Date: Sat, 18 Jun 2005 15:42:24 -0400 Subject: [Tutor] database app In-Reply-To: <42B48930.6070404@xit.net> References: <42B48930.6070404@xit.net> Message-ID: <20050618154224.30cc02ae@luke.matheteuo.rel> On Sat, 18 Jun 2005 13:50:56 -0700 nephish wrote: > Hey there, > > i have used the cgi module and dig it. > heres the deal, > my employer wants me to build a dynamic website that will access a > database and display customer > information on web. ok, easy enough. > heres the trick. > the database is MS Access. - ick. > what could i do to manipulate data in an access database ? can it be > done ? > all the research i have done just points me to sql, sqlite, etc... > i wouldnt mind if i can find a way to push everything from access to > another kind of database, > but i dont know where to start. > any ideas? > > -thanks > _______________________________________________ There is a way to work with your Access data via Python & the Jet engine, but I have no clue about that. Check the Python documentation - I'm sure that's where I saw reference to it. I may have seen it on one of the Python-related sites, but I think this link will offer some insight: http://www.python.org/windows/OdbcHints.html If you want to get out of Access, you can save your data as tab-delimited text files, and import them into MySQL. I'm sure that goes for PostGreSQL as well. Just make sure you remove the quote marks - regexp type work. (I haven't done that part programmatically yet, just using the find/replace feature of jEdit.) I'll have to cover that ground myself soon, so we'll see what happens. HTH, Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From flaxeater at yahoo.com Sat Jun 18 21:35:47 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat, 18 Jun 2005 12:35:47 -0700 (PDT) Subject: [Tutor] database app Message-ID: <20050618193547.56142.qmail@web54304.mail.yahoo.com> Well when working with M$ db's you should use odbc. http://www.egenix.com/files/python/mxODBC.html nephish wrote: >Hey there, > > i have used the cgi module and dig it. > heres the deal, > my employer wants me to build a dynamic website that will access a >database and display customer > information on web. ok, easy enough. > heres the trick. > the database is MS Access. - ick. > what could i do to manipulate data in an access database ? can it be >done ? > all the research i have done just points me to sql, sqlite, etc... > i wouldnt mind if i can find a way to push everything from access to >another kind of database, > but i dont know where to start. > any ideas? > >-thanks >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From nephish at xit.net Sat Jun 18 23:47:04 2005 From: nephish at xit.net (nephish) Date: Sat, 18 Jun 2005 14:47:04 -0700 Subject: [Tutor] database app Message-ID: <42B49658.3010008@xit.net> Exactly what i was looking for. thanks gents, i didn't even know this module existed. i guess this access project will not be as intimidating as i thought. cheers From alan.gauld at freenet.co.uk Sun Jun 19 16:38:19 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 19 Jun 2005 15:38:19 +0100 Subject: [Tutor] database app References: <42B48930.6070404@xit.net> Message-ID: <001201c574dc$89e0b7c0$4e4c8651@xp> > database and display customer information on web. ok, easy enough. > heres the trick. the database is MS Access. - ick. ick indeed, but maybe for different reasons... There is an ODBC database driver that you can use to access Access. But you will have to be careful about locking if the traffic is high. Access was designed as a single uuser desktop database and that legacy still shows through. The very latest versions are better but if you have more than 1 simultaneous update going on at a time I'd consider moving the database or using snapshot technology or similar, Access locks by pages (default 2K?) which can mean a lot of data rows being locked by a single update. Make sure as a minimum that you are not locking on reads! HTH, Alan G. From nephish at xit.net Mon Jun 20 05:41:17 2005 From: nephish at xit.net (nephish) Date: Sun, 19 Jun 2005 20:41:17 -0700 Subject: [Tutor] question about comma delineated text Message-ID: <42B63ADD.7060907@xit.net> Hey there, i have some log files that i want to be able to work with. the lines of the log files are comma - delineated. i want to put those into a database where each piece of info (comma delineated) would be the fields of the database. ok, so the first obstacle is learning how to make a list or dictionary (prefer dictionary) out of each line of the log. any suggestions of where to start? thanks From kent37 at tds.net Mon Jun 20 03:51:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 19 Jun 2005 21:51:35 -0400 Subject: [Tutor] question about comma delineated text In-Reply-To: <42B63ADD.7060907@xit.net> References: <42B63ADD.7060907@xit.net> Message-ID: <42B62127.7090607@tds.net> nephish wrote: > Hey there, > i have some log files that i want to be able to work with. > the lines of the log files are comma - delineated. > i want to put those into a database where each piece of info (comma > delineated) > would be the fields of the database. > > ok, so the first obstacle is learning how to make a list or dictionary > (prefer dictionary) out of > each line of the log. > > any suggestions of where to start? See the DictReader class in the csv library module. Kent From phillip.hart at gmail.com Mon Jun 20 06:46:00 2005 From: phillip.hart at gmail.com (Phillip Hart) Date: Sun, 19 Jun 2005 23:46:00 -0500 Subject: [Tutor] Layering Canvas widgets with Tkinter Message-ID: <560fda42050619214621eeeb39@mail.gmail.com> Greetings again helpful friends, I've written a series of Python/Tkinter programs, each of which will represent a different menu/screen in a simple Tkinter game I'm making. Now, my trouble is linking them together through layered menus with buttons. So far, I've tried using a single Tk window, creating a series of canvas widgets, each containing a series of buttons. When pressed, each button calls a function which uses .grid_remove() on the current canvas and creates a new canvas with new buttons in its place (a new menu). My trouble is the menu layers are not covering each other up correctly. menu1 and menu2 functions fail to create a canvas of their designated size and .grid_remove() does not seem to remove the main canvas, thus creating the appearance of jumbled, stacked buttons. Oddly, the menu3 function will create its designated canvas to cover up the main menu, but only seems to work because it has no buttons. Likewise, the mainmenu function will return the menu cleanly to its normal state. I've also fiddled with .grid_forget() and .destroy() and had the same results. I'm still very inexperienced. Can someone give me a hand here? Thanks, -Phil ######### from Tkinter import * def menu(y): main.grid_remove () root.update() if y ==1: menu1() if y==2: menu2() if y==3: menu3() def menu1(): X=Canvas(root, width=200, height=200, bg="blue") X.grid(row=0,column=0) but2=Button(X,text="back",command=mainmenu) but2.grid() def menu2(): Y=Canvas(root, width=200, height=200, bg="red") Y.grid(row=0,column=0) but1=Button(Y,text="back",command=mainmenu) but1.grid() def menu3(): Z=Canvas(root, width=200, height=200, bg="green") Z.grid(row=0,column=0) def mainmenu(): main=Canvas(root,width=200,height=200,bg="grey") main.grid(row=0,column=0) men1=Button(main,text="menu 1",command=lambda y=1:menu(y)) men1.grid() men2=Button(main,text="menu 2",command=lambda y=2:menu(y)) men2.grid() men3=Button(main,text="menu 3",command=lambda y=3:menu(y)) men3.grid() root= Tk() root.geometry('200x200') main=Canvas(root,width=200,height=200,bg="grey") main.grid(row=0,column=0) men1=Button(main,text="menu 1",command=menu1) men1.grid() men2=Button(main,text="menu 2",command=menu2) men2.grid() men3=Button(main,text="menu 3",command=menu3) men3.grid() root.mainloop() ################# -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050619/83d80f60/attachment.htm From webdev at matheteuo.org Mon Jun 20 07:13:11 2005 From: webdev at matheteuo.org (DC Parris) Date: Mon, 20 Jun 2005 05:13:11 -0000 Subject: [Tutor] Numbers & Characters As Dictionary Keys Message-ID: <20050620051320.ACC69414E2@mail01.powweb.com> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20050620/687c1bc6/attachment.diff From chuck at freshsources.com Mon Jun 20 07:14:52 2005 From: chuck at freshsources.com (Chuck Allison) Date: Sun, 19 Jun 2005 23:14:52 -0600 Subject: [Tutor] Every Other In-Reply-To: <941480980506152019319eebde@mail.gmail.com> References: <941480980506152019319eebde@mail.gmail.com> Message-ID: <42B650CC.8000005@freshsources.com> Hello Tutors, What would be the most Pythonic way of printing (or extracting) every other element of a list? Thanks in advance. -- Chuck Allison From jfouhy at paradise.net.nz Mon Jun 20 07:55:25 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 20 Jun 2005 17:55:25 +1200 (NZST) Subject: [Tutor] Layering Canvas widgets with Tkinter In-Reply-To: <560fda42050619214621eeeb39@mail.gmail.com> References: <560fda42050619214621eeeb39@mail.gmail.com> Message-ID: <1119246925.42b65a4d34e78@www.paradise.net.nz> Quoting Phillip Hart : > So far, I've tried using a single Tk window, creating a series of canvas > widgets, each containing a series of buttons. When pressed, each button > calls a function which uses .grid_remove() on the current canvas and > creates a new canvas with new buttons in its place (a new menu). Your logic is a bit confused, I think. What you are aiming for, I think, is something like this: Display Main Menu "menu 1" pushed --> hide main menu, display menu1 "back" pushed --> hide menu1, display main menu "menu 2" pushed --> hide main menu, display menu2 "back" pushed --> hide menu2, display main menu "menu 3" pushed --> hide main menu, display menu3. One way you could do this is to create all four menus, and then use callbacks that simply show/hide as appropriate. For example: ######## Note that I have replaced leading spaces with underscores ##### ######## You will need to undo this to run the program ################# from Tkinter import * def switch(hide, show): ____hide.grid_forget() ____show.grid(sticky=N+S+E+W) tk = Tk() # This is necessary, otherwise the canvas shrinks to the size of the button(s) it contains. # You could also use width= and height= to give the canvases a specific size. tk.grid_rowconfigure(0, weight=1) tk.grid_columnconfigure(0, weight=1) main = Canvas(tk) menu1 = Canvas(tk, background='green') menu2 = Canvas(tk, background='pink') menu3 = Canvas(tk, background='yellow') for i, m in enumerate((menu1, menu2, menu3)): ____Button(main, text='Menu %d' % i, command=lambda m=m: switch(main, m)).grid() ____Button(m, text='Back', command=lambda m=m: switch(m, main)).grid() main.grid() tk.mainloop() ################################## I am only creating the canvases once, and then just using grid() and grid_forget() to hide/show them as appropriate. In your code, you created a new canvas with every call to menu1/menu2/menu3. Also, you never called grid_forget on any of those canvases (so they never disappeared). Finally, I made all the canvases children of tk, rather than making menu1/menu2/menu3 children of main. If menu1 were a child of main, then to display menu1, you would have to hide the buttons (because menu1 would display inside main). ---- Additional comments: - grid_forget is, I think, exactly the same as grid_remove. - Are you sure you want to be using canvases at all? Geometry managers like grid are normally used with Frames. If you want to display widgets on a canvas, the normal way to do it is to use canvas.create_window. -- John. From jfouhy at paradise.net.nz Mon Jun 20 07:58:06 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 20 Jun 2005 17:58:06 +1200 (NZST) Subject: [Tutor] Every Other In-Reply-To: <42B650CC.8000005@freshsources.com> References: <941480980506152019319eebde@mail.gmail.com> <42B650CC.8000005@freshsources.com> Message-ID: <1119247086.42b65aee9a0f5@www.paradise.net.nz> Quoting Chuck Allison : > Hello Tutors, > > What would be the most Pythonic way of printing (or extracting) every > other element of a list? Thanks in advance. This is probably it: >>> arr = range(20) >>> arr[::2] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> arr[1::2] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] -- John. From bvande at po-box.mcgill.ca Mon Jun 20 08:06:11 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 20 Jun 2005 02:06:11 -0400 Subject: [Tutor] Numbers & Characters As Dictionary Keys In-Reply-To: <20050620051320.ACC69414E2@mail01.powweb.com> References: <20050620051320.ACC69414E2@mail01.powweb.com> Message-ID: <42B65CD3.7040502@po-box.mcgill.ca> DC Parris said unto the world upon 20/06/2005 01:13: > I have a dictionary called Menu_Main: > > Menu_Main = { 1: ['People', Call_Fam], > 2: ['Groups', Call_Group], > 3: ['Events', nullfunc], > 4: ['Attendance', nullfunc], > 5: ['Visitation', nullfunc], > 6: ['Finances', nullfunc], > 7: ['Administration', nullfunc], > 10: ['Help', nullfunc], # I would like to make the "10" an "h" > 12: ['Quit', 'return']} # and the "12" a "q". > > > I assume the keys can be of mixed types. However, I'm not sure how > to adjust my code below that actually drives the menu system. I > changed "input" to "raw_input", but I get "H is not defined" when I > run the script. Essentially, I'd like the user to enter a number > for most items, but use letters for "Help", "Quit", and "Back to > Main". > > def RunMenu(MenuList): > '''This is the function that drives the menu system. > > We place the "clear screen" command twice to provide a fresh screen for > each menu level. We then call the menus above to display them. There is a > special value for MenuList[sel][1] of 'return' which is the exit condition > for the loop. look at the entry for 9 of Menu_Main, or item 8 of Menu_Fam. > ''' > while True: > for opts in MenuList.keys(): # print menu list > print opts, ': ', MenuList[opts][0] # > sel = input('Enter Selection:') # get input > if sel in MenuList.keys(): #verify user input is a valid key > if MenuList[sel][1] == 'return': return MenuList[sel][0] > else: MenuList[sel][1]() > > Thanks, > Don Hi Don, you are better off using raw_input for reasons of security -- input executes the input it receives, which can be dangerous. I'd probably just go with all dict keys being strings, be they '1', 'h', or whatever. If you're set on some being ints rather than strings, here's one approach. (I've simplified the rest of the case to show the idea more clearly. Doubtless someone else could improve upon it.) menu_dict = {1:'Action 1!', 2:'Action 2!', 'h':'Assistance here', 'q':'For quitters'} while True: # Sorted, as else there is no standard order for the keys. # Needs a reasonably recent Python -- I forget when it came in. # And, you can just print key in a_dict, you don't need # a_dict.keys() for key in sorted(menu_dict): print key, menu_dict[key] choice = raw_input('make your choice') try: choice = int(choice) except ValueError: # The ValueError will get raised for cases where choice is a # string not convertible into an int ('h', 'five', etc) pass if choice in menu_dict: print menu_dict[choice] break else: print "Please read the menu" HTH, Brian vdB From janos.juhasz at VELUX.com Mon Jun 20 09:24:10 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 20 Jun 2005 09:24:10 +0200 Subject: [Tutor] max(len(item)) for cols In-Reply-To: <014501c57366$54af4c00$97a28651@xp> Message-ID: Dear Alan, similar :) I have scripted a small sql e-mail reporting simplified from # written by Mike Brown # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 import string def TableStr(labels, rows, delim=' | '): columns = zip(*[labels] + rows) # get the maximum of each column by the string length of its items maxWidths = [max([len(str(cell)) for cell in column]) for column in columns] result = delim.join( [str.ljust(str(item),width) for (item,width) in zip(labels,maxWidths)] )+'\n' result += '='*(sum(maxWidths) + len(delim)*(len(columns)-1))+'\n' for row in rows: result += delim.join( [str.ljust(str(item),width) for (item,width) in zip(row,maxWidths)] )+'\n' return result data = """\ WH,Stock,Qty 01,1001,10 01,1002,23 02,1432,4 03,This is long stockcode,100""" table = string.split(data, '\n') labels = string.split(table[0], ',') rows = [string.split(row, ',') for row in table[1:]] print '' print TableStr(labels, rows, delim=' | ') It makes beautiful tables from sql queries into e-mail as warning. That I don't know is the asterisk in zip(*[labels] + rows) I wasn't able to find in the python reference what it means. May you help me in that ? Yours sincerely, ______________________________ J?nos Juh?sz "Alan G" To J?nos Juh?sz , cc 2005.06.17 19:59 Subject Re: [Tutor] max(len(item)) for cols I have a 2D array: >>>[['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. >>> tda = [['1', '2 ', '3 '], ['longer ', 'longer ', 'sort']] >>> mcw = [[len(r) for r in c] for c in tda] >>> mcw [[1, 2, 5], [11, 10, 4]] >>> mcw = [max([len(r) for r in c]) for c in tda] >>> mcw [5, 11] >>> widest = max(mcw) >>> widest 11 Is that what you mean? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From shuying at gmail.com Mon Jun 20 09:56:21 2005 From: shuying at gmail.com (Shuying Wang) Date: Mon, 20 Jun 2005 17:56:21 +1000 Subject: [Tutor] calling perl from python code Message-ID: <75fa0c3a0506200056480d4d0@mail.gmail.com> Hi, Can anyone recommend a library that will let me call perl functions from python? I have a python dictionary that I would like to convert to a perl hash for some function. cheers, Shuying From alan.gauld at freenet.co.uk Mon Jun 20 10:00:23 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 20 Jun 2005 09:00:23 +0100 Subject: [Tutor] Layering Canvas widgets with Tkinter References: <560fda42050619214621eeeb39@mail.gmail.com> Message-ID: <005001c5756e$1d0c12b0$4e4c8651@xp> ----------------- def menu(y): main.grid_remove () root.update() if y ==1: menu1() etc/... def menu1(): X=Canvas(root, width=200, height=200, bg="blue") X.grid(row=0,column=0) but2=Button(X,text="back",command=mainmenu) but2.grid() def menu2():... def menu3():... root= Tk() root.geometry('200x200') main=Canvas(root,width=200,height=200,bg="grey") main.grid(row=0,column=0) root.mainloop() -------------------- I think one problem is that you initially call your canvas main. In menu() you then remove main, but you don't ever replace it. Thus on subsequent calls to menu() you are not actually removing anything! This is partly a result of you using global variables everywhere and partly a result of you mixing the object creation and their positioning in a single function. It would IMHO be better to make the menuN() functions simply return the canvas objects rather than to use grid() internally. That way you can associate them with main... That way the code changes to look something like: def menu(y): main.grid_remove () root.update() if y ==1: main = menu1() main.grid(row=0,column=0) etc/... def menu1(): X=Canvas(root, width=200, height=200, bg="blue") but2=Button(X,text="back",command=mainmenu) but2.grid() return X The other option would e to pass main into menuN() as a parameter and use that instead of X but I prefer the approach above... HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jun 20 10:11:53 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 20 Jun 2005 09:11:53 +0100 Subject: [Tutor] Numbers & Characters As Dictionary Keys References: <20050620051320.ACC69414E2@mail01.powweb.com> Message-ID: <005501c5756f$b8d6ed40$4e4c8651@xp> > "raw_input", but I get "H is not defined" when I run the script. > Essentially, I'd like the user to enter a number for most items, > but use letters for "Help", "Quit", and "Back to Main". Are you sure? That kind of inconsistent input is one of the big no-nos of user interface design. It usually confuses the heck out of users! Hoewever to the problem at hand. It should just be a case of changing the keys in the dictionary. Unfortunately you've told us the problem but shown us the code that woreks, not the broken copde. So we can only guess what you might have done! But basically here is a sample program that does approximately what you want: def hello(): print 'hello' def goodbye(): print 'goodbye' menu = { '1' : ('hello', hello), 'Q' : ('goodbye', goodbye)} for m in menu.keys(): print "%s\t%s" % (m,menu[m][0]) cmd = raw_input('pick one ').upper() menu[cmd][1]() Does that help? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jun 20 10:15:45 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 20 Jun 2005 09:15:45 +0100 Subject: [Tutor] Every Other References: <941480980506152019319eebde@mail.gmail.com> <42B650CC.8000005@freshsources.com> Message-ID: <005a01c57570$427de120$4e4c8651@xp> > What would be the most Pythonic way THats always going to be subjective but... > of printing (or extracting) every > other element of a list? I'd probably use range with a step of 2. for index in range(0,len(mylist),2): ptint mylist[index] Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jun 20 10:17:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 20 Jun 2005 09:17:37 +0100 Subject: [Tutor] Every Other References: <941480980506152019319eebde@mail.gmail.com><42B650CC.8000005@freshsources.com> <1119247086.42b65aee9a0f5@www.paradise.net.nz> Message-ID: <006101c57570$85045dd0$4e4c8651@xp> JOhn, > This is probably it: > >>> arr = range(20) > >>> arr[::2] You are probably right, I forgot that slicing now had a 3rd element... :-) Alan G. From andreengels at gmail.com Mon Jun 20 10:26:20 2005 From: andreengels at gmail.com (Andre Engels) Date: Mon, 20 Jun 2005 10:26:20 +0200 Subject: [Tutor] Calling web browser from Python Message-ID: <6faf39c90506200126187d7994@mail.gmail.com> Is it possible to call a web browser from Python, opening a certain page? Preferably the user's standard web browser. Andre Engels From bvande at po-box.mcgill.ca Mon Jun 20 10:32:43 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 20 Jun 2005 04:32:43 -0400 Subject: [Tutor] Calling web browser from Python In-Reply-To: <6faf39c90506200126187d7994@mail.gmail.com> References: <6faf39c90506200126187d7994@mail.gmail.com> Message-ID: <42B67F2B.5000400@po-box.mcgill.ca> Andre Engels said unto the world upon 20/06/2005 04:26: > Is it possible to call a web browser from Python, opening a certain > page? Preferably the user's standard web browser. > > Andre Engels > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > IDLE 1.1.1 >>> import webbrowser >>> webbrowser.open('www.google.ca') >>> Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Mon Jun 20 10:41:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Jun 2005 01:41:23 -0700 (PDT) Subject: [Tutor] calling perl from python code In-Reply-To: <75fa0c3a0506200056480d4d0@mail.gmail.com> Message-ID: On Mon, 20 Jun 2005, Shuying Wang wrote: > Can anyone recommend a library that will let me call perl functions from > python? I have a python dictionary that I would like to convert to a > perl hash for some function. Hi Shuying, Sure! You may want to look at the PyPerl project: http://wiki.python.org/moin/PyPerl The module acts as a bridge between the two langauges, so it should be relatively easy to convert Python dictionaries to Perl hashes and pass them back and forth. Best of wishes! From jfouhy at paradise.net.nz Mon Jun 20 10:44:12 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 20 Jun 2005 20:44:12 +1200 (NZST) Subject: [Tutor] Calling web browser from Python In-Reply-To: <6faf39c90506200126187d7994@mail.gmail.com> References: <6faf39c90506200126187d7994@mail.gmail.com> Message-ID: <1119257052.42b681dcce8ea@www.paradise.net.nz> Quoting Andre Engels : > Is it possible to call a web browser from Python, opening a certain > page? Preferably the user's standard web browser. Check the webbrowser module :-) -- John. From jfouhy at paradise.net.nz Mon Jun 20 11:01:34 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 20 Jun 2005 21:01:34 +1200 (NZST) Subject: [Tutor] max(len(item)) for cols In-Reply-To: References: Message-ID: <1119258094.42b685ee9b8bc@www.paradise.net.nz> Quoting J?nos Juh?sz : > That I don't know is the asterisk in zip(*[labels] + rows) > I wasn't able to find in the python reference what it means. > May you help me in that ? You can find it in the language reference: http://docs.python.org/ref/calls.html Basically, suppose you have a list: >>> myList = ['foo', 42, None] and a function: >>> def doSomething(s, n, t): ... print 'The meaning of %s is %d' % (s, n) ... if t: ... return True ... return False ... Then you can call like this: >>> doSomething(*myList) The meaning of foo is 42 False The *myList means "expand myList into a bunch of positional parameters". So, doSomething got the first element of myList as s, the second element as n, and the third element as t. You can do the same thing in reverse, in the function definition. eg: >>> def myFunction(*args): ... for x in args: ... print x, ... print ... >>> myFunction(1, 2, 'foo', 'bar', 37) 1 2 foo bar 37 In this case, all the positional arguments got combined into a tuple, and given the name 'args'. Finally, this works with keyword arguments as well, but you have to use dictionaries, and you use two asterisks instead of one. >>> myDict = { 'x':3, 'y':7, 'z':19 } >>> def doSomeArithmetic(y=0, z=0, x=0): ... return y*z+x ... >>> doSomeArithmetic(**myDict) 136 HTH! -- John. From levity at gmail.com Mon Jun 20 18:21:13 2005 From: levity at gmail.com (lawrence wang) Date: Mon, 20 Jun 2005 12:21:13 -0400 Subject: [Tutor] Refreshing the interpreter environment Message-ID: <22e13a2205062009213e113edf@mail.gmail.com> How do I refresh the interpreter environment without restarting it, if possible? For example, I'm using the interpreter to test a class I'm writing; importing and instantiating it reveals a typo; I go and fix the typo. Now, is there any way to reload the class afresh? Simply importing again doesn't seem to do it. Thanks in advance for your help. Lawrence Wang From javier at ruere.com.ar Mon Jun 20 19:40:37 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Mon, 20 Jun 2005 14:40:37 -0300 Subject: [Tutor] Refreshing the interpreter environment In-Reply-To: <22e13a2205062009213e113edf@mail.gmail.com> References: <22e13a2205062009213e113edf@mail.gmail.com> Message-ID: lawrence wang wrote: > How do I refresh the interpreter environment without restarting it, if > possible? For example, I'm using the interpreter to test a class I'm > writing; importing and instantiating it reveals a typo; I go and fix > the typo. Now, is there any way to reload the class afresh? Simply > importing again doesn't seem to do it. Thanks in advance for your > help. Yes: (echo "a=1" > a.py) >>> import a >>> a.a 1 (echo "a=2" > a.py) >>> a = reload(a) >>> a.a 2 Javier -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 256 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050620/08b62fbb/signature.pgp From webdev at matheteuo.org Mon Jun 20 20:10:54 2005 From: webdev at matheteuo.org (Don Parris) Date: Mon, 20 Jun 2005 14:10:54 -0400 Subject: [Tutor] Numbers & Characters As Dictionary Keys In-Reply-To: <005501c5756f$b8d6ed40$4e4c8651@xp> References: <20050620051320.ACC69414E2@mail01.powweb.com> <005501c5756f$b8d6ed40$4e4c8651@xp> Message-ID: <20050620141054.00f4dddf@luke.matheteuo.rel> On Mon, 20 Jun 2005 09:11:53 +0100 "Alan G" wrote: > > "raw_input", but I get "H is not defined" when I run the script. > > Essentially, I'd like the user to enter a number for most items, > > but use letters for "Help", "Quit", and "Back to Main". > > Are you sure? That kind of inconsistent input is one of the > big no-nos of user interface design. It usually confuses > the heck out of users! > Hmmm, good point. It was a thought. I am trying to avoid confusing my users. If this kind of input will cause confusion, I should avoid it. I was looking to provide a consistent help/quit/main single-key scheme across all menus. I can (and presently am) using a double-digit number for this purpose in the current script. On the other hand, I thought people would easily recognize at least the "H" & "Q" for "help" and "quit". Alternatively, I could link these to "F1" & [Ctrl]+Q, or something like that. Many people would understand "F1". Basically, the sub-menu offers choices: 1-3 - add/edit/delete 4-? - standard reports 10-12 - H/Q/M > Hoewever to the problem at hand. > It should just be a case of changing the keys in the dictionary. > Unfortunately you've told us the problem but shown us the code > that woreks, not the broken copde. So we can only guess what > you might have done! > > But basically here is a sample program that does approximately > what you want: > > def hello(): print 'hello' > def goodbye(): print 'goodbye' > > menu = { '1' : ('hello', hello), > 'Q' : ('goodbye', goodbye)} > > for m in menu.keys(): > print "%s\t%s" % (m,menu[m][0]) > I am curious what the "%" by itself is doing. > cmd = raw_input('pick one ').upper() > menu[cmd][1]() > > Does that help? > I'll tinker with this a bit. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From bvande at po-box.mcgill.ca Mon Jun 20 21:05:28 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 20 Jun 2005 15:05:28 -0400 Subject: [Tutor] Numbers & Characters As Dictionary Keys In-Reply-To: <20050620141054.00f4dddf@luke.matheteuo.rel> References: <20050620051320.ACC69414E2@mail01.powweb.com> <005501c5756f$b8d6ed40$4e4c8651@xp> <20050620141054.00f4dddf@luke.matheteuo.rel> Message-ID: <42B71378.7070108@po-box.mcgill.ca> Don Parris said unto the world upon 20/06/2005 14:10: > On Mon, 20 Jun 2005 09:11:53 +0100 > "Alan G" wrote: >>for m in menu.keys(): >> print "%s\t%s" % (m,menu[m][0]) >> > > I am curious what the "%" by itself is doing. > Don Hi Don, it is indicating that the tuple that follows is the source that the values for the '%s's in "%s\t%s" will be drawn from. I generally write it without the space between the '%' and the tuple; I don't know what the general practise is. >>> print "%s won't %s" ('this', 'work') Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> print "%s will %s" %('this', 'work') this will work >>> print "%s will %s" % ('this', 'work, too') this will work, too >>> Best, Brian vdB From chinook.nr at tds.net Tue Jun 21 07:57:51 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 21 Jun 2005 01:57:51 -0400 Subject: [Tutor] Using code objects? Message-ID: <0001HW.BEDD249F0014B04BF00FF3B0@smtp.tds.net> Using code objects? =================== As an OO exercise I have a factory pattern that returns class objects that each have an "action" method. ClassObj.action() in turn returns a code object in my recursive process loop. I create the code objects as a one time step outside my factory pattern and potential class definitions, then reference them in my potential classes which seems to work as expected. When I create the code objects though, it seems a couple different ways work and I'm wondering which is better and why (or is there a more correct technique in this situation)? The two different ways are illustrated below: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> def foo(st): ... print st ... >>> exp1 = 'foo("#expersion 1#")' >>> exp2 = 'foo("#expersion 2#")' >>> obj1 = compile(exp1, 'whatever', 'single') >>> exec obj1 #expersion 1# >>> obj2 = compile(exp2, 'whatever', 'exec') >>> exec obj2 #expersion 2# >>> Thank you, Lee C From shuying at gmail.com Tue Jun 21 10:28:06 2005 From: shuying at gmail.com (Shuying Wang) Date: Tue, 21 Jun 2005 18:28:06 +1000 Subject: [Tutor] not invoking the shell from python Message-ID: <75fa0c3a050621012844014ad5@mail.gmail.com> Hi tutors, I've got an external program that I'm calling from python with os.popen. The problem is that I need to pass this program an arbitrary body of text. I've tried escaping characters before passing it as input but the shell still expands out certain characters. I noticed with python2.4. How do I bypass the shell and hand arguments directly to the program? The problematic line in question looks like this: os.popen('''rt create -t ticket set requestor='%s' owner='%s' queue='%s' subject="%s" text="%s" status='%s' ''' % (data['requestor'],data['owner'],data['queue'], re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"', data['body']), data['status']) thanks in advance, Shuying From levity at gmail.com Tue Jun 21 17:15:17 2005 From: levity at gmail.com (lawrence wang) Date: Tue, 21 Jun 2005 11:15:17 -0400 Subject: [Tutor] Importing from directories below yourself... Message-ID: <22e13a2205062108152cf2853b@mail.gmail.com> Say I have a directory tree like this: foo - bar -- quux.py - baz -- glonk.py >From within glonk.py, how do I import quux.py? I've tried going to foo, running baz/glonk.py, and using "from bar import quux", but this doesn't seem to work. Thanks in advance! Lawrence From kent37 at tds.net Tue Jun 21 17:37:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jun 2005 11:37:17 -0400 Subject: [Tutor] Importing from directories below yourself... In-Reply-To: <22e13a2205062108152cf2853b@mail.gmail.com> References: <22e13a2205062108152cf2853b@mail.gmail.com> Message-ID: <42B8342D.8090707@tds.net> lawrence wang wrote: > Say I have a directory tree like this: > > foo > - bar > -- quux.py > - baz > -- glonk.py > >>From within glonk.py, how do I import quux.py? I've tried going to > foo, running baz/glonk.py, and using "from bar import quux", but this > doesn't seem to work. You need a file named __init__.py in bar/. The file can be empty; it is a marker that tells Python to treat bar/ as a package. You will also need __init__.py in baz/ if you want to be able to import glonk from another module. See http://docs.python.org/tut/node8.html#SECTION008400000000000000000 Kent From alan.gauld at freenet.co.uk Tue Jun 21 18:58:46 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 21 Jun 2005 17:58:46 +0100 Subject: [Tutor] not invoking the shell from python References: <75fa0c3a050621012844014ad5@mail.gmail.com> Message-ID: <00dc01c57682$82e997a0$4e4c8651@xp> > input but the shell still expands out certain characters. I noticed > with python2.4. How do I bypass the shell and hand arguments directly > to the program? The first thing I'd do is create the command string before passing it to popen - that way we can debug easier by seeing exactly what is being passed through! > The problematic line in question looks like this: cmd = '''rt create -t ticket set requestor='%s' owner='%s' queue='%s' subject="%s" text="%s" status='%s' ''' % (data['requestor'], data['owner'], data['queue'], re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"',data['body']), data['status']) # your code was missing the closing parens above but I assume # that was just a posting error? print cmd # for debug only os.popen(cmd) See if the line you are producing is what you think it should be. Try typing it in at the shell and see if you get the same effect? Without knowing the details of your data its hard to say much more. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From count0.djd at gmail.com Tue Jun 21 20:34:18 2005 From: count0.djd at gmail.com (David Driver) Date: Tue, 21 Jun 2005 13:34:18 -0500 Subject: [Tutor] who called the class method? Message-ID: <22803ae20506211134446a5b3e@mail.gmail.com> Is there a way to test if a class method was called from an instance? What I am trying to do is if a method is called from the class return a commanding proxy with an mock or stub type object as the proxied object. If it is called from the instance I want to return a proxy for the instance. Does what I am trying to do make sense? Thanks! -- *********************************** See there, that wasn't so bad. *********************************** From webdev at matheteuo.org Tue Jun 21 21:05:00 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 21 Jun 2005 15:05:00 -0400 Subject: [Tutor] MySQL Connection Function Message-ID: <20050621150500.5bc7661f@luke.matheteuo.rel> As a newbie developer, the easiest way for me to connect to MySQL is to just copy & paste the connection commands into each funtion I write. However, I know that's far from ideal, and consumes more time than its worth. I would like to create a MySQL connection function that I can just call up whenever I need it from within an other function. ### The Connection Definition ### # def mysql_Conn(): # Create a connection object and create a cursor. # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user", passwd="password", db="chaddb_test") # email text wrap here # Cursor = Con.cursor() ### The function that Calls the Connection ### def mbr_Roster(): mysql_Conn() # Make SQL string and execute it. sql = "SELECT fst_name, lst_name FROM person\ where env_num is not null\ order by lst_name" Cursor.execute(sql) # Fetch all results from the cursor into a sequence and close the # connection. Results = Cursor.fetchall() Con.close() How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()? Do I need to declare the cursor as a global variable? >From the Traceback: global name 'Cursor' is not defined Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From ajikoe at gmail.com Tue Jun 21 20:58:25 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 21 Jun 2005 20:58:25 +0200 Subject: [Tutor] MySQL Connection Function In-Reply-To: <20050621150500.5bc7661f@luke.matheteuo.rel> References: <20050621150500.5bc7661f@luke.matheteuo.rel> Message-ID: This a very simple connection using mysql. 1. connect to mysql: db = mySQLdb.connect(user='root',passwd='something') 2. To execute and get the result: c = db.cursor() c.execute(sql comment) result = c.fetchall() you can wrap it in a class object. pujo On 6/21/05, Don Parris wrote: > As a newbie developer, the easiest way for me to connect to MySQL is to > just copy & paste the connection commands into each funtion I write. > However, I know that's far from ideal, and consumes more time than its > worth. I would like to create a MySQL connection function that I can just > call up whenever I need it from within an other function. > > ### The Connection Definition ### > # def mysql_Conn(): > # Create a connection object and create a cursor. > # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user", > passwd="password", db="chaddb_test") # email text wrap here > # Cursor = Con.cursor() > > ### The function that Calls the Connection ### > def mbr_Roster(): > mysql_Conn() > > # Make SQL string and execute it. > sql = "SELECT fst_name, lst_name FROM person\ > where env_num is not null\ > order by lst_name" > Cursor.execute(sql) > > # Fetch all results from the cursor into a sequence and close the > # connection. > Results = Cursor.fetchall() > Con.close() > > How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()? Do I > need to declare the cursor as a global variable? > > >From the Traceback: > global name 'Cursor' is not defined > > > Don > -- > evangelinux GNU Evangelist > http://matheteuo.org/ http://chaddb.sourceforge.net/ > "Free software is like God's love - you can share it with anyone anytime > anywhere." > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From albertito_g at hotmail.com Tue Jun 21 21:15:51 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 21 Jun 2005 19:15:51 +0000 Subject: [Tutor] Built-in modules Message-ID: Hey tutors I have some classes I want to make available as built-in modules in Python 2.3.4 over Windows To make myself clear in case you don't understand I have the file List.py (a nested list C# like) and I want to be able to call the class List (which is inside the List.py) without having to copy it in every folder where I have a script that needs this module Can I do that? You see I googled about it but it seems I'm not using the right words. Best Regards Alberto From kent37 at tds.net Tue Jun 21 21:25:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jun 2005 15:25:33 -0400 Subject: [Tutor] who called the class method? In-Reply-To: <22803ae20506211134446a5b3e@mail.gmail.com> References: <22803ae20506211134446a5b3e@mail.gmail.com> Message-ID: <42B869AD.6080808@tds.net> David Driver wrote: > Is there a way to test if a class method was called from an instance? > > What I am trying to do is if a method is called from the class return > a commanding proxy with an mock or stub type object as the proxied > object. If it is called from the instance I want to return a proxy for > the instance. Hmm. Why not just differentiate them at the point of call? If you want to do class T(object): @classmethod def foo(cls): pass instead of t.foo() and T.foo() use t.foo_from_instance() and T.foo_from_class()?? If you must, I can think of two ways to do this. The __get__() method of a property has an instance parameter which is the instance or None, you could use that. Or you can use __new__() to create an instance method that shadows the classmethod. class Test2(object): class _foo(object): ''' A descriptor for Test2.foo ''' def __get__(self, instance, owner): # Test2.foo returns a function def _fooImpl(): Test2.fooImpl(instance) return _fooImpl foo = _foo() del _foo @classmethod def fooImpl(cls, instance): print 'fooImpl called with instance =', instance t = Test2() t.foo() Test2.foo() import new class Test(object): def __new__(cls): def foo(self): print 'foo() called from an instance' instance = object.__new__(cls) instance.foo = new.instancemethod(foo, instance, Test) return instance @classmethod def foo(cls): print 'foo() called as a classmethod' t = Test() t.foo() Test.foo() If you ask on comp.lang.python you will probably get more clever answers but really, why do you need to do this? Kent From kent37 at tds.net Tue Jun 21 21:46:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jun 2005 15:46:41 -0400 Subject: [Tutor] Built-in modules In-Reply-To: References: Message-ID: <42B86EA1.7000105@tds.net> Alberto Troiano wrote: > Hey tutors > > I have some classes I want to make available as built-in modules in Python > 2.3.4 over Windows > To make myself clear in case you don't understand I have the file List.py (a > nested list C# like) and I want to be able to call the class List (which is > inside the List.py) without having to copy it in every folder where I have a > script that needs this module In your Python23\Lib folder make a folder called site-packages. (If you already have one that's OK too.) Put List.py in site-packages. It will be available to any Python program. Kent From chuck at freshsources.com Tue Jun 21 22:52:09 2005 From: chuck at freshsources.com (Chuck Allison) Date: Tue, 21 Jun 2005 14:52:09 -0600 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <42B869AD.6080808@tds.net> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> Message-ID: <10110159435.20050621145209@freshsources.com> Sorry for the elementary question: I was wondering if someone could explain the difference to me between class and static methods. Coming from other languages, I'm used to static methods, but not "class methods". Thanks. -- Best regards, Chuck From mhansen at cso.atmel.com Tue Jun 21 22:43:28 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 21 Jun 2005 14:43:28 -0600 Subject: [Tutor] loading an image into a Postgre database Message-ID: <42B87BF0.9020202@cso.atmel.com> I'm having trouble loading an image into a Postgre database. The code is below as well as the traceback in the apache log. Is something up with my sqlStatement? Do I need to use something other than %s? How can I avoid that type error? Thanks, Mike #! /usr/bin/env python import cgi from pyPgSQL import PgSQL # from pyPgSQL.PgSQL import PgBytea def main(): form = cgi.FieldStorage() if form.has_key("filename"): item = form["filename"] imageName = form["imagename"] if item.file: data = item.file.read() data_obj = PgSQL.PgBytea(data) connectdb =PgSQL.connect('server:port:database:username:password') cur = connectdb.cursor() sqlStatement = """INSERT INTO images (image) VALUES (%s); """ % (data_obj) cur.execute(sqlStatement) cur.close() connectdb.commit() print "Content-type: text/html\n\n" print "image loaded" if __name__ == '__main__': main() Traceback (most recent call last): File "/var/www/htdocs/mtest/imagetest.py", line 28, in ? main() File "/var/www/htdocs/mtest/imagetest.py", line 20, in main cur.execute(sqlStatement) File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3038, in execute self.res = self.conn.conn.query(_qstr) TypeError: query() argument 1 must be string without null bytes, not str [Tue Jun 21 14:34:46 2005] [error] [client 10.95.100.11] Premature end of script headers: /var/www/htdocs/mtest/imagetest.py10.95.100.11] Premature end of script From chinook.nr at tds.net Tue Jun 21 23:28:48 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 21 Jun 2005 17:28:48 -0400 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> Message-ID: <0001HW.BEDDFED0000122F6F0407550@news.gmane.org> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote (in article <10110159435.20050621145209 at freshsources.com>): > Sorry for the elementary question: I was wondering if someone could > explain the difference to me between class and static methods. Coming > from other languages, I'm used to static methods, but not "class > methods". Thanks. > > Does this help (from the QR)? Static methods : Use staticmethod(f) to make method f(x) static (unbound). Class methods: like a static but takes the Class as 1st argument => Use f = classmethod(f) to make method f(theClass, x) a class method. The decorators @staticmethod and @classmethod replace more elegantly the equivalent declarations f = staticmethod(f) and f = classmethod(f). Lee C From dyoo at hkn.eecs.berkeley.edu Tue Jun 21 23:35:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Jun 2005 14:35:49 -0700 (PDT) Subject: [Tutor] loading an image into a Postgre database In-Reply-To: <42B87BF0.9020202@cso.atmel.com> Message-ID: On Tue, 21 Jun 2005, Mike Hansen wrote: > I'm having trouble loading an image into a Postgre database. The code is > below as well as the traceback in the apache log. Is something up with > my sqlStatement? Do I need to use something other than %s? How can I > avoid that type error? Hi Mike, At the moment, you're trying to do the direct value interpolation like this: > sqlStatement = """INSERT INTO images (image) > VALUES (%s); > """ % (data_obj) > cur.execute(sqlStatement) The issue is that this style of direct SQL interpolation won't work very well on non-SQLish data. Python has no clue what the context of your interpolation is: when you ask it to do: ###### sqlStatement = """INSERT INTO images (image) VALUES (%s); """ % data_obj ###### it has no idea that you're constructing an SQL statement, and it's oblivious to the special SQL quoting rules you need to use to pass binary data to the database. Another instance of this problem comes up even with normal string data: something like: cursor.execute("insert into people(name) values ('%s')" % name) will break as soon as someone with the name "O'Reilly" meets the application. Thankfully, you don't have to change much to fix the formatting bug. The only thing you'll need to do is let the SQL cursor do the value formatting for you: ###### sqlStatement = """INSERT INTO images (image) VALUES (%s); cur.execute(sqlStatement, (data_obj)) ###### Cursors know how to do the proper value interpolation that's specific to SQL: just pass the extra values to the execute() function, and the SQL driver will do the hard work. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Jun 21 23:38:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Jun 2005 14:38:34 -0700 (PDT) Subject: [Tutor] loading an image into a Postgre database In-Reply-To: Message-ID: > Thankfully, you don't have to change much to fix the formatting bug. The > only thing you'll need to do is let the SQL cursor do the value formatting > for you: > > ###### > sqlStatement = """INSERT INTO images (image) > VALUES (%s); > cur.execute(sqlStatement, (data_obj)) > ###### Hi Mike, Gaaa. I was a little sloppy there, wasn't I? Let me fix that: ###### sqlStatement = """INSERT INTO images (image) VALUES (%s);""" cur.execute(sqlStatement, (data_obj,)) ###### My apologies! From chuck at freshsources.com Tue Jun 21 23:58:09 2005 From: chuck at freshsources.com (Chuck Allison) Date: Tue, 21 Jun 2005 15:58:09 -0600 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <0001HW.BEDDFED0000122F6F0407550@news.gmane.org> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org> Message-ID: <628909047.20050621155809@freshsources.com> Hello Chinook, So is the main motivation for class methods so that you can have the class object available? It seems you can have that anyway in a static method by just asking. I'm sure there's a good reason for this, but I haven't yet gotten to the point of mastery where I can see a need for class methods (even after reading Martelli's Nutshell). I understand the syntax issues - I just don't see the need yet. Tuesday, June 21, 2005, 3:28:48 PM, you wrote: C> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote C> (in article <10110159435.20050621145209 at freshsources.com>): >> Sorry for the elementary question: I was wondering if someone could >> explain the difference to me between class and static methods. Coming >> from other languages, I'm used to static methods, but not "class >> methods". Thanks. >> >> C> Does this help (from the QR)? C> Static methods : Use staticmethod(f) to make method f(x) static (unbound). C> Class methods: like a static but takes the Class as 1st argument => Use f = C> classmethod(f) to make method f(theClass, x) a class method. C> The decorators @staticmethod and @classmethod replace more elegantly the C> equivalent declarations f = staticmethod(f) and f = classmethod(f). C> Lee C C> _______________________________________________ C> Tutor maillist - Tutor at python.org C> http://mail.python.org/mailman/listinfo/tutor -- Best regards, Chuck From alan.gauld at freenet.co.uk Tue Jun 21 18:47:41 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 21 Jun 2005 17:47:41 +0100 Subject: [Tutor] Numbers & Characters As Dictionary Keys References: <20050620051320.ACC69414E2@mail01.powweb.com><005501c5756f$b8d6ed40$4e4c8651@xp> <20050620141054.00f4dddf@luke.matheteuo.rel> Message-ID: <00d101c57680$f1661de0$4e4c8651@xp> > > print "%s\t%s" % (m,menu[m][0]) > > > I am curious what the "%" by itself is doing. Its a standard string formatting operation in Python. The % operator basically says substitute the values in the folowing tuple for the marked fields in the foregoing string. The print statement above therefore is roughly equivalent to: print m + '\t' + menu[m][0] But the formatting markers allow you to add formatting data like the minimum number of characters, right/left justification, number of digits after a decimal point, hex or decimal display of numbers etc etc. Take a look in the Python docs for string formatting. Alan G. From nephish at xit.net Wed Jun 22 02:17:30 2005 From: nephish at xit.net (nephish) Date: Tue, 21 Jun 2005 17:17:30 -0700 Subject: [Tutor] how do i pause a script ? Message-ID: <42B8AE1A.4010800@xit.net> Hey all, how do i pause a script. like print 'something' pause a half second print 'something else' any takers? From count0.djd at gmail.com Wed Jun 22 00:26:41 2005 From: count0.djd at gmail.com (David Driver) Date: Tue, 21 Jun 2005 17:26:41 -0500 Subject: [Tutor] who called the class method? In-Reply-To: <22803ae20506211134446a5b3e@mail.gmail.com> References: <22803ae20506211134446a5b3e@mail.gmail.com> Message-ID: <22803ae20506211526531e609a@mail.gmail.com> Ketn You are correct. What I will do is an instance method that calls the class method with an optional parameter. I don't know what I was thinking, I was just messing around with nested classes for the first time and kind of forgot how to program. On 6/21/05, David Driver wrote: > Is there a way to test if a class method was called from an instance? > From bvande at po-box.mcgill.ca Wed Jun 22 00:27:12 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 21 Jun 2005 18:27:12 -0400 Subject: [Tutor] how do i pause a script ? In-Reply-To: <42B8AE1A.4010800@xit.net> References: <42B8AE1A.4010800@xit.net> Message-ID: <42B89440.5050504@po-box.mcgill.ca> nephish said unto the world upon 21/06/2005 20:17: > Hey all, > how do i pause a script. like > print 'something' > pause a half second > print 'something else' > > any takers? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi, import time for i in range(5): time.sleep(i) print time.asctime() when run produces: >>> Tue Jun 21 18:23:00 2005 Tue Jun 21 18:23:01 2005 Tue Jun 21 18:23:03 2005 Tue Jun 21 18:23:06 2005 Tue Jun 21 18:23:10 2005 6.11 time -- Time access and conversions "sleep(secs) Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system." http://docs.python.org/lib/module-time.html Best, Brian vdB From alan.gauld at freenet.co.uk Wed Jun 22 00:49:14 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 21 Jun 2005 23:49:14 +0100 Subject: [Tutor] who called the class method? References: <22803ae20506211134446a5b3e@mail.gmail.com> Message-ID: <015401c576b3$72c788b0$4e4c8651@xp> > Is there a way to test if a class method was called from an instance? I think you'll need to override the __getattr__ method. It will pick up the call and you can test whether its a class mrethod being called. I think... > What I am trying to do is if a method is called from the > class return a commanding proxy with an mock or stub type > object as the proxied object. If it is called from the > instance I want to return a proxy for the instance. I'm not quite sure I understand because you are mixing object oriented terminology with procedural programming terminology. I think you mean you want to have a class with various methods. You may or may not have instances of the class. You want to know when a method is invoked whether this was via a direct call of the class's method or via a message being sent to an instance? OR do you mean you will have an actual class method (ie static in C++/Java speak) and want to know if the activating message was sent to the class object or to an instance of the class? Or do you want to know if the class method was invoked from within another method of the same class or invoked by a message sent from an instance of another class? Those are all different scenarios which could be described by your paragraph above, which do you mean? Or is it something different again? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Jun 22 00:52:48 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 21 Jun 2005 23:52:48 +0100 Subject: [Tutor] MySQL Connection Function References: <20050621150500.5bc7661f@luke.matheteuo.rel> Message-ID: <015901c576b3$f2599d70$4e4c8651@xp> > worth. I would like to create a MySQL connection function that I can just > call up whenever I need it from within an other function. Good idea! > ### The Connection Definition ### > # def mysql_Conn(): > # Create a connection object and create a cursor. > # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user", > passwd="password", db="chaddb_test") # email text wrap here > # Cursor = Con.cursor() return Con.cursor() > How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()? > Do I need to declare the cursor as a global variable? No you need to return it from your function. See the topic on modules and functions for more about returning values from functions. You might find you need to clear the cursor before using it too. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Jun 22 00:55:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 21 Jun 2005 23:55:52 +0100 Subject: [Tutor] Built-in modules References: Message-ID: <016001c576b4$5ff72370$4e4c8651@xp> > nested list C# like) and I want to be able to call the class List (which is > inside the List.py) without having to copy it in every folder where I have a > script that needs this module > > Can I do that? Yes. See Kent's reply to a similar post about creating a package. You can also just copy the module file List.py into a folder that's in your search path. That works too. But calling it List is probably bad since Python already has Lists. Maybe you could rename it something like NestedList? (Whatever that is!) HTH, Alan G. From chinook.nr at tds.net Wed Jun 22 00:56:29 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 21 Jun 2005 18:56:29 -0400 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org> <628909047.20050621155809@freshsources.com> Message-ID: <0001HW.BEDE135D0005F3E2F0407550@news.gmane.org> On Tue, 21 Jun 2005 17:58:09 -0400, Chuck Allison wrote (in article <628909047.20050621155809 at freshsources.com>): > Hello Chinook, > > So is the main motivation for class methods so that you can have the > class object available? It seems you can have that anyway in a static > method by just asking. I'm sure there's a good reason for this, but I > haven't yet gotten to the point of mastery where I can see a need for > class methods (even after reading Martelli's Nutshell). I understand > the syntax issues - I just don't see the need yet. > > Tuesday, June 21, 2005, 3:28:48 PM, you wrote: > > C> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote > C> (in article <10110159435.20050621145209 at freshsources.com>): > >>> Sorry for the elementary question: I was wondering if someone could >>> explain the difference to me between class and static methods. Coming >>> from other languages, I'm used to static methods, but not "class >>> methods". Thanks. >>> >>> > > C> Does this help (from the QR)? > > C> Static methods : Use staticmethod(f) to make method f(x) static (unbound). > C> Class methods: like a static but takes the Class as 1st argument => Use f > = > C> classmethod(f) to make method f(theClass, x) a class method. > > C> The decorators @staticmethod and @classmethod replace more elegantly the > C> equivalent declarations f = staticmethod(f) and f = classmethod(f). > > C> Lee C > > > C> _______________________________________________ > C> Tutor maillist - Tutor at python.org > C> http://mail.python.org/mailman/listinfo/tutor > > > > Chuck, Being fairly new to Python myself, I know how to create them and how to reference them. I also know to use a static method in a factory pattern because it's name is then local to the scope it is defined in and it is called without an instance argument. Mostly they work like simple functions that happen to be coded inside a class. Static methods are usually used with class attributes to manage information that spans all instances generated from a class (a book's example is keeping track of the number of instances generated from a class). Class methods are similar, but Python automatically passes the class (not an instance) into the method's leftmost argument. I have also read that such was introduced to clear up a gotcha before Python 2.3 Yea, yea, your saying, but you never answered my question :~) All I can relate to at this point in my learning cycle is that it's all a name space issue (re: instance, static and class). Maybe one of the gurus can enlighten both of us further. Lee C From mcf_webdev at matheteuo.org Wed Jun 22 00:33:30 2005 From: mcf_webdev at matheteuo.org (mcf_webdev@matheteuo.org) Date: Tue, 21 Jun 2005 22:33:30 -0000 Subject: [Tutor] Numbers & Characters As Dictionary Keys Message-ID: <20050621223330.877724157C@mail01.powweb.com> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20050621/6a4963fd/attachment.diff From alan.gauld at freenet.co.uk Wed Jun 22 01:03:00 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 22 Jun 2005 00:03:00 +0100 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com><42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> Message-ID: <016901c576b5$5fa341a0$4e4c8651@xp> > Sorry for the elementary question: I was wondering if someone could > explain the difference to me between class and static methods. Coming > from other languages, I'm used to static methods, but not "class > methods". Thanks. There probably is a deep and subtle difference in Python but to all intents and purposes they are the same thing. class method is the original and logically correct name and has been around in Smalltalk, Objective C, Lisp and most early OOP languages for a long time. It means a method of the class itself rather than of an instance and is typically used to perform an operation on the entire class - ie all the existing instances. The term 'static' comes from C++ where it refers to the fact that the code for static methods lives on the heap rather than the stack and so is persistent and the variables effectively shared - this echos C's use of 'static' variables. Java and Object Pascal copied the name from C++ and now Python seems to have adopted both names just to accomodate all tastes! Alan G. From kent37 at tds.net Wed Jun 22 01:03:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jun 2005 19:03:08 -0400 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <628909047.20050621155809@freshsources.com> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org> <628909047.20050621155809@freshsources.com> Message-ID: <42B89CAC.2020506@tds.net> Chuck Allison wrote: > Hello Chinook, > > So is the main motivation for class methods so that you can have the > class object available? It seems you can have that anyway in a static > method by just asking. No, a classmethod is passed the class that it is called on. If you have an inheritance tree you don't know this with a staticmethod. >>> class Test(object): ... @staticmethod ... def static(): # no args ... print 'I have no clue how I was called' ... @classmethod ... def cls(cls): ... print 'I was called on class', cls ... >>> t=Test() >>> t.static() I have no clue how I was called >>> t.cls() I was called on class >>> >>> class T2(Test): ... pass ... >>> t2=T2() >>> t2.static() I have no clue how I was called >>> t2.cls() I was called on class >>> T2.cls() I was called on class I can't think of a good use case for this at the moment...maybe some factory functions might care... Kent From python at venix.com Wed Jun 22 01:13:43 2005 From: python at venix.com (Python) Date: Tue, 21 Jun 2005 19:13:43 -0400 Subject: [Tutor] MySQL Connection Function Message-ID: <1119395623.24763.119.camel@www.venix.com> As a newbie developer, the easiest way for me to connect to MySQL is to > just copy & paste the connection commands into each funtion I write. > However, I know that's far from ideal, and consumes more time than its > worth. I would like to create a MySQL connection function that I can just > call up whenever I need it from within an other function. I like to use the following style of code. Since there will be passwords, the connection strings should be somewhat protected. Put them in a separate file that can be controlled. Here's my sample code. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #! /usr/bin/python # sqlconnect.py import MySQLdb as SQLdb db_parms = { 'regular': { 'host': 'localhost', 'user':'regular_user', 'passwd':'password', 'db':'some_database', }, 'premium': { 'host':'localhost', 'user':'premium_user', 'passwd':'password', 'db': 'SGSG02', }, "super": { 'host': 'localhost', 'unix_socket': '/var/lib/superdb/mysql.sock', 'user':'super_user', 'passwd':'password', 'db':'some_database', }, } def connect( parm_name): parms = db_parms[parm_name] return SQLdb.connect( **parms) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Use a dictionary to save the connect parameters. Different users and circumstances can require different parameters. To use this code import sqlconnect as sql conn = sql.connect('regular') # then get a cursor so that you can do something to the database curs = conn.Cursor() curs.execute(Some_SQL_Command) results = curs.fetchall() curs.close() Your example code seems to view getting a connection and a cursor as closely related. Typically, a connection is kept for the life of the application process and cursors are created, used, and closed as needed. -- Lloyd Kvam Venix Corp From count0.djd at gmail.com Wed Jun 22 02:23:44 2005 From: count0.djd at gmail.com (David Driver) Date: Tue, 21 Jun 2005 19:23:44 -0500 Subject: [Tutor] who called the class method? In-Reply-To: <015401c576b3$72c788b0$4e4c8651@xp> References: <22803ae20506211134446a5b3e@mail.gmail.com> <015401c576b3$72c788b0$4e4c8651@xp> Message-ID: <22803ae205062117234412c3ba@mail.gmail.com> You are right to be confused because I was as well. I was shooting for: > OR do you mean you will have an actual class method > (ie static in C++/Java speak) and want to know if the > activating message was sent to the class object or to > an instance of the class? The easiest solution was to do a class method 'GetDefaultProxy' that creates the default object (a stub with initial values) and creates the proxy with it and an instance method 'GetInstanceProxy' that creates the proxy for the already instanced object. I am working on integrating sqlobject with formencode's validators and a commanding proxy. Partly as an academic exercise. It is the biggest OO project that I have ever tried in any language and it has turned out to be pretty neat. There are a few details to work out but in the end I think that I will have something special. On 6/21/05, Alan G wrote: > > > Is there a way to test if a class method was called from an > instance? > > I think you'll need to override the __getattr__ method. > It will pick up the call and you can test whether its a > class mrethod being called. I think... > > > What I am trying to do is if a method is called from the > > class return a commanding proxy with an mock or stub type > > object as the proxied object. If it is called from the > > instance I want to return a proxy for the instance. > > I'm not quite sure I understand because you are mixing object > oriented terminology with procedural programming terminology. > > I think you mean you want to have a class with various methods. > You may or may not have instances of the class. > You want to know when a method is invoked whether this was via > a direct call of the class's method or via a message being > sent to an instance? > > OR do you mean you will have an actual class method > (ie static in C++/Java speak) and want to know if the > activating message was sent to the class object or to > an instance of the class? > > Or do you want to know if the class method was invoked > from within another method of the same class or invoked > by a message sent from an instance of another class? > > Those are all different scenarios which could be described > by your paragraph above, which do you mean? > Or is it something different again? > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > -- *********************************** See there, that wasn't so bad. *********************************** From webdev at matheteuo.org Wed Jun 22 06:33:35 2005 From: webdev at matheteuo.org (Don Parris) Date: Wed, 22 Jun 2005 00:33:35 -0400 Subject: [Tutor] MySQL Connection Function In-Reply-To: <1119395623.24763.119.camel@www.venix.com> References: <1119395623.24763.119.camel@www.venix.com> Message-ID: <20050622003335.5e9895f4@luke.matheteuo.rel> On Tue, 21 Jun 2005 19:13:43 -0400 Python wrote: > I like to use the following style of code. Since there will be > passwords, the connection strings should be somewhat protected. Put > them in a separate file that can be controlled. Here's my sample code. > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > > Your example code seems to view getting a connection and a cursor as > closely related. Typically, a connection is kept for the life of the > application process and cursors are created, used, and closed as needed. > > I'll be tinkering with your suggestion tonight. You're absolutely correct, though - my view of the connection & cursor is as you say. Thanks for correcting my understanding. I've gotten that impression based on the rather brief examples used in the tutorials. They merely give an example of connecting to the database and closing the connection, without describing the reality of the process. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From shidan at gmail.com Wed Jun 22 06:28:44 2005 From: shidan at gmail.com (Shidan) Date: Wed, 22 Jun 2005 00:28:44 -0400 Subject: [Tutor] List of regular expressions Message-ID: <429b380e050621212855fa9fa2@mail.gmail.com> Hi I have a list of regular expression patterns like such: thelist = ['^594694.*','^689.*','^241.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*'] Now I want to iterate thru each of these like: for pattern in thelist: regex=re.compile(pattern) if regex.match('24110'): the_pattern = pattern . . sys.exit(0) but in this case it will pick thelist[2] and not the list[3] as I wanted to, how can I have it pick the pattern that describes it better from the list. Thanks for your help and advice in advance, Shidan From hugonz-lists at h-lab.net Wed Jun 22 06:35:08 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 21 Jun 2005 23:35:08 -0500 Subject: [Tutor] not invoking the shell from python In-Reply-To: <75fa0c3a050621012844014ad5@mail.gmail.com> References: <75fa0c3a050621012844014ad5@mail.gmail.com> Message-ID: <42B8EA7C.6030701@h-lab.net> Hi Wang, You need to do what the shell does, all up the program directly, like this: fork parent, in the parent, reap the child in the child, call exec() with the subprogram as the argument Here's an example: import os program_executable = "/bin/ls" parameters = ["/home/me/file1.txt", "/home/me/file2.txt"] pid = os.fork() if pid==0: #I'm the child os.execv(program_executable, program_executable + parameters) else: #I'm the parent os.waitpid(-1) #wait and reap a child process ---------- I have not been able to test it since I'm in Windows but this should do. This is basically just an implementation of what system() does... the waitpid() step is necessary in order not to leave a zombie process lying around. Hope it helps, Hugo Shuying Wang wrote: > Hi tutors, > > I've got an external program that I'm calling from python with > os.popen. The problem is that I need to pass this program an arbitrary > body of text. I've tried escaping characters before passing it as > input but the shell still expands out certain characters. I noticed > with python2.4. How do I bypass the shell and hand arguments directly > to the program? > > The problematic line in question looks like this: > os.popen('''rt create -t ticket set requestor='%s' owner='%s' > queue='%s' subject="%s" text="%s" status='%s' ''' % > (data['requestor'],data['owner'],data['queue'], > re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"', > data['body']), data['status']) > > thanks in advance, > Shuying > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ewald.ertl at hartter.com Wed Jun 22 09:17:36 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 22 Jun 2005 09:17:36 +0200 Subject: [Tutor] List of regular expressions In-Reply-To: <429b380e050621212855fa9fa2@mail.gmail.com> References: <429b380e050621212855fa9fa2@mail.gmail.com> Message-ID: <20050622091736.00003943@sunray2.hartter.com> Hi Shidan! on Wed, 22 Jun 2005 00:28:44 -0400 Shidan wrote : --------------------------------------------------------------------------------------------- Shidan > Hi I have a list of regular expression patterns like such: Shidan > Shidan > thelist = ['^594694.*','^689.*','^241.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*'] Shidan > Shidan > Shidan > Now I want to iterate thru each of these like: Shidan > Shidan > for pattern in thelist: Shidan > regex=re.compile(pattern) Shidan > if regex.match('24110'): Shidan > the_pattern = pattern Shidan > . Shidan > . Shidan > sys.exit(0) Shidan > Shidan > but in this case it will pick thelist[2] and not the list[3] as I wanted to, Shidan > how can I have it pick the pattern that describes it better from the list. Perhaps you can reorder "thelist" in such a way, that the more extact pattern come's first thelist = ['^594694.*','^689.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*','^241.*'] So you cann exit if '^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*' is found, because here you want 241 followed by the number-combination which is an exacter description as '241.*'. ------------------- end ---------------------- HTH Ewald From alan.gauld at freenet.co.uk Wed Jun 22 09:35:15 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 22 Jun 2005 08:35:15 +0100 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com> <42B89CAC.2020506@tds.net> Message-ID: <01aa01c576fc$eec1c680$4e4c8651@xp> ----- Original Message ----- From: "Kent Johnson" > No, a classmethod is passed the class that it is called on. > If you have an inheritance tree you don't know this with a staticmethod. Aha! Like the OP I was aware of the class/no class distinction but couldn't see how this helped since a static method implicitly knows hich class it is in. But this example shows the big difference, the static method knows its in T1 but is not aware of inheritance so will always respond as a T1. The classmethod is aware of inheritance and will respond as whatever class is being accessed. So If I have a heirarchy of shapes and want a class method that only operates on the shape class itself, not on all the subclasses then I have to use staticmethod whereas if I want the class method to act on shape and each of its sub classes I must use a classmethod. The canonical example being counting instances. staticmethod would only allow me to count shapes but class method would allow me to count all the sub classes separately. Mind you this would require reprogramming the class method for each new shape which is probably a bad idea - overriding would be a better approach IMHO... Neat, I understand, I think... Thanks Kent. Alan G. > >>> class Test(object): > ... @staticmethod > ... def static(): # no args > ... print 'I have no clue how I was called' > ... @classmethod > ... def cls(cls): > ... print 'I was called on class', cls > ... > >>> class T2(Test): > ... pass > ... > >>> t2=T2() > >>> t2.static() > I have no clue how I was called > >>> t2.cls() > I was called on class > >>> T2.cls() > I was called on class From alan.gauld at freenet.co.uk Wed Jun 22 09:39:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 22 Jun 2005 08:39:38 +0100 Subject: [Tutor] List of regular expressions References: <429b380e050621212855fa9fa2@mail.gmail.com> Message-ID: <01b101c576fd$8b703fc0$4e4c8651@xp> > for pattern in thelist: > regex=re.compile(pattern) > if regex.match('24110'): > the_pattern = pattern > . > . > sys.exit(0) > > but in this case it will pick thelist[2] and not the list[3] as I wanted to, > how can I have it pick the pattern that describes it better from the list. Define 'better'. Both regex describe it equally well, how is Python supposed to know which one is 'better'? You have to tell it by ordering your list according to your idea of better, usually meaning most specific test first. Alan G From nequeo at gmail.com Wed Jun 22 11:04:43 2005 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 22 Jun 2005 19:04:43 +1000 Subject: [Tutor] how do i pause a script ? In-Reply-To: <42B8AE1A.4010800@xit.net> References: <42B8AE1A.4010800@xit.net> Message-ID: <42B929AB.9060303@gmail.com> >Hey all, >how do i pause a script. like >print 'something' >pause a half second >print 'something else' > > Hi, I think you're looking for 'sleep' in the time module. >>> import time >>> print "something" >>> time.sleep(1) >>> print "something else" That should do what you're describing. Incidentally, 'sleep' takes a float, not an int. So you can use time.sleep(1.5) to pause for one and a half seconds, and so forth. Hope that helps! If anyone knows a better way, feel free to correct me. I've only just started to learn Python myself. -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber nequeo at gmail.com From kent37 at tds.net Wed Jun 22 12:39:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Jun 2005 06:39:38 -0400 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <01aa01c576fc$eec1c680$4e4c8651@xp> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com> <42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> Message-ID: <42B93FEA.1080104@tds.net> Alan G wrote: > So If I have a heirarchy of shapes and want a class method that > only operates on the shape class itself, not on all the > subclasses then I have to use staticmethod whereas if I want > the class method to act on shape and each of its sub classes > I must use a classmethod. The canonical example being counting > instances. staticmethod would only allow me to count shapes > but class method would allow me to count all the sub classes > separately. Sounds good so far. Mind you this would require reprogramming the > class method for each new shape which is probably a bad > idea - overriding would be a better approach IMHO... Not sure why you think you have to write a new classmethod for each shape. Suppose you want to maintain creation counts for each class. Here is one way to do it using classmethods: class Shape(object): _count = 0 # Default for classes with no instances (cls.count() never called) @classmethod def count(cls): try: cls._count += 1 except AttributeError: cls._count = 1 @classmethod def showCount(cls): print 'Class %s has count = %s' % (cls.__name__, cls._count) def __init__(self): self.count() class Point(Shape): pass class Line(Shape): pass p, p2, p = Point(), Point(), Point() Point.showCount() Line.showCount() l = Line() Line.showCount() ### prints Class Point has count = 3 Class Line has count = 0 Class Line has count = 1 Kent From singletoned at gmail.com Wed Jun 22 14:24:59 2005 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 22 Jun 2005 13:24:59 +0100 Subject: [Tutor] Changing what you've already printed Message-ID: <34bb7f5b05062205249d1500d@mail.gmail.com> Is it possible (and easy) to change something you've already printed rather than print again? For example, if I'm making a little noughts and crosses game and I print the board: | | | | ___|___|___ | | | | ___|___|___ | | | | | | Then the computer has it's go, and rather than print the board out again and have the previous empty board appear higher up, I want to just add a X to the board I've already created. Eg. | | | | ___|___|___ | | | X | ___|___|___ | | | | | | I've programs do this on the command line in Linux, so I assume it must be possible. (I don't mind making my programs Linux only so that's not a problem). Any clues or pointers to documentation gratefully recieved. Thanks Ed From mhansen at cso.atmel.com Wed Jun 22 15:15:07 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 22 Jun 2005 07:15:07 -0600 Subject: [Tutor] loading an image into a Postgre database In-Reply-To: References: Message-ID: <42B9645B.1010306@cso.atmel.com> Thanks Danny. That did the trick. I think I had thought about putting the variables in the execute statement, but I didn't run across any examples. I'll need to read the DB API 2.0 docs some more. Mike Danny Yoo wrote: >>Thankfully, you don't have to change much to fix the formatting bug. The >>only thing you'll need to do is let the SQL cursor do the value formatting >>for you: >> >>###### >>sqlStatement = """INSERT INTO images (image) >> VALUES (%s); >>cur.execute(sqlStatement, (data_obj)) >>###### > > > > Hi Mike, > > > Gaaa. I was a little sloppy there, wasn't I? Let me fix that: > > ###### > sqlStatement = """INSERT INTO images (image) > VALUES (%s);""" > cur.execute(sqlStatement, (data_obj,)) > ###### > > > My apologies! > From pierre.barbier at cirad.fr Wed Jun 22 15:25:23 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 22 Jun 2005 15:25:23 +0200 Subject: [Tutor] Changing what you've already printed In-Reply-To: <34bb7f5b05062205249d1500d@mail.gmail.com> References: <34bb7f5b05062205249d1500d@mail.gmail.com> Message-ID: <42B966C3.2000205@cirad.fr> Well, it is certainly possible. First, the hard way: you use the ANSI termainal control commands (you can find the reference on the web, or if you need it I can send you an HTML file containing them). Second, the better way: you can use the ncurse library (via the curses Python module). There you'll get a whole toolkit for TUI (Terminal User Interface ;) ). BTW, if you happen to need this while drawing only a single line, the "\r" char gets you at the beginning of the current line ! So flushing stdout and then sending the "\r" char will allow you to overwrite the current line. Pierre Ed Singleton a ?crit : > Is it possible (and easy) to change something you've already printed > rather than print again? > > For example, if I'm making a little noughts and crosses game and I > print the board: > > | | > | | > ___|___|___ > | | > | | > ___|___|___ > | | > | | > | | > > Then the computer has it's go, and rather than print the board out > again and have the previous empty board appear higher up, I want to > just add a X to the board I've already created. > > Eg. > > > | | > | | > ___|___|___ > | | > | X | > ___|___|___ > | | > | | > | | > > I've programs do this on the command line in Linux, so I assume it > must be possible. (I don't mind making my programs Linux only so > that's not a problem). > > Any clues or pointers to documentation gratefully recieved. > > Thanks > > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kraus at hagen-partner.de Wed Jun 22 15:33:02 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed, 22 Jun 2005 15:33:02 +0200 Subject: [Tutor] Changing what you've already printed In-Reply-To: <34bb7f5b05062205249d1500d@mail.gmail.com> References: <34bb7f5b05062205249d1500d@mail.gmail.com> Message-ID: Curses might help you: http://docs.python.org/lib/module-curses.html Take a look at the Demo-directory which is included in the Python source-package. There is a curses subdir in it which might get you started. HTH, Wolfram Ed Singleton wrote: > Is it possible (and easy) to change something you've already printed > rather than print again? > > For example, if I'm making a little noughts and crosses game and I > print the board: > > | | > | | > ___|___|___ > | | > | | > ___|___|___ > | | > | | > | | > > Then the computer has it's go, and rather than print the board out > again and have the previous empty board appear higher up, I want to > just add a X to the board I've already created. > > Eg. > > > | | > | | > ___|___|___ > | | > | X | > ___|___|___ > | | > | | > | | > > I've programs do this on the command line in Linux, so I assume it > must be possible. (I don't mind making my programs Linux only so > that's not a problem). > > Any clues or pointers to documentation gratefully recieved. > > Thanks > > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From singletoned at gmail.com Wed Jun 22 17:01:04 2005 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 22 Jun 2005 16:01:04 +0100 Subject: [Tutor] Changing what you've already printed In-Reply-To: References: <34bb7f5b05062205249d1500d@mail.gmail.com> Message-ID: <34bb7f5b050622080175fa4502@mail.gmail.com> Yeah I think curses looks like it will do what I want. It doesn't look particularly easy to use (the [y,x] format is going to trip me up a lot) but I think I could write myself a simple interface to it that would make it simpler for me to use. Pierre's '/r' char thing isn't enough for what I want to do, but it's well worth knowing. Thanks All Ed On 6/22/05, Wolfram Kraus wrote: > Curses might help you: > http://docs.python.org/lib/module-curses.html > > Take a look at the Demo-directory which is included in the Python > source-package. There is a curses subdir in it which might get you started. > > HTH, > Wolfram > > Ed Singleton wrote: > > Is it possible (and easy) to change something you've already printed > > rather than print again? From RPhillips at engineer.co.summit.oh.us Wed Jun 22 19:48:49 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed, 22 Jun 2005 13:48:49 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? Message-ID: I believe I've tried every setting known to man, in every script in every little scrap of documentation available. XMLRPC requests using SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI script, and I get system lock ups and that's all. No error codes; no response whatsoever. I am using Python 2.3, Windows XP. I have run other CGI scripts in the same directory, so I know that works. Has anyone used this successfully? Can you share demo server and client scripts -- just an echo function or something? Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050622/d117b026/attachment.htm From webdev at matheteuo.org Wed Jun 22 20:37:10 2005 From: webdev at matheteuo.org (Don Parris) Date: Wed, 22 Jun 2005 14:37:10 -0400 Subject: [Tutor] MySQL Connection Function In-Reply-To: <1119395623.24763.119.camel@www.venix.com> References: <1119395623.24763.119.camel@www.venix.com> Message-ID: <20050622143710.45980b93@luke.matheteuo.rel> On Tue, 21 Jun 2005 19:13:43 -0400 Python wrote: Alright, I've had time to play with this and wanted to be sure I understand this well. It works, so I understand enough to make it work. However, I see a difference between your code and mine that makes me think I've missed something other than the relationship between the cursor & the connection > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > #! /usr/bin/python > # sqlconnect.py > import MySQLdb as SQLdb > I didn't see anything in the tutorial about the import as. Is this simply assigning the module a variable name? > > def connect( parm_name): > parms = db_parms[parm_name] > return SQLdb.connect( **parms) > <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< O.k., I was attempting to return "Con", not sql.connect() in my function. I think that's where part of my problem was. > > Use a dictionary to save the connect parameters. Different users and > circumstances can require different parameters. To use this code > > import sqlconnect as sql > conn = sql.connect('regular') > > # then get a cursor so that you can do something to the database > curs = conn.Cursor() > curs.execute(Some_SQL_Command) > results = curs.fetchall() > curs.close() > As is, I can copy/paste the 4 lines above into each function I've defined, and it works like a charm. What I would like now, is to use this like so: ### function for the cursor ### def get_Curs(): curs = conn.Cursor() curs.execute(sqlCmd) results = curs.fetchall() curs.close() Would I use curs.execute as an argument to get_Curs()? And would I then feed sqlCmd into mbr_Phone(sqlCmd)? ### Run get_Curs() for this query and give the user the results.### def mbr_Phone(): # how to get the cursor? get_Curs() # # Make SQL string and execute it. sqlCmd = "SELECT fst_name, lst_name, hphn FROM person\ order by lst_name" print 'Phone List' for record in Results: print record[0] , '', record[1], '\t', record[2] def a_Query(sqlCmd): get_Curs() code for a_Query def other_Query(sqlCmd): get_Curs() code for other_Query Kind of like this, anyway. Thanks for your patience. :) Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From Catdude2000 at aol.com Wed Jun 22 23:37:37 2005 From: Catdude2000 at aol.com (Catdude2000@aol.com) Date: Wed, 22 Jun 2005 17:37:37 EDT Subject: [Tutor] question about programmers Message-ID: What's the average age of a python user? This is my only question about programmers themselves. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050622/12aea76d/attachment-0001.htm From johnp at milwaukielumber.com Wed Jun 22 23:56:47 2005 From: johnp at milwaukielumber.com (John Purser) Date: Wed, 22 Jun 2005 14:56:47 -0700 Subject: [Tutor] question about programmers In-Reply-To: Message-ID: <200506222156.j5MLulWS012032@email.morseintranet.com> If that's your only question about programmers then you aint been around them much. I'm 45. ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Catdude2000 at aol.com Sent: Wednesday, June 22, 2005 14:38 To: tutor at python.org Subject: [Tutor] question about programmers What's the average age of a python user? This is my only question about programmers themselves. From alan.gauld at freenet.co.uk Thu Jun 23 00:59:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 22 Jun 2005 23:59:52 +0100 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com><42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> <42B93FEA.1080104@tds.net> Message-ID: <02ce01c5777e$194ae310$4e4c8651@xp> > class Shape(object): > _count = 0 > > @classmethod > def count(cls): > try: > cls._count += 1 > except AttributeError: > cls._count = 1 Ah, clever. This is where I thought I'd need an if/elif chain, adding a new clause for each subclass. i never thought of using a try/except to add an attribute to subclasses based on cls. I like it. Thanks again Kent. Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Jun 23 01:02:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Jun 2005 16:02:38 -0700 (PDT) Subject: [Tutor] question about programmers In-Reply-To: Message-ID: On Wed, 22 Jun 2005 Catdude2000 at aol.com wrote: > What's the average age of a python user? This is my only question about > programmers themselves. Hi Catdude, We actually had a small thread about this a few months back. The subject line "O.T." from that thread didn't make it particularly easy to find. *grin* But here it is: http://mail.python.org/pipermail/tutor/2004-December/034373.html The message threading doesn't work perfectly, but just search for the subject "O.T." from the December 2004 archives, and you should be able to find the right messages. Best of wishes to you! From alan.gauld at freenet.co.uk Thu Jun 23 01:04:08 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 00:04:08 +0100 Subject: [Tutor] Changing what you've already printed References: <34bb7f5b05062205249d1500d@mail.gmail.com> Message-ID: <02d301c5777e$b1f51220$4e4c8651@xp> > Is it possible (and easy) to change something you've already printed > rather than print again? Its possible. How easy depends on where you are printing. Using curses in a character based terminal its easy, just define the window within the screen that you want to change. Similarly any GUI toolkit will likewise be easy. But if you are uising a teletype interface you are reduced to using backspace characters and it gets messy, even with a cursor addressable screen (such as a 3270 or ANSI terminal) it still gets very hard to keep track of exactly what to erase and when. > For example, if I'm making a little noughts and crosses > game and I print the board: I'd use curses for this. Or better still a GUI. > I've programs do this on the command line in Linux, so > I assume it must be possible. Curses comes as standard on linux... Alan G. From alan.gauld at freenet.co.uk Thu Jun 23 01:05:47 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 00:05:47 +0100 Subject: [Tutor] Changing what you've already printed References: <34bb7f5b05062205249d1500d@mail.gmail.com> <42B966C3.2000205@cirad.fr> Message-ID: <02d801c5777e$ed8295b0$4e4c8651@xp> > BTW, if you happen to need this while drawing only a single line, the > "\r" char gets you at the beginning of the current line ! And '\h' should delete back one char. Between the two techniques you can control a single line, but not, sadly, a noughts and crosses board! Alan G. From alan.gauld at freenet.co.uk Thu Jun 23 01:08:28 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 00:08:28 +0100 Subject: [Tutor] question about programmers References: Message-ID: <02ea01c5777f$4d62a6f0$4e4c8651@xp> > What's the average age of a python user? This is my only question about > programmers themselves. > There was a thread on this on comp.lang.python recently. Try searching google groups and you should find literally hundreds of replies! >From memory average was around 30 but with a distribution from about 10 to over 70... Be really keen and write a python program to collect the answers parse out the ages and do the sums... :-) Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Jun 23 01:22:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Jun 2005 16:22:05 -0700 (PDT) Subject: [Tutor] age of python programmers In-Reply-To: Message-ID: On Wed, 22 Jun 2005, Danny Yoo wrote: > > > On Wed, 22 Jun 2005 Catdude2000 at aol.com wrote: > > > What's the average age of a python user? This is my only question about > > programmers themselves. > > The message threading doesn't work perfectly, but just search for the > subject "O.T." from the December 2004 archives, and you should be able to > find the right messages. Ah, from that thread, Roel Schroeven mentioned that he has collected statistics from comp.lang.python, and nicely presented them on his web site: http://mail.python.org/pipermail/tutor/2004-December/034378.html http://www.roelschroeven.net/pythonages/ So there you go. *grin* I'm sure it's not completely representative, but it appears to be a good rough sample. From dyoo at hkn.eecs.berkeley.edu Thu Jun 23 01:30:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Jun 2005 16:30:35 -0700 (PDT) Subject: [Tutor] List of regular expressions In-Reply-To: <429b380e050621212855fa9fa2@mail.gmail.com> Message-ID: On Wed, 22 Jun 2005, Shidan wrote: > Hi I have a list of regular expression patterns like such: > > thelist = ['^594694.*','^689.*','^241.*', > '^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*'] > > > Now I want to iterate thru each of these like: > > for pattern in thelist: > regex=re.compile(pattern) > if regex.match('24110'): > the_pattern = pattern > . > . > sys.exit(0) > > but in this case it will pick thelist[2] and not the list[3] as I wanted > to, how can I have it pick the pattern that describes it better from the > list. Hi Shidan, Regular expressions don't have a concept of "better match": a regular expression either matches a pattern or it doesn't. It's binary: there's no concept of the "specificity" of a regular expression match unless you can define one yourself. Intuitively, it sounds like you're considering anything that uses a wildcard to be less match-worthy than something that uses simpler things like a character set. Does that sound right to you? If so, then perhaps we can write a function that calculates the "specificity" of a regular expression, so that 'theList[2]' scores less highly than 'theList[3]'. You can then see which regular expressions match your string, and then rank them in terms of specificity. But it's important to realize that what you've asked is actually a subjective measure of "best match", and so we have to define specifically what "best" means to us. (Other people might consider short regular expressions to be better because they're shorter and easier to read!) Tell us more about the problem, and we'll do what we can to help. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Thu Jun 23 01:32:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Jun 2005 16:32:06 -0700 (PDT) Subject: [Tutor] Changing what you've already printed In-Reply-To: <34bb7f5b050622080175fa4502@mail.gmail.com> Message-ID: On Wed, 22 Jun 2005, Ed Singleton wrote: > Yeah I think curses looks like it will do what I want. It doesn't > look particularly easy to use (the [y,x] format is going to trip me up > a lot) but I think I could write myself a simple interface to it that > would make it simpler for me to use. Hi Ed, You might also find: http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py helpful as an example of what curses can do. Best of wishes! From chuck at freshsources.com Thu Jun 23 01:35:34 2005 From: chuck at freshsources.com (Chuck Allison) Date: Wed, 22 Jun 2005 17:35:34 -0600 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <02ce01c5777e$194ae310$4e4c8651@xp> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com><42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> <42B93FEA.1080104@tds.net> <02ce01c5777e$194ae310$4e4c8651@xp> Message-ID: <42B9F5C6.1080307@freshsources.com> This is a neat trick. But can't this also be done with a static method that accesses a static data attribute the same way? Alan G wrote: >>class Shape(object): >> _count = 0 >> >> @classmethod >> def count(cls): >> try: >> cls._count += 1 >> except AttributeError: >> cls._count = 1 >> >> > >Ah, clever. This is where I thought I'd need an if/elif >chain, adding a new clause for each subclass. i never thought of >using a try/except to add an attribute to subclasses based on cls. > >I like it. > >Thanks again Kent. > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From denise.hartley at gmail.com Thu Jun 23 01:46:09 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 22 Jun 2005 16:46:09 -0700 Subject: [Tutor] samples Message-ID: <8daabe56050622164654d72090@mail.gmail.com> Hello, everyone! I hope this isnt the wrong place to post this, but the internet has not been very helpful to me on this point. I am looking for several (open-source, obviously) clones of Bejeweled (the pop cap game) or something like it. There is one listed at pygame (and that same one is referenced at sourceforge and other places), and I have downloaded it and am trying to go through the code, but it's made up of 46 different .py files, none of which seem to be the "main" game (lots of little modules, like an input box, a high score list, etc). It's a lot harder for someone new to programming to read. (It doesn't actually play on my computer either, but that's another matter). Also, the reason that I would like to see several examples is that I would like to see how different people approach things like keeping track of the columns' being filled or not, how they approach timing questions, whether or not they give hints, that kind of thing. I did this when first beginning python, with simple arcade games: it helps me a great deal to see how different people try to do the same (or similar) things in their code, especially when that code is actually documented. As I've said in here a hundred times, I am very new to this, and I know that my experience with space invaders - type games really helped solidify my understanding of what I was doing in my own game. I have donwloaded tetris clones as well, and have made one myself (getting toward the falling objects idea, anyway), but they havent been on a static board which is filled at all times with objects. Nor have I ever, actually, done anything with mouse clicks (!!). In any case, I am certainly not asking for howto's on all these complex subjects. For one, I have stacks of howto's and other books at my disposal, and what's more, I want to figure it out on my own. What I *am* looking for, if you have it or know of anyone who does, is *simple* source code files (preferrably the entire game's code is in one .py file), with lots of documentation, to familiarize myself further with examples of code, and particularly, to see how others attack some of the problems I am looking at now. Does anyone have any little "gamelets" like these, or know of well-documented comparable examples? I'd particularly love some bejeweled examples, but really, the more "little examples" I can look through and play with the better off I am. (And yes, I have checked and regularly do check pygame, sourceforge, google, and the like - I'm just looking for others that a). might not get posted online, b). someone just was playing around with, or c). that you have or know of that are particularly easy to 'read'). Thanks for any suggestions! ~Denise From dyoo at hkn.eecs.berkeley.edu Thu Jun 23 01:46:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Jun 2005 16:46:08 -0700 (PDT) Subject: [Tutor] loading an image into a Postgre database In-Reply-To: <42B9645B.1010306@cso.atmel.com> Message-ID: On Wed, 22 Jun 2005, Mike Hansen wrote: > Thanks Danny. That did the trick. I think I had thought about putting > the variables in the execute statement, but I didn't run across any > examples. I'll need to read the DB API 2.0 docs some more. Hi Mike, No problem; it's actually a really common mistake in many introductory language/db binding tutorials too. AMK's tutorial doesn't mention it: http://www.amk.ca/python/writing/DB-API.html so you'd have to either read the API really closely, read a tutorial that does mention it, or get someone to point the problem out. *grin* By the way, if you're going to do a lot of DB stuff, you may find the DB-SIG a useful resource too: http://mail.python.org/mailman/listinfo/db-sig Best of wishes! From maxnoel_fr at yahoo.fr Thu Jun 23 01:55:04 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 23 Jun 2005 01:55:04 +0200 Subject: [Tutor] Changing what you've already printed In-Reply-To: <02d301c5777e$b1f51220$4e4c8651@xp> References: <34bb7f5b05062205249d1500d@mail.gmail.com> <02d301c5777e$b1f51220$4e4c8651@xp> Message-ID: <80841485-71B4-40F7-B39A-9F5E507D9F08@yahoo.fr> On Jun 23, 2005, at 01:04, Alan G wrote: > Curses comes as standard on linux... > They also do on Windows. Just listen to any user when the bloody thing crashes. (sorry, couldn't resist :p ) More seriously, I seem to recall that on the contrary, the Windows Python distribution does not include the curses module (you have to use msvcrt[?] instead). I wonder why, because I'm pretty sure I saw (C) curses-based applications running on Windows (NetHack is one, AFAIK). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger Téléchargez cette version sur http://fr.messenger.yahoo.com From chuck at freshsources.com Thu Jun 23 02:18:10 2005 From: chuck at freshsources.com (Chuck Allison) Date: Wed, 22 Jun 2005 18:18:10 -0600 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <42B93FEA.1080104@tds.net> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com> <42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> <42B93FEA.1080104@tds.net> Message-ID: <1983494339.20050622181810@freshsources.com> Hello Kent, This is the killer example I've been looking for. Now I understand. Sorry I've been so dense. This is way cool. Thanks. Wednesday, June 22, 2005, 4:39:38 AM, you wrote: KJ> Not sure why you think you have to write a new classmethod for KJ> each shape. Suppose you want to maintain creation counts for each KJ> class. Here is one way to do it using classmethods: KJ> class Shape(object): KJ> _count = 0 # Default for classes with no instances (cls.count() never called) KJ> @classmethod KJ> def count(cls): KJ> try: KJ> cls._count += 1 KJ> except AttributeError: KJ> cls._count = 1 KJ> @classmethod KJ> def showCount(cls): KJ> print 'Class %s has count = %s' % (cls.__name__, cls._count) KJ> def __init__(self): KJ> self.count() KJ> class Point(Shape): pass KJ> class Line(Shape): pass KJ> p, p2, p = Point(), Point(), Point() KJ> Point.showCount() KJ> Line.showCount() KJ> l = Line() KJ> Line.showCount() KJ> ### prints KJ> Class Point has count = 3 KJ> Class Line has count = 0 KJ> Class Line has count = 1 KJ> Kent -- Best regards, Chuck From nephish at xit.net Thu Jun 23 05:20:18 2005 From: nephish at xit.net (nephish) Date: Wed, 22 Jun 2005 20:20:18 -0700 Subject: [Tutor] database app In-Reply-To: <01b801c5774e$7d5b7f70$4e4c8651@xp> References: <42B48930.6070404@xit.net> <001201c574dc$89e0b7c0$4e4c8651@xp> <42B97A54.6070506@xit.net> <01b801c5774e$7d5b7f70$4e4c8651@xp> Message-ID: <42BA2A72.4050701@xit.net> Alan G wrote: >>>going on at a time I'd consider moving the database >>>or using snapshot technology or similar, Access locks >>>by pages (default 2K?) which can mean a lot of data >>>rows being locked by a single update. >>> >>> >>> >>ok, another question about this, if i use a snapshot, copy that >> >> >snapshot to > > >>the shared folder, i should be ok, to not lock it up for that main >> >> >app > > >>that uses this database right? the database has a .mdb extension, >> >> >ODBC > > >>provides for that right? i have been looking but not finding out if >> >> >i > > >>can copy the .mdb access database file to a windows XP shared >> >> >folder, > > >>copy that into my debian linux box and manipulate the database. >> >> > >I'm no expert but I don't think the file on its own will be enough. >You need the Access engine for the ODBC driver to work - so it needs >to be on windows. > >When I said snapshot I expected you to copy the data to a new Access >database, run the web app and alongside have a synchronisation job >running looking at the audit trails on both sides and synchronising >every 15 minutes or so. Of course that has its own locking issues >since Access doesn't really support that either, but maybe you could >copy the snapshot onto MySQL or somesuch, then at least the locking >problems are only in one direction! > >It might be worth checking MSDN to see if they recommend a solution. >I know we gave up on Access for web apps but presumably others >have grappled and found working solutions? > >Alan G. > > > > ok, i have looked and looked, and i cant find a way to use an access mdb file. yes from windows, no from linux. no way around it, i gotta be able to export access to a string of text somewhere. i think that access can export to and from excel - perhaps with the cv module i can do something with the log file. but right now, unless my research is bugged out, access is a no-go solution for linux. thanks, shawn From kent37 at tds.net Thu Jun 23 05:32:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Jun 2005 23:32:17 -0400 Subject: [Tutor] samples In-Reply-To: <8daabe56050622164654d72090@mail.gmail.com> References: <8daabe56050622164654d72090@mail.gmail.com> Message-ID: <42BA2D41.2000007@tds.net> D. Hartley wrote: > Does anyone have any little "gamelets" like these, or know of > well-documented comparable examples? I'd particularly love some > bejeweled examples, but really, the more "little examples" I can look > through and play with the better off I am. (And yes, I have checked > and regularly do check pygame, sourceforge, google, and the like - I'm > just looking for others that a). might not get posted online, b). > someone just was playing around with, or c). that you have or know of > that are particularly easy to 'read'). You might be interested in Livewires. It might be too simple for you, but it's worth looking at. http://www.livewires.org.uk/python/ Kent From kent37 at tds.net Thu Jun 23 05:53:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Jun 2005 23:53:59 -0400 Subject: [Tutor] Refreshing the interpreter environment In-Reply-To: References: <22e13a2205062009213e113edf@mail.gmail.com> Message-ID: <42BA3257.7010502@tds.net> Javier Ruere wrote: > lawrence wang wrote: > >>How do I refresh the interpreter environment without restarting it, if >>possible? For example, I'm using the interpreter to test a class I'm >>writing; importing and instantiating it reveals a typo; I go and fix >>the typo. Now, is there any way to reload the class afresh? Simply >>importing again doesn't seem to do it. Thanks in advance for your >>help. > > > Yes: > > (echo "a=1" > a.py) > >>>>import a >>>>a.a > > 1 > (echo "a=2" > a.py) > >>>>a = reload(a) >>>>a.a > > 2 but be careful, if you try from a import a then the value of a will not change when a.py changes; you have created a new variable in your namespace that is bound to 1. Also if there is a class defined in a.py and you create instances of the class, when you reload(a) the instances will still refer to the old class. I'm sure there are many other ways this method can fail. You should have a clear understanding of namespaces to use it reliably; otherwise you may be surprised. Kent From nephish at xit.net Thu Jun 23 09:19:50 2005 From: nephish at xit.net (nephish) Date: Thu, 23 Jun 2005 00:19:50 -0700 Subject: [Tutor] strip an email Message-ID: <42BA6296.9080803@xit.net> Does anyone know how to strip everything off of an email? i have a little app that i am working on to read an email message and write the body of a message to a log file. each email this address gets is only about three to five lines long. but i cannot seem to get just the body filtered through. i get all the headers, the path, what spam-wall it went through, etc... any suggestions would be greatly appreciated . thanks From alan.gauld at freenet.co.uk Thu Jun 23 09:31:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 08:31:59 +0100 Subject: [Tutor] Class vs. Static Methods References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com><42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> <42B93FEA.1080104@tds.net> <02ce01c5777e$194ae310$4e4c8651@xp> <42B9F5C6.1080307@freshsources.com> Message-ID: <02ef01c577c5$a426b530$4e4c8651@xp> > This is a neat trick. But can't this also be done with a static method > that accesses a static data attribute the same way? I don't think so because the static mehod can only see the attributes of Shape not of Line. It doesn't have access to the cls value in Kent's code below... > >> @classmethod > >> def count(cls): > >> try: > >> cls._count += 1 > >> except AttributeError: > >> cls._count = 1 So if it tried to incremet count every instance of every kind of shape would increment the shape counter - which may be what you want under some circumstances, but it wouldn't know which of the subclasses was calling it so couldn't access their counters. I think thats right!? Alan G. From alan.gauld at freenet.co.uk Thu Jun 23 09:36:03 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 08:36:03 +0100 Subject: [Tutor] Changing what you've already printed References: <34bb7f5b05062205249d1500d@mail.gmail.com> <02d301c5777e$b1f51220$4e4c8651@xp> <80841485-71B4-40F7-B39A-9F5E507D9F08@yahoo.fr> Message-ID: <02f401c577c6$35c107c0$4e4c8651@xp> > > Curses comes as standard on linux... > > > > More seriously, I seem to recall that on the contrary, the > Windows Python distribution does not include the curses module That's correct. > have to use msvcrt[?] instead). I wonder why, because I'm pretty sure > I saw (C) curses-based applications running on Windows (NetHack is > one, AFAIK). There is a DOS implementation but a) it is not complete and b) it doesn't always work well. But the problem for Python is that until someone builds a reliable and complete C version for windoze the Python wrapper won't work... I suspect part of the problem is that the DOS terminal, even with ANSI mode switched on, which is not common nowadays, is still pretty limited compared to a VT100/200 terminal in terms of cursor control. Alan G. From shuying at gmail.com Thu Jun 23 09:41:32 2005 From: shuying at gmail.com (Shuying Wang) Date: Thu, 23 Jun 2005 17:41:32 +1000 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <75fa0c3a05062300415395431a@mail.gmail.com> I'm not sure what you're trying to do. But I run cgi scripts and make xmlrpc requests with xmlrpclib with a connection with xmlrpclib.Server(server_uri), though I'm only doing this client side. I'm not running the server as cgi. On 6/23/05, Ron Phillips wrote: > > I believe I've tried every setting known to man, in every script in every > little scrap of documentation available. XMLRPC requests using > SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI > script, and I get system lock ups and that's all. No error codes; no > response whatsoever. > > I am using Python 2.3, Windows XP. I have run other CGI scripts in the same > directory, so I know that works. > > Has anyone used this successfully? Can you share demo server and client > scripts -- just an echo function or something? > > Ron > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Thu Jun 23 10:06:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 09:06:59 +0100 Subject: [Tutor] samples References: <8daabe56050622164654d72090@mail.gmail.com> Message-ID: <032501c577ca$883e2380$4e4c8651@xp> > What I *am* looking for, if you have it or know of anyone who does, is > *simple* source code files (preferrably the entire game's code is in > one .py file), Thats unlikely to happen because its very bad practice and Python tries to make it easy NOT to do that. Breaking code into modules makes it easier to maintain and easier to reuse. But the downside is trying to navigate it can be tricky - especially when you don;t know which one is main... Try a grep for __main__ to see if you can find the if "__name__ === " trick. Or try grep for a def main. In mainstream languages like C/Java you can use a feature of vim/emacs called tags to navigate code across multiple files, some IDEs have similar menu options, where you highlight a function call and say 'go to source' and the IDE finds the file with the definition... Makes browsing code much easier. Of course better still is a design document! > Does anyone have any little "gamelets" like these, There are several games on Useless Python, including my guessing games framework (which is from my book) and the heavily commented code is zipped up on Useless (hmgui.zip). But most of them don't use the pygame framework. HTH, Alan G. From kent37 at tds.net Thu Jun 23 13:01:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 07:01:16 -0400 Subject: [Tutor] Class vs. Static Methods In-Reply-To: <02ef01c577c5$a426b530$4e4c8651@xp> References: <22803ae20506211134446a5b3e@mail.gmail.com> <42B869AD.6080808@tds.net> <10110159435.20050621145209@freshsources.com> <0001HW.BEDDFED0000122F6F0407550@news.gmane.org><628909047.20050621155809@freshsources.com><42B89CAC.2020506@tds.net> <01aa01c576fc$eec1c680$4e4c8651@xp> <42B93FEA.1080104@tds.net> <02ce01c5777e$194ae310$4e4c8651@xp> <42B9F5C6.1080307@freshsources.com> <02ef01c577c5$a426b530$4e4c8651@xp> Message-ID: <42BA967C.20303@tds.net> Alan G wrote: >>This is a neat trick. But can't this also be done with a static > > method > >>that accesses a static data attribute the same way? > > > I don't think so because the static mehod can only see > the attributes of Shape not of Line. Well, it can *see* Point._count and Line._count, it just doesn't know which one it should increment. > It doesn't have > access to the cls value in Kent's code below... > > >>>> @classmethod >>>> def count(cls): >>>> try: >>>> cls._count += 1 >>>> except AttributeError: >>>> cls._count = 1 > > > So if it tried to incremet count every instance of every > kind of shape would increment the shape counter - which may > be what you want under some circumstances, but it wouldn't > know which of the subclasses was calling it so couldn't > access their counters. Yes. In the absence of inheritance module methods, staticmethods and classmethods all have access to pretty much the same information. In the presence of inheritance, if you want to know the actual class a method was called on you need a classmethod. Kent From kent37 at tds.net Thu Jun 23 13:20:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 07:20:15 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <42BA9AEF.50308@tds.net> Ron Phillips wrote: > I believe I've tried every setting known to man, in every script in > every little scrap of documentation available. XMLRPC requests using > SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI > script, and I get system lock ups and that's all. No error codes; no > response whatsoever. > > I am using Python 2.3, Windows XP. I have run other CGI scripts in the > same directory, so I know that works. > > Has anyone used this successfully? Can you share demo server and client > scripts -- just an echo function or something? The server example in the docs works for me with one correction: ## cgi-bin/xmlrpc.py from SimpleXMLRPCServer import CGIXMLRPCRequestHandler class MyFuncs: def div(self, x, y) : return x // y handler = CGIXMLRPCRequestHandler() handler.register_function(pow) handler.register_function(lambda x,y: x+y, 'add') handler.register_introspection_functions() handler.register_instance(MyFuncs()) handler.handle_request() ## Run a simple CGI server by opening a command line to the parent dir of cgi-bin and running python -c "import CGIHTTPServer; CGIHTTPServer.test()" ## >From the command line: >>> import xmlrpclib >>> server = xmlrpclib.ServerProxy("http://localhost:8000/cgi-bin/xmlrpc.py") >>> server.system.listMethods() ['add', 'div', 'pow', 'system.listMethods', 'system.methodHelp', 'system.methodSignature'] >>> server.add(1, 2) 3 >>> server.pow(2, 10) 1024 Using Python 2.4.1 on Windows 2000 Kent From project5 at redrival.net Thu Jun 23 13:25:12 2005 From: project5 at redrival.net (Andrei) Date: Thu, 23 Jun 2005 11:25:12 +0000 (UTC) Subject: [Tutor] samples References: <8daabe56050622164654d72090@mail.gmail.com> Message-ID: D. Hartley gmail.com> writes: > code, but it's made up of 46 different .py files, none of which seem > to be the "main" game (lots of little modules, like an input box, a > high score list, etc). It's a lot harder for someone new to > programming to read. Identify the main file (the one that you launch) and go from there. A search for 'main' might turn up something. Having all code in one big file makes it more difficult to read for advanced users, but also for beginners. Make sure you use a good editor with code outline support (outline of classes/methods), it makes it easier to explore the code. > Also, the reason that I would like to see several examples is that I > would like to see how different people approach things like keeping > track of the columns' being filled or not, how they approach timing > questions, whether or not they give hints, that kind of thing. I did > game. I have donwloaded tetris clones as well, and have made one > myself (getting toward the falling objects idea, anyway), but they > havent been on a static board which is filled at all times with > objects. Nor have I ever, actually, done anything with mouse clicks > (!!). Except for tetris, you could also look at othello/reversi, five in a row, checkers and chess. They deal with sequences of pieces, clicking on pieces to move them and (depending on the implementation and target audience) hints. It might be even more instructive to look at differences between the games than to look at differences within a game. > at my disposal, and what's more, I want to figure it out on my own. I'd say you shouldn't be shy about borrowing ideas (and even code, if the licence allows it) from other people. Usually the best way to learn is not by starting with the development of the wheel. > Does anyone have any little "gamelets" like these, or know of I remember not too long ago there was a discussion on the pygame list about developing a partygame-like system, with a framework capable of loading all kinds of simple minigames. I don't know how far it is by now, but if you look in the pygame mailing list archives you should be able to find it. Yours, Andrei From mhansen at cso.atmel.com Thu Jun 23 16:20:56 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 23 Jun 2005 08:20:56 -0600 Subject: [Tutor] getting an image out of a postgre database Message-ID: <42BAC548.8060409@cso.atmel.com> Well, I've managed to get an image into a postgre database, but now I'm having trouble getting it out. #! /usr/bin/env python from pyPgSQL import PgSQL def main(): connectdb = PgSQL.connect('server:port:database:username:password') cur = connectdb.cursor() sqlStatement = """SELECT image from images where image_id = 1""" cur.execute(sqlStatement) rec = cur.fetchone() # TODO make temp file name include image_id. # TODO use tempfile module # TODO clean up old temp files tempFileName = "1.jpg" tempFile = open(tempFileName, "w") tempFile.write(rec[0]) tempFile.close() cur.close() print "Content-type: text/html\n\n" print """" """ if __name__ == '__main__': main() Traceback (most recent call last): File "./dispimage.py", line 39, in ? main() File "./dispimage.py", line 16, in main tempFile.write(rec[0]) TypeError: argument 1 must be string or read-only character buffer, not instance So, rec[0] is an instance, but an instance of what? Since I needed to use the PgSQL.PgBytea method on the image before inserting it into the database, do I need to use a similar method to undo what PgBytea did to it, or am I incorrectly writing this binary data? I tried PgSQL.PgUnQuoteBytea(rec[0]), but that didn't work. If this is more appropriate for another mail list, let me know. Mike From Christian.Wyglendowski at greenville.edu Thu Jun 23 17:26:44 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 23 Jun 2005 10:26:44 -0500 Subject: [Tutor] database app Message-ID: > -----Original Message----- > > Hey there, Hi, > i have used the cgi module and dig it. > heres the deal, > my employer wants me to build a dynamic website that will > access a > database and display customer > information on web. ok, easy enough. Looks like some others have pointed you in the right direction as far as interfacing with Access. For the "web" part of your application, I'd recommend CherryPy (http://www.cherrypy.org). It lets you write web applications in python. Example: from time import ctime from cherrypy import cpg header = """ %s """ footer = """ """ class Site: def index(self): yield header % ('Index',) yield "

Here is a header

\n" yield "

Here is a paragraph. It is currently is %s.

\n" % (ctime(),) yield "

Here is a list of items

\n" yield "
    \n" for num in range(10): yield "
  • Item %s
  • \n" % (num,) yield "
\n" yield footer index.exposed = True cpg.root = Site() cpg.server.start() ----------------------------------- That starts a webserver listening on port 8080 serving up your "index" method at: http://yourhost:8080/ or http://yourhost:8080/index Anyhow, CherryPy is very easy to get a hold of. Good luck with your web application. Christian http://www.dowski.com From denise.hartley at gmail.com Thu Jun 23 19:57:27 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 23 Jun 2005 10:57:27 -0700 Subject: [Tutor] Cookies and authorization Message-ID: <8daabe56050623105718c7145c@mail.gmail.com> Hello, everyone! I am trying to go to a website, collect any and all cookies I receive by going to that website, and then look at the cookies/print them. So I did the following, from the cookie examples in the documentation: import cookielib, urllib2 myjar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar)) x = opener.open("http://www.amazon.com") (I just did amazon because I knew it would leave cookies, as a sample). I'm not entirely sure how this works yet, because I'm just learning about cookies now, but I am going to play with it and see what I can find out. My question for you is this: The website I have to access and get the cookies from is, of course, not amazon, it is: http://www.pythonchallenge.com/pc/return/__________.html ..where ____________ is an actual word, but I'm not typing it so I don't give away any spoilers to people who are working on the challenges. My problem is, when I plug this url into my sample code above, I get an error ("HTTP Error 401: Authorization Required"), because normally when you go to this url it makes you enter in a username and a password. Does anyone know how to get around this, either with code commands I can change to embed the password/username, or a way I can reformat the URL to *include* the password/username? I remember seeing something like this but I can't get it formatted right. Say my username is "guido" and my password is "python." Any help would be much appreciated! Thanks :) ~Denise (Also, there is lots of documentation on the cookie modules, and, to my own great amusement, even examples(!!), but if anyone has a simple howto for cookie processing, that would also be a great resource!) From jsmith at medplus.com Thu Jun 23 20:00:47 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 23 Jun 2005 14:00:47 -0400 Subject: [Tutor] Interesting problem Message-ID: Consider a class with a lt of properties. I would like a member function which generates a dictionary where the keys are the property names and the values are the property values? Is this clear? How might I go about this? Jeff From Christian.Wyglendowski at greenville.edu Thu Jun 23 20:17:28 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 23 Jun 2005 13:17:28 -0500 Subject: [Tutor] Cookies and authorization Message-ID: > -----Original Message----- > > Hello, everyone! Hi, > My problem is, when I plug this url into my sample code above, I get > an error ("HTTP Error 401: Authorization Required"), because normally > when you go to this url it makes you enter in a username and a > password. Does anyone know how to get around this, either with code > commands I can change to embed the password/username, or a way I can > reformat the URL to *include* the password/username? I remember > seeing something like this but I can't get it formatted right. Say my > username is "guido" and my password is "python." Try subclassing urllib.FancyURLopener and overriding the prompt_user_passwd() method. That should get you what you need :-) > Any help would be much appreciated! Thanks :) > > ~Denise HTH, Christian http://www.dowski.com From kent37 at tds.net Thu Jun 23 20:18:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 14:18:51 -0400 Subject: [Tutor] Cookies and authorization In-Reply-To: <8daabe56050623105718c7145c@mail.gmail.com> References: <8daabe56050623105718c7145c@mail.gmail.com> Message-ID: <42BAFD0B.4040305@tds.net> D. Hartley wrote: > My problem is, when I plug this url into my sample code above, I get > an error ("HTTP Error 401: Authorization Required"), because normally > when you go to this url it makes you enter in a username and a > password. > > (Also, there is lots of documentation on the cookie modules, and, to > my own great amusement, even examples(!!), but if anyone has a simple > howto for cookie processing, that would also be a great resource!) See http://www.voidspace.org.uk/python/articles.shtml#http for articles about authorization and cookies. Make sure you read the auth article to the end, it does it the hard way first to show what is going on... Kent From zanesdad at bellsouth.net Thu Jun 23 20:21:58 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 23 Jun 2005 14:21:58 -0400 Subject: [Tutor] Interesting problem In-Reply-To: References: Message-ID: <42BAFDC6.7060305@bellsouth.net> Smith, Jeff wrote: >Consider a class with a lt of properties. I would like a member >function which generates a dictionary where the keys are the property >names and the values are the property values? > >Is this clear? > >How might I go about this? > >Jeff >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Like .__dict__? Given this class: 1 class Foo: 2 def __init__(self, **kw): 3 self.__dict__.update(kw) 4 And creating an instance of it like this: In [17]: foo = Foo(**{"bar":"b", "foo":"f", "bam":"bm"}) And accessing the properties of it like this: In [18]: foo.foo Out[18]: 'f' In [19]: foo.bar Out[19]: 'b' In [20]: foo.bam Out[20]: 'bm' You can get all properties of it like this: In [21]: foo.__dict__ Out[21]: {'bam': 'bm', 'bar': 'b', 'foo': 'f'} Is this what you're looking for? JJ From Christian.Wyglendowski at greenville.edu Thu Jun 23 20:24:30 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 23 Jun 2005 13:24:30 -0500 Subject: [Tutor] Interesting problem Message-ID: > -----Original Message----- > > Consider a class with a lt of properties. I would like a member > function which generates a dictionary where the keys are the property > names and the values are the property values? > > Is this clear? I think so :-) > How might I go about this? I think you could simply use the special object attribute __dict__. It holds a dictionary of all properties and their values. >>> class Something: ... def __init__(self, item1, item2, item3, item4, item5): ... self.item1 = item1 ... self.item2 = item2 ... self.item3 = item3 ... self.item4 = item4 ... self.item5 = item5 ... >>> s = Something(42,52,55,1,54) >>> s.__dict__ {'item2': 52, 'item3': 55, 'item1': 42, 'item4': 1, 'item5': 54} > Jeff HTH, Christian http://www.dowski.com From kent37 at tds.net Thu Jun 23 20:29:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 14:29:13 -0400 Subject: [Tutor] Interesting problem In-Reply-To: References: Message-ID: <42BAFF79.4020907@tds.net> Smith, Jeff wrote: > Consider a class with a lt of properties. I would like a member > function which generates a dictionary where the keys are the property > names and the values are the property values? > > Is this clear? No, actually :-) Do you want the properties of the class (which are typically the methods of the class) or properties of an instance of the class (which is typically instance variables). I'm guessing you want to see the instance values. These are already available in a dictionary, the __dict__ attribute of the instance: >>> class T: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def show(self): ... print 'x =', self.x, 'y =', self.y ... dir(T) shows all the attributes of T, including inherited attributes: >>> dir(T) ['__doc__', '__init__', '__module__', 'show'] >>> t=T(1, 2) dir works for instances too. Notice it shows all accessible attributes which includes attributes of the class: >>> dir(t) ['__doc__', '__init__', '__module__', 'show', 'x', 'y'] But I think __dict__ is what you want: >>> t.__dict__ {'y': 2, 'x': 1} Kent From jsmith at medplus.com Thu Jun 23 20:43:43 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 23 Jun 2005 14:43:43 -0400 Subject: [Tutor] Interesting problem Message-ID: I can see I wasn't clear :-) Here's the basic framework of what I'm looking for. Needless to say, this is just an example and not the real problem which is quite complicated and includes multiple classes. What I'm looking for is the actual implementation of get_props_as_dict which I've written here as pseudo-code class MyClass: def __init__(self): self._var1 = val1 self._var2 = val2 var1 = property(lambda s: s._var1) var2 = property(lambda s: s._var2) def _var3(self): return self._var1 + self._var2 var3 = property(_var3) def getprops_as_dict(self): d = dict() for prop in properties: d[prop_name] = prop_value return d Thanks, Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Smith, Jeff Sent: Thursday, June 23, 2005 2:01 PM To: tutor at python.org Subject: [Tutor] Interesting problem Consider a class with a lt of properties. I would like a member function which generates a dictionary where the keys are the property names and the values are the property values? Is this clear? How might I go about this? Jeff _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Thu Jun 23 21:16:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 15:16:48 -0400 Subject: [Tutor] Interesting problem In-Reply-To: References: Message-ID: <42BB0AA0.6000704@tds.net> Smith, Jeff wrote: > I can see I wasn't clear :-) > > Here's the basic framework of what I'm looking for. Needless to say, > this is just an example and not the real problem which is quite > complicated and includes multiple classes. > > What I'm looking for is the actual implementation of get_props_as_dict > which I've written here as pseudo-code > > class MyClass: > def __init__(self): > self._var1 = val1 > self._var2 = val2 > > var1 = property(lambda s: s._var1) > var2 = property(lambda s: s._var2) > > def _var3(self): > return self._var1 + self._var2 > > var3 = property(_var3) > > def getprops_as_dict(self): > d = dict() > for prop in properties: > d[prop_name] = prop_value > return d Still not that clear. What do you want to see when you call MyClass().getprops_as_dict() ? Maybe this will give you some ideas: >>> class MyClass: ... def __init__(self, val1, val2): ... self._var1 = val1 ... self._var2 = val2 ... var1 = property(lambda s: s._var1) ... var2 = property(lambda s: s._var2) ... def _var3(self): ... return self._var1 + self._var2 ... var3 = property(_var3) ... def getprops_as_dict(self): ... d = dict(self.__dict__) ... return d ... >>> m=MyClass(1,2) Using just m.__dict__: >>> m.getprops_as_dict() {'_var2': 2, '_var1': 1} The inspect module might be some help: >>> import inspect >>> for k, v in inspect.getmembers(m): ... print k, '=', v ... __doc__ = None __init__ = > __module__ = __main__ _var1 = 1 _var2 = 2 _var3 = > getprops_as_dict = > var1 = 1 var2 = 2 var3 = 3 This inspects the class for actual properties and shows their values. It won't print simple attributes (in m.__dict__) or attributes defined by user-defined descriptors though: >>> for p in dir(m.__class__): ... pp = getattr(m.__class__, p) ... if isinstance(pp, property): ... print p, '=', getattr(m, p) ... var1 = 1 var2 = 2 var3 = 3 Kent From jsmith at medplus.com Thu Jun 23 21:24:59 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 23 Jun 2005 15:24:59 -0400 Subject: [Tutor] Interesting problem Message-ID: Here would be the usage: myinst = MyClass() print myinst.getprops_as_dict() would print {'var1': 1, 'var2': 2, 'var3': 3} Needless to say I want the instance values which might be different for each instance. I know that I could code it brute force, but I want to be able to add properties without having to remember to update getprops_as_dict(). For those who are interested, the dictionary created by getprops_as_dict() will be fed to string.Template.substitute Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, June 23, 2005 3:17 PM To: Python Tutor Subject: Re: [Tutor] Interesting problem Still not that clear. What do you want to see when you call MyClass().getprops_as_dict() ? Maybe this will give you some ideas: >>> class MyClass: ... def __init__(self, val1, val2): ... self._var1 = val1 ... self._var2 = val2 ... var1 = property(lambda s: s._var1) ... var2 = property(lambda s: s._var2) ... def _var3(self): ... return self._var1 + self._var2 ... var3 = property(_var3) ... def getprops_as_dict(self): ... d = dict(self.__dict__) ... return d ... >>> m=MyClass(1,2) Using just m.__dict__: >>> m.getprops_as_dict() {'_var2': 2, '_var1': 1} The inspect module might be some help: >>> import inspect >>> for k, v in inspect.getmembers(m): ... print k, '=', v ... __doc__ = None __init__ = > __module__ = __main__ _var1 = 1 _var2 = 2 _var3 = > getprops_as_dict = > var1 = 1 var2 = 2 var3 = 3 This inspects the class for actual properties and shows their values. It won't print simple attributes (in m.__dict__) or attributes defined by user-defined descriptors though: >>> for p in dir(m.__class__): ... pp = getattr(m.__class__, p) ... if isinstance(pp, property): ... print p, '=', getattr(m, p) ... var1 = 1 var2 = 2 var3 = 3 Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From Christian.Wyglendowski at greenville.edu Thu Jun 23 21:56:04 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 23 Jun 2005 14:56:04 -0500 Subject: [Tutor] Cookies and authorization Message-ID: > -----Original Message----- > > Christian, > > > Try subclassing urllib.FancyURLopener and overriding the > > prompt_user_passwd() method. That should get you what you need :-) > > Well, I used urllib.FancyURLopener, and can open and look at > the url, like this: > > import urllib > opener2 = urllib.FancyURLopener({}) > f = > opener2.open("http://www.pythonchallenge.com/pc/return/romance.html") > f.read() > > ..but to get at the cookies, I need to use urllib2.build_opener Ah ha ... I should have been paying more attention :-) > instead of urllib.FancyURLopener so that I can have access to > urllib2.HTTPCookieProcessor, which does not seem to be an option in > the regular urllib module? Sorry if this seems like a dense question, > I have little-to-no experience with cookies (and very little with > urllib itself), so the examples sometimes leave me hanging! It looks like the link that Kent suggested uses urllib2 and gives some good examples of how to do authentication. > I'd appreciate any clarification you could give, or if you meant > something else by your message? I don't have much programming experience with cookies, so I don't have much more to offer. Good luck! Christian http://www.dowski.com From kent37 at tds.net Thu Jun 23 22:38:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 16:38:39 -0400 Subject: [Tutor] Interesting problem In-Reply-To: References: Message-ID: <42BB1DCF.4030303@tds.net> Smith, Jeff wrote: > Here would be the usage: > > myinst = MyClass() > print myinst.getprops_as_dict() > > would print > > {'var1': 1, 'var2': 2, 'var3': 3} > > Needless to say I want the instance values which might be different for > each instance. I know that I could code it brute force, but I want to > be able to add properties without having to remember to update > getprops_as_dict(). OK, so will a variation on my last recipe work? This looks for property attributes of the class and gets the corresponding property on the instance: def getprops_as_dict(self): return dict(pname, getattr(self, pname) for pname in dir(self.__class__) if isinstance(getattr(self.__class__, pname), property)) ) Kent > > For those who are interested, the dictionary created by > getprops_as_dict() will be fed to string.Template.substitute > > Jeff From alan.gauld at freenet.co.uk Thu Jun 23 22:49:02 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 23 Jun 2005 21:49:02 +0100 Subject: [Tutor] Interesting problem References: Message-ID: <001c01c57834$fd84ab90$5ea68651@xp> > Consider a class with a lt of properties. I would like a member > function which generates a dictionary where the keys are the property > names and the values are the property values? Use the force... :-) Since Python uses dictionaries to store all those things already there must be a suitable bit of black magic that will serve it up on a plate. Doing some reading around the innards of classes should shed light on it. Alan G. From jsmith at medplus.com Thu Jun 23 22:55:48 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 23 Jun 2005 16:55:48 -0400 Subject: [Tutor] Interesting problem Message-ID: That's what I was looking for. Although I couldn't get the below to work, I went with a different mod of the original you gave: def get_props_as_dict(self): d = dict() for entry in dir(self.__class__): if isinstance(getattr(self.__class__, entry), property): d[entry] = getattr(self, entry) return d Thanks! Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, June 23, 2005 4:39 PM To: Python Tutor Subject: Re: [Tutor] Interesting problem Smith, Jeff wrote: > Here would be the usage: > > myinst = MyClass() > print myinst.getprops_as_dict() > > would print > > {'var1': 1, 'var2': 2, 'var3': 3} > > Needless to say I want the instance values which might be different > for each instance. I know that I could code it brute force, but I > want to be able to add properties without having to remember to update > getprops_as_dict(). OK, so will a variation on my last recipe work? This looks for property attributes of the class and gets the corresponding property on the instance: def getprops_as_dict(self): return dict(pname, getattr(self, pname) for pname in dir(self.__class__) if isinstance(getattr(self.__class__, pname), property)) ) Kent > > For those who are interested, the dictionary created by > getprops_as_dict() will be fed to string.Template.substitute > > Jeff _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From denise.hartley at gmail.com Thu Jun 23 22:59:07 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 23 Jun 2005 13:59:07 -0700 Subject: [Tutor] Cookies and authorization - urllib2 vs urllib In-Reply-To: <8daabe56050623113429254260@mail.gmail.com> References: <8daabe56050623113429254260@mail.gmail.com> Message-ID: <8daabe5605062313593280ef4c@mail.gmail.com> >From Christian: > Try subclassing urllib.FancyURLopener and overriding the > prompt_user_passwd() method. That should get you what you need :-) Well, I used urllib.FancyURLopener, and can open and look at the url, like this: import urllib opener2 = urllib.FancyURLopener({}) f = opener2.open("http://www.pythonchallenge.com/pc/return/romance.html") f.read() ..but to get at the cookies, I need to use urllib2.build_opener instead of urllib.FancyURLopener so that I can have access to urllib2.HTTPCookieProcessor, which does not seem to be an option in the regular urllib module? Sorry if this seems like a dense question, I have little-to-no experience with cookies (and very little with urllib itself), so the examples sometimes leave me hanging! Does anyone know a way to use an opener (like that above from urllib2) that can process cookies AND can pass in a user/pass (like FancyURLopener from urllib)? I'm not having much luck trying to do both things at once! Thanks, Denise P.S. Kent - thank you for the helpful tutorials on authentication, they really cleared up the process a great deal. The only problem is: When I create an opener to process the cookies, it looks like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar)) ..where myjar is cookielib.CookieJar() But in the examples for authentication, when I create the opener: opener = urllib2.build_opener(authhandler) ..where authhandler is urllib2.HTTPBasicAuthHandler(passwordmanager) So both use build_opener, but the thing I pass in, from what I am looking at so far, has to be a cookie processor OR an authenticator. How can I do both at once? From reed at focusdatasolutions.com Thu Jun 23 23:20:44 2005 From: reed at focusdatasolutions.com (Reed L. O'Brien) Date: Thu, 23 Jun 2005 17:20:44 -0400 Subject: [Tutor] strip an email In-Reply-To: <42BA6296.9080803@xit.net> References: <42BA6296.9080803@xit.net> Message-ID: nephish wrote: > Does anyone know how to strip everything off of an email? > i have a little app that i am working on to read an email message and > write the > body of a message to a log file. > each email this address gets is only about three to five lines long. > but i cannot seem to get just the body filtered through. > i get all the headers, the path, what spam-wall it went through, etc... > > any suggestions would be greatly appreciated . > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > THis is from the email module. If I remember correctly text is the first part of the payload in a multipart that has text. So if you know it comes in that way you can grab it with the optional i=0. If it isn't and you know it's coming in as a string just get the string and write it to the log. Then again someone else may have a better answer... get_payload( [i[, decode]]) Return a reference the current payload, which will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False. If the payload is a list and you mutate the list object, you modify the message's payload in place. With optional argument i, get_payload() will return the i-th element of the payload, counting from zero, if is_multipart() is True. An IndexError will be raised if i is less than 0 or greater than or equal to the number of items in the payload. If the payload is a string (i.e. is_multipart() is False) and i is given, a TypeError is raised. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding: header. When True and the message is not a multipart, the payload will be decoded if this header's value is "quoted-printable" or "base64". If some other encoding is used, or Content-Transfer-Encoding: header is missing, or if the payload has bogus base64 data, the payload is returned as-is (undecoded). If the message is a multipart and the decode flag is True, then None is returned. The default for decode is False. From phillip.hart at gmail.com Fri Jun 24 00:15:59 2005 From: phillip.hart at gmail.com (Phillip Hart) Date: Thu, 23 Jun 2005 17:15:59 -0500 Subject: [Tutor] Lists in List question Message-ID: <560fda420506231515974437e@mail.gmail.com> Hello, I've been using lists within lists for several functions, but have been unable, in loop form, to extract data from them or, in loop for, apply data to them. Basically, when extracting data, it only runs 1 loop. Likewise, when initially assigning the data, it only runs 1 loop. In the following example, the loop works once for x, and then a full loop (8 times) for y: ### rr1=[0,0,0,0,0,0,0,0] rr2=[0,0,0,0,0,0,0,0] rr3=[0,0,0,0,0,0,0,0] rr4=[0,0,0,0,0,0,0,0] rr5=[0,0,0,0,0,0,0,0] rr6=[0,0,0,0,0,0,0,0] rr7=[0,0,0,0,0,0,0,0] rr8=[0,0,0,0,0,0,0,0] results=[rr1,rr2,rr3,rr4,rr5,rr6,rr7,rr8] x=0 y=0 while x<8: while y<8: value=x+y results[x][y]=value y=y+1 x=x+1 x=0 y=0 while x<8: while y<8: print "(",x,", ",y,") is ",results[x][y] ###results[] is a list of lists y=y+1 x=x+1 ### The output is simply: ( 0 , 0 ) is 0 ( 0 , 1 ) is 1 ( 0 , 2 ) is 2 ( 0 , 3 ) is 3 ( 0 , 4 ) is 4 ( 0 , 5 ) is 5 ( 0 , 6 ) is 6 ( 0 , 7 ) is 7 Thanks for the help. I'm sure this is another newbie mistake, but one I'd be greateful to see past. -Phil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050623/35de4518/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Jun 24 01:00:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Jun 2005 16:00:51 -0700 (PDT) Subject: [Tutor] Lists in List question In-Reply-To: <560fda420506231515974437e@mail.gmail.com> Message-ID: On Thu, 23 Jun 2005, Phillip Hart wrote: > I've been using lists within lists for several functions, but have been > unable, in loop form, to extract data from them or, in loop for, apply data > to them. [cut] Hi Phillip, Can you try checking for indentation? Your code came out indented all on the left margin, so it's difficult to see if: > while x<8: > while y<8: > print "(",x,", ",y,") is ",results[x][y] ###results[] is a list of lists > y=y+1 > x=x+1 represents the code block: ###### while x<8: while y<8: print "(",x,", ",y,") is ",results[x][y] y=y+1 x=x+1 ###### or if it represents the code block: ###### while x<8: while y<8: print "(",x,", ",y,") is ",results[x][y] y=y+1 x=x+1 ###### I'll assume for the moment that the second interpretation is what you have, since the first one makes less sense. *grin* Also, you may want to see if you really want to use the "while" loop, or if a "for" loop is more convenient. The code as written is handling loop indicies manually, and there may be a bug in the way you're using it. Let's take the second code block for the moment: ###### while x<8: while y<8: print "(",x,", ",y,") is ",results[x][y] y=y+1 x=x+1 ###### The 'y' variable does not automatically reset here back to zero at any given point, so the loop will only run through the first row of the results. Try and see if expressing the iteration with a 'for' loop is easier. Because it has an explicit range(), 'for' often makes it easier to write the code without having to deal with incrementing index variables by hand. Best of wishes to you! From kent37 at tds.net Fri Jun 24 04:00:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 22:00:40 -0400 Subject: [Tutor] Interesting problem In-Reply-To: References: Message-ID: <42BB6948.9020802@tds.net> Smith, Jeff wrote: > That's what I was looking for. Although I couldn't get the below to > work, I went with a different mod of the original you gave: > > def get_props_as_dict(self): > d = dict() > for entry in dir(self.__class__): > if isinstance(getattr(self.__class__, entry), property): > d[entry] = getattr(self, entry) > return d > OK good! My code was untested and requires Python 2.4. I'm glad you could turn it into something that works for you. Kent > Thanks! > Jeff > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Kent Johnson > OK, so will a variation on my last recipe work? This looks for property > attributes of the class and gets the corresponding property on the > instance: > def getprops_as_dict(self): > return dict(pname, getattr(self, pname) > for pname in dir(self.__class__) > if isinstance(getattr(self.__class__, pname), property)) > ) > > Kent From kent37 at tds.net Fri Jun 24 04:06:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jun 2005 22:06:29 -0400 Subject: [Tutor] Cookies and authorization - urllib2 vs urllib In-Reply-To: <8daabe5605062313593280ef4c@mail.gmail.com> References: <8daabe56050623113429254260@mail.gmail.com> <8daabe5605062313593280ef4c@mail.gmail.com> Message-ID: <42BB6AA5.7030708@tds.net> D. Hartley wrote: > P.S. Kent - thank you for the helpful tutorials on authentication, > they really cleared up the process a great deal. The only problem is: > > When I create an opener to process the cookies, it looks like this: > > opener = > urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar)) > > ..where myjar is cookielib.CookieJar() > > But in the examples for authentication, when I create the opener: > > opener = urllib2.build_opener(authhandler) > > ..where authhandler is urllib2.HTTPBasicAuthHandler(passwordmanager) > > So both use build_opener, but the thing I pass in, from what I am > looking at so far, has to be a cookie processor OR an authenticator. > How can I do both at once? I think build_opener() can take multiple arguments: cookieHandler = urllib2.HTTPCookieProcessor(myjar) authhandler = urllib2.HTTPBasicAuthHandler(passwordmanager) opener = urllib2.build_opener(cookieHandler, authhandler) Kent From webdev at matheteuo.org Fri Jun 24 07:43:53 2005 From: webdev at matheteuo.org (Don Parris) Date: Fri, 24 Jun 2005 01:43:53 -0400 Subject: [Tutor] MySQL Connection Function (Solution) In-Reply-To: <1119467182.14248.31.camel@www.venix.com> References: <1119395623.24763.119.camel@www.venix.com> <20050622142048.1a27acef@luke.matheteuo.rel> <1119467182.14248.31.camel@www.venix.com> Message-ID: <20050624014353.5f95ccf7@luke.matheteuo.rel> On Wed, 22 Jun 2005 15:06:22 -0400 Python wrote: > On Wed, 2005-06-22 at 14:20 -0400, Don Parris wrote: > > On Tue, 21 Jun 2005 19:13:43 -0400 > > Python wrote: > > > > Here's my solution, using the code Lloyd provided in a previous post: The script that contains the MySQL functions that the end-user will use most imports the file containing the connection code: def connect( parm_name): parms = db_parms[parm_name] return SQLdb.connect( **parms) The file containing the core db functions uses do_Query to handle the cursor and results, and return the results back to the functions, which then continue their job of outputting the results. def do_Query(sqlCmd): curs = conn.cursor() curs.execute(sqlCmd) results = curs.fetchall() curs.close() return results def mbr_Roster(): # Make SQL string and execute it. sqlCmd = "SELECT env_num, lst_name, fst_name FROM person\ where env_num is not null\ order by lst_name" Results = do_Query(sqlCmd) The above line calling do_Query can be pasted into each function, and provides exactly what I need (so far). # iterate through resultset. print 'The Church Membership Roster' for record in Results: print '%s ..... %s, %s' % record # print record mbrRoster = open('mbrRoster.txt', 'w') cPickle.dump(Results, mbrRoster) mbrRoster.close() raw_input('Press ENTER to return to the menu.') Due to the way the menu system is designed, raw_input allows me to hold the output on the console screen until the user has verified the data that gets written to the file. Otherwise, the function returns control of the program back over to the menu system, and the user is left looking at the menu after seeing the output from the query flash on the screen for a second. This may still be somewhat klunky, but it does what I need. At the moment, I'll leave well enough alone, but I would appreciate any feedback. Meanwhile, I appreciate the help and solutions offered. Meanwhile, I do need to go over some good examples of returning values, and passing variables around. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From ewald.ertl at hartter.com Fri Jun 24 09:28:48 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri, 24 Jun 2005 09:28:48 +0200 Subject: [Tutor] Lists in List question In-Reply-To: <560fda420506231515974437e@mail.gmail.com> References: <560fda420506231515974437e@mail.gmail.com> Message-ID: <20050624092848.00000c87@sunray1> Hello Phil! the HTML-Formating look's better than the text-Version. on Thu, 23 Jun 2005 17:15:59 -0500 Phillip Hart wrote : --------------------------------------------------------------------------------------------- Phillip Hart > Hello, Phillip Hart > I've been using lists within lists for several functions, but have been Phillip Hart > unable, in loop form, to extract data from them or, in loop for, apply data Phillip Hart > to them. Phillip Hart > Phillip Hart > Basically, when extracting data, it only runs 1 loop. Likewise, when Phillip Hart > initially assigning the data, it only runs 1 loop. Phillip Hart > Phillip Hart > In the following example, the loop works once for x, and then a full loop (8 Phillip Hart > times) for y: Phillip Hart > Phillip Hart > ### Phillip Hart > rr1=[0,0,0,0,0,0,0,0] Phillip Hart > rr2=[0,0,0,0,0,0,0,0] Phillip Hart > rr3=[0,0,0,0,0,0,0,0] Phillip Hart > rr4=[0,0,0,0,0,0,0,0] Phillip Hart > rr5=[0,0,0,0,0,0,0,0] Phillip Hart > rr6=[0,0,0,0,0,0,0,0] Phillip Hart > rr7=[0,0,0,0,0,0,0,0] Phillip Hart > rr8=[0,0,0,0,0,0,0,0] Phillip Hart > results=[rr1,rr2,rr3,rr4,rr5,rr6,rr7,rr8] Phillip Hart > Phillip Hart > Phillip Hart > x=0 Phillip Hart > y=0 Phillip Hart > while x<8: Phillip Hart > while y<8: Phillip Hart > value=x+y Phillip Hart > results[x][y]=value Phillip Hart > y=y+1 Phillip Hart > x=x+1 Phillip Hart > In the nested while-Loop's there is no reset of y during each run for an incremented x so after the first turn the second while will never be run, because y is allways set to 8. ------------------- end ---------------------- HTH Ewald From kent37 at tds.net Fri Jun 24 12:08:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 06:08:11 -0400 Subject: [Tutor] Changing what you've already printed In-Reply-To: <34bb7f5b05062205249d1500d@mail.gmail.com> References: <34bb7f5b05062205249d1500d@mail.gmail.com> Message-ID: <42BBDB8B.9060905@tds.net> Ed Singleton wrote: > Is it possible (and easy) to change something you've already printed > rather than print again? > > Any clues or pointers to documentation gratefully recieved. You might like textui. It creates a console window in Tkinter so it is portable and it supports gotoxy(). http://py.vaults.ca/apyllo.py/808292924.247038364.15871892 Kent From RPhillips at engineer.co.summit.oh.us Fri Jun 24 14:26:41 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 24 Jun 2005 08:26:41 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? Message-ID: Thanks for your response, Shuying Wang -- I was afraid no one even read the post. Now I see I wasn't clear. ---------------------------------------------------------------------------------- Shuying Wang: I'm not sure what you're trying to do. But I run cgi scripts and make xmlrpc requests with xmlrpclib with a connection with xmlrpclib.Server(server_uri), though I'm only doing this client side. I'm not running the server as cgi. ----------------------------------------------------------------------------------- I have a Python module that I am trying to expose via XMLRPC. I can get it running by assigning a port on the server using SimpleXMLRPCRequestHandler, but I would prefer to expose it through CGI if possible. This seems to be the stated purpose of the CGIXMLRPCRequestHandler, but I believe it is broken in some very serious way. The example code in the python online documentation calls a non-existant "div" function, so it was obviously a typing exercise, not actual code that anyone ever tested. In researching the module, I found several requests on various mailing lists for example code -- not a single one ever had a response. When I've seen this before, it has turned out that either: a) it is terribly difficult, or b)it is stupidly simple. Since this is a tutor list, and I have seen the members graciously answer some questions that seemed pretty simple, I thought I'd post it here. Since the only response (yours -- thanks again for responding!) was about xmlrpclib on the client side, not CGIXMLRPCRequestHandler on the server side, I can now conclude that it is terribly difficult, and slink off to publish using SOAP. Ron On 6/23/05, Ron Phillips wrote: > > I believe I've tried every setting known to man, in every script in every > little scrap of documentation available. XMLRPC requests using > SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI > script, and I get system lock ups and that's all. No error codes; no > response whatsoever. > > I am using Python 2.3, Windows XP. I have run other CGI scripts in the same > directory, so I know that works. > > Has anyone used this successfully? Can you share demo server and client > scripts -- just an echo function or something? > > Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/95b37fa3/attachment.htm From RPhillips at engineer.co.summit.oh.us Fri Jun 24 15:03:24 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 24 Jun 2005 09:03:24 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? Message-ID: ## Run a simple CGI server by opening a command line to the parent dir of cgi-bin and running python -c "import CGIHTTPServer; CGIHTTPServer.test()" ## Oh, dear -- I responded before I read your post, Kent. It turns out it was option b), after all. But I had NO idea I would need to do anything like the little clip above. Anything else I run under CGI, I just send an HTTP request and it works. I read, and read, and read, but never read anything about starting a CGIHTTPServer -- I'll look it up right away, but I can't see how I missed that. Maybe by Googling "XMLRPC", which was what I really wanted to do. Anyway, thank you -- if I can find them again, I'll respond to all those other posts with a link to yours in the archives. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/c1a0b597/attachment.htm From kent37 at tds.net Fri Jun 24 15:35:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 09:35:00 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <42BC0C04.9070807@tds.net> Ron Phillips wrote: > ## > Run a simple CGI server by opening a command line to the parent dir of > cgi-bin and running > python -c "import CGIHTTPServer; CGIHTTPServer.test()" > > ## > > Oh, dear -- I responded before I read your post, Kent. It turns out it > was option b), after all. But I had NO idea I would need to do anything > like the little clip above. Anything else I run under CGI, I just send > an HTTP request and it works. I read, and read, and read, but never read > anything about starting a CGIHTTPServer -- I'll look it up right away, > but I can't see how I missed that. Maybe by Googling "XMLRPC", which was > what I really wanted to do. CGI requires a running HTTP server in front of it. The server receives the HTTP request, sees that it is a CGI request, starts a new process with the environment set according to the CGI protocol, and runs the CGI handler. Do you understand this relationship? (I mean that kindly, your response makes me suspect there is a fair amount of black magic in this for you.) The snippet above just starts a simple CGI-capable HTTP server. It is useful for testing, not an essential part of the recipe. If you have other CGIs working you must have a working HTTP server already, such as Apache or IIS. In your initial post you said "I have run other CGI scripts in the same directory." Were those CGIs written in Python? How did you run them? Kent From joe at omc-international.com.au Fri Jun 24 15:26:21 2005 From: joe at omc-international.com.au (joe@omc-international.com.au) Date: Fri, 24 Jun 2005 23:26:21 +1000 (EST) Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <60391.203.166.236.141.1119619581.squirrel@203.166.236.141> Hi, I managed to make it work with the following code: #! /usr/bin/python from SimpleXMLRPCServer import CGIXMLRPCRequestHandler def plus(a,b): return a + b server = CGIXMLRPCRequestHandler() server.register_function(plus) server.handle_request() Setting this to run from a cgi directory then using the following worked: >>> import xmlrpclib >>> s = xmlrpclib.ServerProxy("http://127.0.0.1/~joe/xmlrpctest.cgi") >>> s.plus(4,5) 9 Hope this helps Joe > Thanks for your response, Shuying Wang -- I was afraid no one even read > the post. Now I see I wasn't clear. > ---------------------------------------------------------------------------------- > Shuying Wang: I'm not sure what you're trying to do. But I run cgi > scripts and make > xmlrpc requests with xmlrpclib with a connection with > xmlrpclib.Server(server_uri), though I'm only doing this client side. > I'm not running the server as cgi. > ----------------------------------------------------------------------------------- > I have a Python module that I am trying to expose via XMLRPC. I can get > it running by assigning a port on the server using > SimpleXMLRPCRequestHandler, but I would prefer to expose it through CGI > if possible. This seems to be the stated purpose of the > CGIXMLRPCRequestHandler, but I believe it is broken in some very serious > way. > > The example code in the python online documentation calls a > non-existant "div" function, so it was obviously a typing exercise, not > actual code that anyone ever tested. > > In researching the module, I found several requests on various mailing > lists for example code -- not a single one ever had a response. When > I've seen this before, it has turned out that either: a) it is terribly > difficult, or b)it is stupidly simple. Since this is a tutor list, and I > have seen the members graciously answer some questions that seemed > pretty simple, I thought I'd post it here. > > Since the only response (yours -- thanks again for responding!) was > about xmlrpclib on the client side, not CGIXMLRPCRequestHandler on the > server side, I can now conclude that it is terribly difficult, and slink > off to publish using SOAP. > > Ron > > > On 6/23/05, Ron Phillips wrote: >> >> I believe I've tried every setting known to man, in every script in > every >> little scrap of documentation available. XMLRPC requests using >> SimpleXMLRPCRequestHandler -- no problem. But try to run them as a > CGI >> script, and I get system lock ups and that's all. No error codes; no >> response whatsoever. >> >> I am using Python 2.3, Windows XP. I have run other CGI scripts in > the same >> directory, so I know that works. >> >> Has anyone used this successfully? Can you share demo server and > client >> scripts -- just an echo function or something? >> >> Ron > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kabads at gmail.com Fri Jun 24 16:09:36 2005 From: kabads at gmail.com (Adam Cripps) Date: Fri, 24 Jun 2005 15:09:36 +0100 Subject: [Tutor] Help with Tkinter teachers' report program? Message-ID: I am a teacher and have written this little Python/Tkinter application to help me with my report writing: http://cvs.sourceforge.net/viewcvs.py/squawk/ It's released under GPL and was quite fun to write. However, currently the application only allows for 15 statements to be managed. Increasing it to 25 would be easy. But I'm not sure how I would manage the widget to present 100 or organise the statements according to subjects. Can anyone have a look at the code - perhaps run it and if possible suggest a way of implementing many more statements? Tabbed frames would be a good way forward (where each tab is a school subject) but under Tkinter they don't appear to be that easy. TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From arcege at gmail.com Fri Jun 24 16:31:46 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Fri, 24 Jun 2005 10:31:46 -0400 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: References: Message-ID: <7e5ba9220506240731feb1e1@mail.gmail.com> On 6/24/05, Adam Cripps wrote: > > I am a teacher and have written this little Python/Tkinter application > to help me with my report writing: > > http://cvs.sourceforge.net/viewcvs.py/squawk/ > > It's released under GPL and was quite fun to write. > > However, currently the application only allows for 15 statements to be > managed. Increasing it to 25 would be easy. But I'm not sure how I > would manage the widget to present 100 or organise the statements > according to subjects. > > Can anyone have a look at the code - perhaps run it and if possible > suggest a way of implementing many more statements? Tabbed frames > would be a good way forward (where each tab is a school subject) but > under Tkinter they don't appear to be that easy. > You can do tabbed frames in Tkinter. They take a little bit of coding, but to get right, but it is certainly something to think about. You might want to look into PMW (Python MegaWidgets) which is a Tkinter library. Myself, I had always prefered to write things in Tkinter, but a lot of people like the widget set in PMW. As for scaling the statements you have, you might want to think about putting the Label/Entry/Button widgets in a Frame with a Scrollbar widget. Then you can add as many as you like and the user can scroll down to the 200th statement. (I'm assuming that the user fills out each statement one by one, ugh!) Incidently, this Frame would be the same frame used for the tabbing, I would expect. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/9c326d57/attachment-0001.htm From kabads at gmail.com Fri Jun 24 16:40:19 2005 From: kabads at gmail.com (Adam Cripps) Date: Fri, 24 Jun 2005 15:40:19 +0100 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: <7e5ba9220506240731feb1e1@mail.gmail.com> References: <7e5ba9220506240731feb1e1@mail.gmail.com> Message-ID: On 6/24/05, Michael P. Reilly wrote: > On 6/24/05, Adam Cripps wrote: > > I am a teacher and have written this little Python/Tkinter application > > to help me with my report writing: > > > > http://cvs.sourceforge.net/viewcvs.py/squawk/ > > > > It's released under GPL and was quite fun to write. > > > > However, currently the application only allows for 15 statements to be > > managed. Increasing it to 25 would be easy. But I'm not sure how I > > would manage the widget to present 100 or organise the statements > > according to subjects. > > > > Can anyone have a look at the code - perhaps run it and if possible > > suggest a way of implementing many more statements? Tabbed frames > > would be a good way forward (where each tab is a school subject) but > > under Tkinter they don't appear to be that easy. > > > > You can do tabbed frames in Tkinter. They take a little bit of coding, but > to get right, but it is certainly something to think about. You might want > to look into PMW (Python MegaWidgets) which is a Tkinter library. Myself, I > had always prefered to write things in Tkinter, but a lot of people like the > widget set in PMW. > > As for scaling the statements you have, you might want to think about > putting the Label/Entry/Button widgets in a Frame with a Scrollbar widget. > Then you can add as many as you like and the user can scroll down to the > 200th statement. (I'm assuming that the user fills out each statement one > by one, ugh!) Incidently, this Frame would be the same frame used for the > tabbing, I would expect. > -Arcege I hadn't thought about a scrollbar - that would be very useful, although doesn't add to the management side of the statement (i.e. organising them according to subjects). The user can load a text file and adapt that - so they don't have to enter them by hand if they have them in a .txt file. Typing them in by hand once is better than typing them in by hand for every child that you have in your class, which is the whole aim of the software. Thanks Adam -- http://www.monkeez.org PGP key: 0x7111B833 From arcege at gmail.com Fri Jun 24 16:49:39 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Fri, 24 Jun 2005 10:49:39 -0400 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: References: <7e5ba9220506240731feb1e1@mail.gmail.com> Message-ID: <7e5ba922050624074912c80088@mail.gmail.com> On 6/24/05, Adam Cripps wrote: > > I hadn't thought about a scrollbar - that would be very useful, > although doesn't add to the management side of the statement (i.e. > organising them according to subjects). > > The user can load a text file and adapt that - so they don't have to > enter them by hand if they have them in a .txt file. Typing them in by > hand once is better than typing them in by hand for every child that > you have in your class, which is the whole aim of the software. > I could try to whip up an example a little later if you like. I probably wouldn't be large, but it could demonstrate tabbed frames with scrolling. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/5e6cbaaf/attachment.htm From RPhillips at engineer.co.summit.oh.us Fri Jun 24 17:39:20 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 24 Jun 2005 11:39:20 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? Message-ID: Kent wrote: CGI requires a running HTTP server in front of it. The server receives the HTTP request, sees that it is a CGI request, starts a new process with the environment set according to the CGI protocol, and runs the CGI handler. Do you understand this relationship? (I mean that kindly, your response makes me suspect there is a fair amount of black magic in this for you.) The snippet above just starts a simple CGI-capable HTTP server. It is useful for testing, not an essential part of the recipe. If you have other CGIs working you must have a working HTTP server already, such as Apache or IIS. In your initial post you said "I have run other CGI scripts in the same directory." Were those CGIs written in Python? How did you run them? Kent ------------------------------------- Well, I understand the words, and I can see that the HTTP server (IIS, in this case) hands off CGI stuff to a CGI handler -- but I think that IS a fair amount of black magic! So no, I really can't claim any deep understanding of the process. What I ran before were simple little test scripts of the "HelloWorld.py" variety. I would put them in the cgi-bin directory and invoke them with the browser, or with the HTTPLib in the command line, and I would get something back. When I invoke any script in the cgi-bin that has CGIXMLRPCRequestHandler in it through localhost or localhost:80, the program freezes right up. Nothing returned, nothing in the IIS error log, no reply at all. However, the little test scripts that you and Joe provided run just fine as long as I don't use IIS as the server. Maybe I should have posted "IIS and CGIXMLRPCRequestHandler doesn't work at all!!" Seriously, it looks like my IIS installation is at fault -- probably some setting I need to change. I wonder if that's the reason for all those unanswered posts -- it's not a Python problem, per se? Odd, though, that IIS is perfectly happy to run a Python script unless it has CGIXMLRPCRequestHandler in it. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/fd67844e/attachment.htm From reed at intersiege.com Fri Jun 24 17:47:23 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Fri, 24 Jun 2005 11:47:23 -0400 Subject: [Tutor] Search and Replace Message-ID: <42BC2B0B.3070305@intersiege.com> I ma trying to write a script to search adn replace a sizable chink of text in about 460 html pages. It is an old form that usesa search engine no linger availabe. I am wondering if anyone has any advice on the best way to go about that. There are more than one layout place ment for the form, but I would be happy to correct the last few by hand as more than 90% are the same. So my ideas have been, use regex to find
.*
and replace it with
newform
. Unfortunately there is more than just search form. So this would just clobber all of them. So I could
.*knownName of SearchButton.*
-->
newform
Or should I read each file in as a big string and break on the form tags, test the strings as necessary ad operate on them if the conditions are met. Unfortunaltely I think there are wide variances in white space and lines breaks. Even the order of the tags is inconsistent. So I think I am stuck with the first option... Unless there is some module or package I haven't found that works on html in just the way that I want. I found htmlXtract but it is for Python 1.5 and not immediately intuitive. Any help or advice on this is much appreciated. TIA ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 From kabads at gmail.com Fri Jun 24 18:08:37 2005 From: kabads at gmail.com (Adam Cripps) Date: Fri, 24 Jun 2005 17:08:37 +0100 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: <7e5ba922050624074912c80088@mail.gmail.com> References: <7e5ba9220506240731feb1e1@mail.gmail.com> <7e5ba922050624074912c80088@mail.gmail.com> Message-ID: On 6/24/05, Michael P. Reilly wrote: > On 6/24/05, Adam Cripps wrote: > > I hadn't thought about a scrollbar - that would be very useful, > > although doesn't add to the management side of the statement (i.e. > > organising them according to subjects). > > > > The user can load a text file and adapt that - so they don't have to > > enter them by hand if they have them in a .txt file. Typing them in by > > hand once is better than typing them in by hand for every child that > > you have in your class, which is the whole aim of the software. > > > > I could try to whip up an example a little later if you like. I probably > wouldn't be large, but it could demonstrate tabbed frames with scrolling. > > -Arcege > -- Michael, That would be much appreciated. Thanks Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Fri Jun 24 18:13:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 12:13:56 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <42BC3144.1010809@tds.net> Ron Phillips wrote: > What I ran before were simple little test scripts of the "HelloWorld.py" > variety. I would put them in the cgi-bin directory and invoke them with > the browser, or with the HTTPLib in the command line, and I would get > something back. OK, that is a good test. > > When I invoke any script in the cgi-bin that has CGIXMLRPCRequestHandler > in it through localhost or localhost:80, the program freezes right up. Which program freezes up? The client, IIS, or the CGI? > Nothing returned, nothing in the IIS error log, no reply at all. > However, the little test scripts that you and Joe provided run just fine > as long as I don't use IIS as the server. Maybe I should have posted > "IIS and CGIXMLRPCRequestHandler doesn't work at all!!" Seriously, it > looks like my IIS installation is at fault -- probably some setting I > need to change. Try putting this at the top of your Python CGI: import cgitb cgitb.enable(display=0, logdir='C:/temp') where logdir points to a writable directory. Then try accessing the cgi and see if anything is written to the log dir. Hopefully it will give a clue to what is going wrong. Kent From kent37 at tds.net Fri Jun 24 19:14:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 13:14:44 -0400 Subject: [Tutor] Search and Replace In-Reply-To: <42BC2B0B.3070305@intersiege.com> References: <42BC2B0B.3070305@intersiege.com> Message-ID: <42BC3F84.7050407@tds.net> Reed L. O'Brien wrote: > I ma trying to write a script to search adn replace a sizable chink of > text in about 460 html pages. > It is an old form that usesa search engine no linger availabe. > > I am wondering if anyone has any advice on the best way to go about that. > There are more than one layout place ment for the form, but I would be > happy to correct the last few by hand as more than 90% are the same. > > So my ideas have been, > use regex to find
.*
and replace it with
newform
. > Unfortunately there is more than just search form. So this would just > clobber all of them. So I could
.*knownName of > SearchButton.*
-->
newform
If you are sure 'knownName of SearchButton' only occurs in the form you want to replace, this seems like a good option. Only use non-greedy matching
.*?knownName of SearchButton.*?
Without the ? you will match from the start of the first form in the page, to the end of the last form, as long as the search form is one of them. > > Or should I read each file in as a big string and break on the form > tags, test the strings as necessary ad operate on them if the conditions > are met. Unfortunaltely I think there are wide variances in white > space and lines breaks. Even the order of the tags is inconsistent. So > I think I am stuck with the first option... > > Unless there is some module or package I haven't found that works on > html in just the way that I want. I found htmlXtract but it is for > Python 1.5 and not immediately intuitive. You might be able to find a module that will read the HTML into a structured form, work on that, and write it out again. Whether this is easy or practical depends a lot on how well-formed your HTML is, and how important it is to keep exactly the same form when you write it back out. You could take a look at ElementTidy for example. http://effbot.org/zone/element-tidylib.htm But I think the regex solution sounds good. Kent From dyoo at hkn.eecs.berkeley.edu Fri Jun 24 20:44:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Jun 2005 11:44:44 -0700 (PDT) Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: Message-ID: > The example code in the python online documentation calls a non-existant > "div" function, so it was obviously a typing exercise, not actual code > that anyone ever tested. Hi Ron, Ah, ok, I see. Check the bottom of: http://www.python.org/doc/lib/simple-xmlrpc-servers.html for a working example of that div function in the MyFuncs class. I believe that the example you were looking at earlier, near the bottom of: http://www.python.org/doc/lib/node556.html has is a documentation bug: the intent is clearly to compare and contrast SimpleXMLRPCServer and CGIXMLRPCRequestHandler, so the code should be using the same example. The fact that it isn't is confusing, and should be fixed. I'll send a bug report now. http://python.org/sf/1227181 Try Kent's example again; XMLRPC stuff is itself not too bad. Your two assumptions: 1. It's too easy to mention, and not worth talking about 2. It's too hard in practice, and not worth talking about are too black-and-white: XMLRPC itself is not bad at all, but CGI stuff can be maddeningly difficult at first, because it involves not only Python but also integration with an external web server. What I think you're running into is the CGI part, the part that doesn't debug as easily, just because error output doesn't automatically send to the browser --- that would be a security risk! --- but instead is shuttled off to your web server's error log file. So take a closer look at your web server's error logs; I wouldn't be surprised to see some Python error messages there that should help to isolate the issue. Best of wishes to you! From RPhillips at engineer.co.summit.oh.us Fri Jun 24 21:05:17 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 24 Jun 2005 15:05:17 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? Message-ID: Yes, I believe you are right -- I posted a reply to the list indicating that I suspect IIS is at fault; not Python. Or perhaps I should say "my installation of IIS"; I have no confidence whatsoever in my abilities to administer IIS properly. Thanks for looking at the documentation -- I was stuck using 2.3 because of some other modules I needed, so I didn't look at the 2.4 docs. That would have made me less angry, but the script still wouldn't have run, because the problem (evidently) is in IIS, not my code. I was really hard up against it -- no response at all from IIS, just a lockup, and apparently when IIS locked up, it did so prior to writing to the error log. When I tried using the CGIHTTPServer, everything I did over the past 3 days worked without a hitch. What a relief!! Now I just need to work around IIS -- and we don't use it outside the firewall, anyway. I think I'll put Apache on my local machine and use that. Thanks, again Ron >>> Danny Yoo 6/24/2005 2:44:44 PM >>> > The example code in the python online documentation calls a non-existant > "div" function, so it was obviously a typing exercise, not actual code > that anyone ever tested. Hi Ron, Ah, ok, I see. Check the bottom of: http://www.python.org/doc/lib/simple-xmlrpc-servers.html for a working example of that div function in the MyFuncs class. I believe that the example you were looking at earlier, near the bottom of: http://www.python.org/doc/lib/node556.html has is a documentation bug: the intent is clearly to compare and contrast SimpleXMLRPCServer and CGIXMLRPCRequestHandler, so the code should be using the same example. The fact that it isn't is confusing, and should be fixed. I'll send a bug report now. http://python.org/sf/1227181 Try Kent's example again; XMLRPC stuff is itself not too bad. Your two assumptions: 1. It's too easy to mention, and not worth talking about 2. It's too hard in practice, and not worth talking about are too black-and-white: XMLRPC itself is not bad at all, but CGI stuff can be maddeningly difficult at first, because it involves not only Python but also integration with an external web server. What I think you're running into is the CGI part, the part that doesn't debug as easily, just because error output doesn't automatically send to the browser --- that would be a security risk! --- but instead is shuttled off to your web server's error log file. So take a closer look at your web server's error logs; I wouldn't be surprised to see some Python error messages there that should help to isolate the issue. Best of wishes to you! ______________________________________________________________________ This email has been scanned by the MessageLabs Email Security System. For more information please visit http://www.messagelabs.com/email ______________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/17fca494/attachment.htm From kent37 at tds.net Fri Jun 24 21:24:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 15:24:37 -0400 Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: References: Message-ID: <42BC5DF5.3080308@tds.net> Danny Yoo wrote: > I believe that the example you were looking at earlier, near the bottom > of: > > http://www.python.org/doc/lib/node556.html > > has is a documentation bug: the intent is clearly to compare and contrast > SimpleXMLRPCServer and CGIXMLRPCRequestHandler, so the code should be > using the same example. The fact that it isn't is confusing, and should > be fixed. I'll send a bug report now. http://python.org/sf/1227181 I'm way ahead of you on that one :-) I filed a bug report that fixed the example on the SimpleXMLRPCServer page and recently reopened it for the CGIXMLRPCRequestHandler page. You might want to flag yours as a duplicate...see http://sourceforge.net/tracker/index.php?func=detail&aid=1041501&group_id=5470&atid=105470 Kent From alan.gauld at freenet.co.uk Fri Jun 24 21:39:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 24 Jun 2005 20:39:38 +0100 Subject: [Tutor] Help with Tkinter teachers' report program? References: Message-ID: <001101c578f4$75aa5e20$a89f8851@xp> > suggest a way of implementing many more statements? Tabbed frames > would be a good way forward (where each tab is a school subject) but > under Tkinter they don't appear to be that easy. Faking tabbed frames is fairly easy. Baasically its two frames one on top of the other, the top one is the tab set and the bottom the tab content selected. As you click a button simply unpack the current frame an pack the new one. Remember to change the highlighting of the selected tab by changing button appearance in some way. The principle is easy even if requiring a little bit of effort. We did this with an Oracle Forms application about 12 years ago when tabbed displays were very new and very sexy! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From hall at nhn.ou.edu Fri Jun 24 22:49:04 2005 From: hall at nhn.ou.edu (Ike) Date: Fri, 24 Jun 2005 15:49:04 -0500 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: References: Message-ID: <42BC71C0.8000603@nhn.ou.edu> for tabs, try the PMW library, notebook widget. its fairly easy to use I have found. Ike Adam Cripps wrote: >I am a teacher and have written this little Python/Tkinter application >to help me with my report writing: > >http://cvs.sourceforge.net/viewcvs.py/squawk/ > >It's released under GPL and was quite fun to write. > >However, currently the application only allows for 15 statements to be >managed. Increasing it to 25 would be easy. But I'm not sure how I >would manage the widget to present 100 or organise the statements >according to subjects. > >Can anyone have a look at the code - perhaps run it and if possible >suggest a way of implementing many more statements? Tabbed frames >would be a good way forward (where each tab is a school subject) but >under Tkinter they don't appear to be that easy. > >TIA >Adam > > From dyoo at hkn.eecs.berkeley.edu Fri Jun 24 22:58:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Jun 2005 13:58:42 -0700 (PDT) Subject: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it? In-Reply-To: <42BC5DF5.3080308@tds.net> Message-ID: > > has is a documentation bug: the intent is clearly to compare and contrast > > SimpleXMLRPCServer and CGIXMLRPCRequestHandler, so the code should be > > using the same example. The fact that it isn't is confusing, and should > > be fixed. I'll send a bug report now. http://python.org/sf/1227181 > > I'm way ahead of you on that one :-) I filed a bug report that fixed the > example on the SimpleXMLRPCServer page and recently reopened it for the > CGIXMLRPCRequestHandler page. You might want to flag yours as a > duplicate...see > http://sourceforge.net/tracker/index.php?func=detail&aid=1041501&group_id=5470&atid=105470 Hi Kent, Ah! Ok, thanks for the correction. That was silly of me. *grin* Ok, will do; I'm marking my report as a duplicate now. From hugonz-lists at h-lab.net Fri Jun 24 07:16:53 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 24 Jun 2005 00:16:53 -0500 Subject: [Tutor] strip an email In-Reply-To: <42BA6296.9080803@xit.net> References: <42BA6296.9080803@xit.net> Message-ID: <42BB9745.6060307@h-lab.net> Hi nephish, I clearly remember it is very very simple and it is defined in the RFC. As far as I remember, the end of the headers are signalled by an empty line. Try looking for '\n\n', this should do the trick. I've saved a couple of emails and it looks like this should work. something like: #full_text holds the full text of the message bodypos = full_text.find('\n\n') + 2 body = full_text[bodypos:] #body now holds the message body Please let us know if this works, hope it helps. Hugo nephish wrote: > Does anyone know how to strip everything off of an email? > i have a little app that i am working on to read an email message and > write the > body of a message to a log file. > each email this address gets is only about three to five lines long. > but i cannot seem to get just the body filtered through. > i get all the headers, the path, what spam-wall it went through, etc... > > any suggestions would be greatly appreciated . > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Fri Jun 24 08:12:10 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-15?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 24 Jun 2005 01:12:10 -0500 Subject: [Tutor] Popen4 and Paths Containing Spaces In-Reply-To: <92445514.20050615165544@freshsources.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D49E@riv-excha5.echostar.com> <42B07175.50105@h-lab.net> <92445514.20050615165544@freshsources.com> Message-ID: <42BBA43A.7090406@h-lab.net> Thanks, didn't know it before, as I have done very little Windows programming... only used the command line... > Windows doesn't care. The only place you can't use forward slashes in > path names is in a command prompt. It's been that way since DOS 2.0 in > the 80s. I prefer using the forward slashes in file name strings since > they're fairly portable. > From arcege at gmail.com Sat Jun 25 01:24:12 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Fri, 24 Jun 2005 19:24:12 -0400 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: References: <7e5ba9220506240731feb1e1@mail.gmail.com> <7e5ba922050624074912c80088@mail.gmail.com> Message-ID: <7e5ba9220506241624510b8f26@mail.gmail.com> On 6/24/05, Adam Cripps wrote: > > On 6/24/05, Michael P. Reilly wrote: > > On 6/24/05, Adam Cripps wrote: > > > I hadn't thought about a scrollbar - that would be very useful, > > > although doesn't add to the management side of the statement (i.e. > > > organising them according to subjects). > > > > > > The user can load a text file and adapt that - so they don't have to > > > enter them by hand if they have them in a .txt file. Typing them in by > > > hand once is better than typing them in by hand for every child that > > > you have in your class, which is the whole aim of the software. > > > > > > > I could try to whip up an example a little later if you like. I probably > > wouldn't be large, but it could demonstrate tabbed frames with > scrolling. > > > > -Arcege > > -- > > Michael, > > That would be much appreciated. > > Thanks > Adam > Here you go, Adam. It's not full and complete, but it's working and you can customize it how you like. -Michael -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050624/0ff91e34/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: TabbedFrame.py Type: text/x-python Size: 5357 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050624/0ff91e34/TabbedFrame-0001.py From flaxeater at yahoo.com Sat Jun 25 01:26:15 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri, 24 Jun 2005 16:26:15 -0700 (PDT) Subject: [Tutor] Search and Replace Message-ID: <20050624232615.37929.qmail@web54302.mail.yahoo.com> Reed L. O'Brien wrote: >I ma trying to write a script to search adn replace a sizable chink of >text in about 460 html pages. >It is an old form that usesa search engine no linger availabe. > Well in the vein of Kents suggestion there is http://www.crummy.com/software/BeautifulSoup/ however it will change the output some. So if you have some bizarre markup I think it'll try to fix it. Which afaik most html parsers outputers will do. I don't know how to do regex's so I would just do he string manipulation method. Good Luck __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill at celestial.net Sat Jun 25 03:52:45 2005 From: bill at celestial.net (Bill Campbell) Date: Fri, 24 Jun 2005 18:52:45 -0700 Subject: [Tutor] strip an email In-Reply-To: <42BB9745.6060307@h-lab.net> References: <42BA6296.9080803@xit.net> <42BB9745.6060307@h-lab.net> Message-ID: <20050625015245.GA55710@alexis.mi.celestial.com> On Fri, Jun 24, 2005, Hugo Gonz?lez Monteverde wrote: >Hi nephish, > >I clearly remember it is very very simple and it is defined in the RFC. >As far as I remember, the end of the headers are signalled by an empty line. > >Try looking for '\n\n', this should do the trick. I've saved a couple of >emails and it looks like this should work. See http://docs.python.org/lib/module-email.html for easy ways to handle e-mail. The email module has utilities that make it easy to handle headers and body. >something like: > >#full_text holds the full text of the message > >bodypos = full_text.find('\n\n') + 2 > >body = full_text[bodypos:] > >#body now holds the message body > >Please let us know if this works, hope it helps. > >Hugo > >nephish wrote: >> Does anyone know how to strip everything off of an email? >> i have a little app that i am working on to read an email message and >> write the >> body of a message to a log file. >> each email this address gets is only about three to five lines long. >> but i cannot seem to get just the body filtered through. >> i get all the headers, the path, what spam-wall it went through, etc... >> >> any suggestions would be greatly appreciated . >> thanks >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > -- Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Good luck to all you optimists out there who think Microsoft can deliver 35 million lines of quality code on which you can operate your business.'' -- John C. Dvorak From reederk at comcast.net Sat Jun 25 07:21:52 2005 From: reederk at comcast.net (Kevin Reeder) Date: Fri, 24 Jun 2005 22:21:52 -0700 Subject: [Tutor] fileinput problem Message-ID: <20050624222152.75e849b6.reederk@comcast.net> I'm getting unexpected behaviour from this module. My script is meant to count the number of occurences of a term in one or more files. --- import sys, string, fileinput searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = string.count(line, searchterm) if num_matches: print "found '%s' %i times in %s on line %i." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) --- When I run at the command line, this error message appears: $ python ./Python/fileinput.py for ./Python/*.py Traceback (most recent call last): File "./Python/fileinput.py", line 1, in ? import sys, string, fileinput File "./Python/fileinput.py", line 6, in ? for line in fileinput.input(): AttributeError: 'module' object has no attribute 'input' --- I'm stumped. Any ideas? Kevin From kabads at gmail.com Sat Jun 25 09:56:08 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat, 25 Jun 2005 08:56:08 +0100 Subject: [Tutor] Help with Tkinter teachers' report program? In-Reply-To: <7e5ba9220506241624510b8f26@mail.gmail.com> References: <7e5ba9220506240731feb1e1@mail.gmail.com> <7e5ba922050624074912c80088@mail.gmail.com> <7e5ba9220506241624510b8f26@mail.gmail.com> Message-ID: On 6/25/05, Michael P. Reilly wrote: > On 6/24/05, Adam Cripps wrote: > > On 6/24/05, Michael P. Reilly wrote: > > > On 6/24/05, Adam Cripps wrote: > > > > I hadn't thought about a scrollbar - that would be very useful, > > > > although doesn't add to the management side of the statement (i.e. > > > > organising them according to subjects). > > > > > > > > The user can load a text file and adapt that - so they don't have to > > > > enter them by hand if they have them in a .txt file. Typing them in by > > > > hand once is better than typing them in by hand for every child that > > > > you have in your class, which is the whole aim of the software. > > > > > > > > > > I could try to whip up an example a little later if you like. I > probably > > > wouldn't be large, but it could demonstrate tabbed frames with > scrolling. > > > > > > -Arcege > > > -- > > > > Michael, > > > > That would be much appreciated. > > > > Thanks > > Adam > > > > Here you go, Adam. It's not full and complete, but it's working and you > can customize it how you like. > -Michael Many thanks Michael, just studying it now. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Sat Jun 25 12:41:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Jun 2005 06:41:01 -0400 Subject: [Tutor] fileinput problem In-Reply-To: <20050624222152.75e849b6.reederk@comcast.net> References: <20050624222152.75e849b6.reederk@comcast.net> Message-ID: <42BD34BD.7060502@tds.net> Kevin Reeder wrote: > I'm getting unexpected behaviour from this module. My script is > meant to count the number of occurences of a term in one or more > files. > > --- > > import sys, string, fileinput > > searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] > > for line in fileinput.input(): > num_matches = string.count(line, searchterm) > if num_matches: > print "found '%s' %i times in %s on line %i." % (searchterm, > num_matches, fileinput.filename(), fileinput.filelineno()) > > --- > > When I run at the command line, this error message appears: > > $ python ./Python/fileinput.py for ./Python/*.py > > Traceback (most recent call last): > File "./Python/fileinput.py", line 1, in ? > import sys, string, fileinput > File "./Python/fileinput.py", line 6, in ? > for line in fileinput.input(): > AttributeError: 'module' object has no attribute 'input' > > --- > > I'm stumped. Any ideas? You named your program fileinput.py, so when you import fileinput you are getting your own program again instead of the library module. Change the name of your program and try again. Kent From alan.gauld at freenet.co.uk Sat Jun 25 13:54:40 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 25 Jun 2005 12:54:40 +0100 Subject: [Tutor] fileinput problem References: <20050624222152.75e849b6.reederk@comcast.net> Message-ID: <005c01c5797c$aba5c2c0$a89f8851@xp> > Traceback (most recent call last): > File "./Python/fileinput.py", line 1, in ? > import sys, string, fileinput You are importing fileinput from a file called fileinput. It therefore reads your file and notices that you have no input method... Don't call your program the same name as the module! HTH, Alan G. From reederk at comcast.net Sat Jun 25 16:50:22 2005 From: reederk at comcast.net (Kevin Reeder) Date: Sat, 25 Jun 2005 07:50:22 -0700 Subject: [Tutor] fileinput problem In-Reply-To: <42BD34BD.7060502@tds.net> References: <20050624222152.75e849b6.reederk@comcast.net> <42BD34BD.7060502@tds.net> Message-ID: <20050625075022.035345e3.reederk@comcast.net> On Sat, 25 Jun 2005 06:41:01 -0400 Kent Johnson wrote: > You named your program fileinput.py, so when you import fileinput > you are getting your own program again instead of the library > module. Change the name of your program and try again. Doh! I do remember reading that somewhere before. Lesson learnt. Kevin From albertito_g at hotmail.com Sat Jun 25 19:00:47 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Sat, 25 Jun 2005 17:00:47 +0000 Subject: [Tutor] MineSweeper Message-ID: Hey Tutors I have a question I want to make a minesweeper (just for practice) but I don't what can I use to make the GUI I was thinking about buttons (click event you know) and change the background image on change Maybe there's another widget to use My doubt is that I want to be able to allow the user to put how many bombs they want and how any spaces (how big is the board) so I will have to create buttons dinamically, but in doing this the reference to the buttons will be lost How do I know which button did I click when all buttons have the same name? Does this make sense? I recall in VB.6.0 the control matrix but I never knew how to use it Any help? Thanks in advanced Alberto From kabads at gmail.com Sat Jun 25 19:24:20 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat, 25 Jun 2005 18:24:20 +0100 Subject: [Tutor] MineSweeper In-Reply-To: References: Message-ID: On 6/25/05, Alberto Troiano wrote: > Hey Tutors > I have a question > I want to make a minesweeper (just for practice) but I don't what can I use > to make the GUI > I was thinking about buttons (click event you know) and change the > background image on change > Maybe there's another widget to use > My doubt is that I want to be able to allow the user to put how many bombs > they want and how any spaces (how big is the board) so I will have to create > buttons dinamically, but in doing this the reference to the buttons will be > lost > How do I know which button did I click when all buttons have the same name? > Does this make sense? > I recall in VB.6.0 the control matrix but I never knew how to use it > > Any help? > > Thanks in advanced > > Alberto I have written some similar code to this - you give each button a different name through an interator. You can see my code at: http://www.sf.net/projects/jiletters and follow the links to the CVS code repository. For that, I used wxPython, but it's up to you what you go for. The main part that may be useful to you is: for i in noduplicatesalphabet: identity = int(D[i]) + 29 # It's quicker to add 29 than go through and edit the dictionary by hand bmp = wxBitmap('alphabet_graphics/' + i + '.bmp', wxBITMAP_TYPE_BMP) self.grafic =wxBitmapButton(self, identity,bmp,wxPoint(160,20), wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) self.sizer2.Add(self.grafic,1,wxEXPAND) EVT_BUTTON(self, identity, self.ButtonPushed) The noduplicates is a list that I generated by hand, but you could do this in a range(a,b) way if it's not attached to any particular data or meaning. The EVT_BUTTON passes the id to the function self.ButtonPushed, which then can tell which button was pushed. HTH Adam -- http://www.monkeez.org PGP key: 0x7111B833 From adam.jtm30 at gmail.com Sat Jun 25 21:07:38 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sat, 25 Jun 2005 20:07:38 +0100 Subject: [Tutor] wxPython shaped window Message-ID: Is it possible to put controls into a shaped window in wxPython. I have tried putting a button on the demo and it becomes the exact size and shape of the window. Also when I tried to bind it to an action it wouldn't even start. Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050625/5bfb3887/attachment.htm From kabads at gmail.com Sat Jun 25 22:02:11 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat, 25 Jun 2005 21:02:11 +0100 Subject: [Tutor] wxPython shaped window In-Reply-To: References: Message-ID: On 6/25/05, Adam Bark wrote: > Is it possible to put controls into a shaped window in wxPython. I have > tried putting a button on the demo and it becomes the exact size and shape > of the window. Also when I tried to bind it to an action it wouldn't even > start. > > Adam > I'm working through something similar myself at the moment. Try adding a wx.Panel to the frame and then the button to the panel. You can position them through pos parameter, but it should default to the top left of the panel and have a good size if you use button.SetSize(button.GetBestSize()) HTH Adam -- http://www.monkeez.org PGP key: 0x7111B833 From adam.jtm30 at gmail.com Sun Jun 26 00:17:14 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sat, 25 Jun 2005 23:17:14 +0100 Subject: [Tutor] wxPython shaped window In-Reply-To: References: Message-ID: Thanks for the info Adam I just seem to be having a problem with the panel size it greys out nearly all the image. Ideally I would like to make the panel transparent but I can't work out how to do that. On 6/25/05, Adam Cripps wrote: > > On 6/25/05, Adam Bark wrote: > > Is it possible to put controls into a shaped window in wxPython. I have > > tried putting a button on the demo and it becomes the exact size and > shape > > of the window. Also when I tried to bind it to an action it wouldn't > even > > start. > > > > Adam > > > > I'm working through something similar myself at the moment. > > Try adding a wx.Panel to the frame and then the button to the panel. > You can position them through pos parameter, but it should default to > the top left of the panel and have a good size if you use > button.SetSize(button.GetBestSize()) > > HTH > > Adam > -- > http://www.monkeez.org > PGP key: 0x7111B833 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050625/7427d44f/attachment.htm From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 02:33:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Jun 2005 17:33:58 -0700 (PDT) Subject: [Tutor] MineSweeper In-Reply-To: Message-ID: On Sat, 25 Jun 2005, Alberto Troiano wrote: > My doubt is that I want to be able to allow the user to put how many > bombs they want and how any spaces (how big is the board) so I will have > to create buttons dinamically, but in doing this the reference to the > buttons will be lost How do I know which button did I click when all > buttons have the same name? Does this make sense? Hi Alberto, [The following is a tutorial about using functions as values; it's a bit long, so if you have any questions at all, ask!] In Tkinter, each button can be associated with a "command" that gets called when we press a button. ### Example One ### from Tkinter import * def sayRefrain(): print "... for the rain, it raineth every day" root = Tk() button = Button(root, text="hey ho the wind and the rain", command=sayRefrain) button.pack() root.mainloop() ################### Note that when we say that our 'button' should use 'sayRefrain', not 'sayRefrain()'. We're using a function as a value that the button will remember. Just as the button knows what text it should show, it also knows which function it should call when we press it. So that's a quick and dirty example of a window with one button. But let's say that we have two buttons, now. How can we distinguish one button from another button? We can do this by attaching two separate commands to the individual buttons: ### Example Two ### from Tkinter import * def sayRefrain1(): print "... for the rain, it raineth every day" def sayRefrain2(): print "... and we'll strive to please you every day" root = Tk() button1 = Button(root, text="hey ho the wind and the rain", command=sayRefrain1) button2 = Button(root, text="hey ho the wind and the rain", command=sayRefrain2) button1.pack() button2.pack() root.mainloop() ################## Ok, now we have two buttons in our example. We can distinguish between buttons by associating different commands to them: they have the same text, but they do different things. By the way, just to make sure this point is clear: we're just passing the function values of sayRefrain1 and sayRefrain2 instead of calling them directly. If we just ask Python what the value of sayRefrain1 is: ####### >>> sayRefrain1 ####### it's just a value, just as: ####### >>> "hey ho the wind and the rain" 'hey ho the wind and the rain' ####### is just a value, just like the familiar numbers and strings that you've been using before. Function values are a little special in one regard: they do things if we put parens after them, as you know: ####### >>> sayRefrain2() ... and we'll strive to please you every day ####### but being able to call a function value is pretty much all that distinguish a function value from other Python values. Ok, let's get back to our examples. We went from an example with one button, to an example with two. I think you can guess where we're about to go. *grin* Now let's say that we have a few more buttons that we'd like to use. We know what we'd like each button should say: ####### buttonMessages = ["When that I was and a little tiny boy,", "But when I came to main's estate,", "But when I came alas to wive,", "But when I came unto my beds,"] ####### But let's wait for a moment before plunging forward. If we go along the path that our other examples have been going through, it might be a little tedious to define a separate sayRefrainX for every message in our list. But we can do a little better. Let's try something new: ###### def makeRefrainPrinter(message): """Given a message, returns a new function that'll say the message.""" def sayRefrain(): print message return sayRefrain ###### What does makeRefrainPrinter() do? Let's try playing with it: ###### >>> makeRefrainPrinter("as I am an honest puck") ###### If we call makeRefrainPrinter(), it gives us back a function value. Let's see what happens if we call that function value: ###### >>> someFunctionValue = makeRefrainPrinter("as I am an honest puck") >>> someFunctionValue() as I am an honest puck ###### makeRefrainPrinter() makes up function values, on the fly, so that we can make any kind of sayRefrainX function value with relative ease. If we have this makeRefrainPrinter function, now our example code can look like this: ### Example Three ### from Tkinter import * buttonMessages = ["When that I was and a little tiny boy,", "But when I came to main's estate,", "But when I came alas to wive,", "But when I came unto my beds,"] def makeRefrainPrinter(message): """Given a message, returns a new function that'll say the message.""" def sayRefrain(): print message return sayRefrain root = Tk() for msg in buttonMessages: someFunctionValue = makeRefrainPrinter(msg) button = Button(root, text="hey, ho, the wind and the rain", command=someFunctionValue) button.pack() root.mainloop() ##################### Does this make sense so far? This is still a little bit of a way from getting a Minesweeper GUI, but it's surprisingly close to the minimal concepts you can use to make a Minesweeper-like program. I hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 02:46:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Jun 2005 17:46:27 -0700 (PDT) Subject: [Tutor] wxPython shaped window In-Reply-To: Message-ID: On Sat, 25 Jun 2005, Adam Bark wrote: > Is it possible to put controls into a shaped window in wxPython. I have > tried putting a button on the demo and it becomes the exact size and > shape of the window. Also when I tried to bind it to an action it > wouldn't even start. Hi Adam, You might want to ask this on the wxPython-users mailing list: http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi/11 They're more focused on wxPython GUI stuff than the folks on Tutor, and they appear pretty active too. Best of wishes! From mjxny at hotmail.com Sun Jun 26 04:24:05 2005 From: mjxny at hotmail.com (Ming Xue) Date: Sat, 25 Jun 2005 22:24:05 -0400 Subject: [Tutor] clob and string conversion Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050625/1e90fbac/attachment.htm From webdev at matheteuo.org Sun Jun 26 07:40:32 2005 From: webdev at matheteuo.org (Don Parris) Date: Sun, 26 Jun 2005 01:40:32 -0400 Subject: [Tutor] Alternative File I/O for Tuples Message-ID: <20050626014032.475ac99f@luke.matheteuo.rel> When I pickle a SQL result into a file (ASCII mode), it lays out the data in an interesting format. When I send it to the printer, I'd like to see it arranged more like it is on the console screen - in tabbed columns. None of the tutorial type stuff I've seen even mentions printing files, or accessing the files you create in a Python program. I did manage to find an example of a print function. Here is some sample data from the resulting file: ((S'Everybody' S'Anonymous' Nt(S'James' S'Austin' S'704-111-1234' t(S'Janet' S'Austin' S'704-111-1234' I would like to see something more like when the file is printed: Austin James 704-111-1234 Austin Janet 704-111-1234 etc. Is this a simple task, or am I jumping into deep water? :) Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 07:41:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Jun 2005 22:41:08 -0700 (PDT) Subject: [Tutor] clob and string conversion In-Reply-To: Message-ID: On Sat, 25 Jun 2005, Ming Xue wrote: > I am trying to access oracle9i with cx_Oracle package. One of the column > is clob and when I tried clob.read() I got non-text output. I know the > real data is text. Can somebody show me how to convert clob to string in > python? Hi Ming, This seems really specialized to the cx_Oracle database module; you may want to see if the folks at the Database Special Interest Group (DB-SIG): http://www.python.org/sigs/db-sig/ because the folks there are probably more aware of some issues one needs to think about with CLOBs: we at Tutor might not necessary have the special experience that we need to give you the best help. I've been looking at the definition of the LOB object interface, http://starship.python.net/crew/atuining/cx_Oracle/html/lobobj.html and it does seem like clob.read() should do the trick. Without seeing what you're doing, it's very difficult to know what's going on. Do you mind showing us an example of the text that you're getting back from the CLOB, and what you're expecting to see? You do mention that you're getting something back, but it doesn't look like text to you... Ok, my best guess so far is that you may be seeing a text encoding that you're not expecting. I'll go with that guess until we know more information. *grin* If you can show us that example, we'll have a better basis for testing the hypothesis. Do you know what text encoding the strings in your database are in? Are they in Latin-1, or perhaps in a Unicode format such as UTF-8 or UTF-16? The reason I ask is because it's not at all obvious from looking at bytes alone how to interpret them, so it's possible that you may need to "decode" those bytes by telling Python explicitely what encoding to use. CLOBs are binary streams, so Python will never impose an interpretation on those bytes until we tell it to. For example, if one were to give us the byte string: ###### secret = '\xfe\xff\x00h\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d' ###### then we'd probably be quite unhappy until we also knew that those bytes represented a string in utf-16 encoding: ###### >>> secret.decode('utf-16') u'hello world' ###### For a more general introduction to unicode encodings, you may want to look at Joel Spolsky's amusing article on "The Absolute Minimum Every Software Developer Absolutely, Postitively Must Know About Unicode and Character Sets (No Excuses!)": http://www.joelonsoftware.com/articles/Unicode.html Python's supported list of encodings are listed here: http://www.python.org/doc/lib/standard-encodings.html Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 07:48:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Jun 2005 22:48:34 -0700 (PDT) Subject: [Tutor] Alternative File I/O for Tuples In-Reply-To: <20050626014032.475ac99f@luke.matheteuo.rel> Message-ID: > I would like to see something more like when the file is printed: > > Austin James 704-111-1234 > Austin Janet 704-111-1234 > etc. > > Is this a simple task, or am I jumping into deep water? :) Hi Don, Not too bad; I think you'll looking for "String Formatting": http://www.python.org/doc/lib/typesseq-strings.html The idea is that we use a template to lay out the rows. This template gives the general shape of what we want. In your example, it looks like every row is ten characters long. A template that can lay out two values as two columns might looks something like this: ###### >>> "%10s%10s" % ("Curious", "George") ' Curious George' ###### Oh, it's justified right. Let me switch that over: ###### >>> "%-10s%-10s" % ("Curious", "George") 'Curious George ' ###### Ok, that's better. *grin* So you should be able to generalize this to build up these nicely formatted lines that can be printed at once. There are some other sophisticated string-formatting tools in Python, many of which live in strings themselves. http://www.python.org/doc/lib/string-methods.html For example, strings even know how to "center" themselves: ###### >>> 'I am a centered sentence.'.center(40) ' I am a centered sentence. ' ###### If you have more questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 07:52:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Jun 2005 22:52:08 -0700 (PDT) Subject: [Tutor] Alternative File I/O for Tuples In-Reply-To: Message-ID: > In your example, it looks like every row is ten characters long. A ^^^ Hi Don, Gaa, that's why I'm so bad at matrix math. I meant "column", not "row". Sorry about that. From kabads at gmail.com Sun Jun 26 09:23:02 2005 From: kabads at gmail.com (Adam Cripps) Date: Sun, 26 Jun 2005 08:23:02 +0100 Subject: [Tutor] wxPython shaped window In-Reply-To: References: Message-ID: On 6/25/05, Adam Bark wrote: > Thanks for the info Adam I just seem to be having a problem with the panel > size it greys out nearly all the image. Ideally I would like to make the > panel transparent but I can't work out how to do that. > > > On 6/25/05, Adam Cripps wrote: > > On 6/25/05, Adam Bark wrote: > > > Is it possible to put controls into a shaped window in wxPython. I have > > > tried putting a button on the demo and it becomes the exact size and > shape > > > of the window. Also when I tried to bind it to an action it wouldn't > even > > > start. > > > > > > Adam > > > > > > > I'm working through something similar myself at the moment. > > > > Try adding a wx.Panel to the frame and then the button to the panel. > > You can position them through pos parameter, but it should default to > > the top left of the panel and have a good size if you use > > button.SetSize(button.GetBestSize()) > > > > HTH > > > > Adam Adam - how much code do you have? Why not post it either here or the wxpython-users list (to which I'm also subscribed) and we can take a look. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From alan.gauld at freenet.co.uk Sun Jun 26 10:19:19 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 26 Jun 2005 09:19:19 +0100 Subject: [Tutor] MineSweeper References: Message-ID: <008001c57a27$c07407b0$a89f8851@xp> > How do I know which button did I click when all buttons have the same name? Put them in a matrix. ie a list of lists. Then refer to them by their position inthe lists so that the top left button is "buttons[0][0]" etc This is also how you dynamically create your screen, just iterate over the list to create and pack/grid/place each button. HTH, Alan G. From bvande at po-box.mcgill.ca Sun Jun 26 10:32:43 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 26 Jun 2005 04:32:43 -0400 Subject: [Tutor] filtering a webpage for plucking to a Palm Message-ID: <42BE682B.50109@po-box.mcgill.ca> Hi all, I have a Palm handheld, and use the excellent (and written in Python) Plucker to spider webpages and format the results for viewing on the Palm. One site I 'pluck' is the Daily Python URL . From the point of view of a daily custom 'newspaper' everything but the last day or two of URLs is so much cruft. (The cruft would be the total history of the last seven'ish days, the navigation links for www.pythonware.com, etc.) Today, I wrote a script to parse the Daily URL, and create a minimal local html page including nothing but the last n items, n links, or last n days worth of links. (Which is employed is a user option.) Then, I pluck that, rather than the actual Daily URL site. Works great. :-) (If anyone on the list is a fellow plucker'er and would be interested in my script, I'm happy to share.) In anticipation of wanting to do the same thing to other sites, I've spent a bit of time abstracting it. I've made some real progress. But, before I finish up, I've a voice in the back of my head asking if maybe I'm re-inventing the wheel. To my shame, I've not spent very much time at all exploring available frameworks and modules for any domain, and almost none for web-related tasks. So, does anyone know of any modules or frameworks which would make the sort of task I am describing easier? The difficulty in making my routine general is that pretty much each site will need its own code for identifying what counts as a distinct item (such as a URL and its description in the Daily URL) and what counts as a distinct block of items (such as a days worth of Daily URL items). I can't imagine there's a way around that, but if someone else has done much of the work in setting up the general structure to be tweaked for each site, that'd be good to know. (Doesn't feel like one that would be googleable.) Thanks for any suggestions, and best to all, Brian vdB From kent37 at tds.net Sun Jun 26 15:24:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Jun 2005 09:24:10 -0400 Subject: [Tutor] Alternative File I/O for Tuples In-Reply-To: <20050626014032.475ac99f@luke.matheteuo.rel> References: <20050626014032.475ac99f@luke.matheteuo.rel> Message-ID: <42BEAC7A.6090801@tds.net> Don Parris wrote: > When I pickle a SQL result into a file (ASCII mode), it lays out the data in > an interesting format. pickle format is not intended for pretty-printing or readability for that matter. You have to write the file yourself in the format you want. > When I send it to the printer, I'd like to see it > arranged more like it is on the console screen - in tabbed columns. None of > the tutorial type stuff I've seen even mentions printing files, or accessing > the files you create in a Python program. I did manage to find an example > of a print function. It sounds like you want to write a file for later printing. Writing files should be covered in any Python tutorial; the standard tutorial talks about it here: http://docs.python.org/tut/node9.html#SECTION009200000000000000000 Danny has given you some hints about how to do the formatting. This recipe has a very complete solution for formatting tables. You could easily change the example to print to a file: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent > > Here is some sample data from the resulting file: > > ((S'Everybody' > S'Anonymous' > Nt(S'James' > S'Austin' > S'704-111-1234' > t(S'Janet' > S'Austin' > S'704-111-1234' > > I would like to see something more like when the file is printed: > > Austin James 704-111-1234 > Austin Janet 704-111-1234 > etc. > > Is this a simple task, or am I jumping into deep water? :) > > Don From kent37 at tds.net Sun Jun 26 15:31:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Jun 2005 09:31:25 -0400 Subject: [Tutor] filtering a webpage for plucking to a Palm In-Reply-To: <42BE682B.50109@po-box.mcgill.ca> References: <42BE682B.50109@po-box.mcgill.ca> Message-ID: <42BEAE2D.6070602@tds.net> Brian van den Broek wrote: > Hi all, > > I have a Palm handheld, and use the excellent (and written in Python) > Plucker to spider webpages and format the > results for viewing on the Palm. > > One site I 'pluck' is the Daily Python URL > . From the point of view of a daily > custom 'newspaper' everything but the last day or two of URLs is so > much cruft. (The cruft would be the total history of the last > seven'ish days, the navigation links for www.pythonware.com, etc.) > > Today, I wrote a script to parse the Daily URL, and create a minimal > local html page including nothing but the last n items, n links, or > last n days worth of links. (Which is employed is a user option.) > Then, I pluck that, rather than the actual Daily URL site. Works > great. :-) (If anyone on the list is a fellow plucker'er and would be > interested in my script, I'm happy to share.) > > In anticipation of wanting to do the same thing to other sites, I've > spent a bit of time abstracting it. I've made some real progress. But, > before I finish up, I've a voice in the back of my head asking if > maybe I'm re-inventing the wheel. > > To my shame, I've not spent very much time at all exploring available > frameworks and modules for any domain, and almost none for web-related > tasks. So, does anyone know of any modules or frameworks which would > make the sort of task I am describing easier? > > The difficulty in making my routine general is that pretty much each > site will need its own code for identifying what counts as a distinct > item (such as a URL and its description in the Daily URL) and what > counts as a distinct block of items (such as a days worth of Daily URL > items). I can't imagine there's a way around that, but if someone else > has done much of the work in setting up the general structure to be > tweaked for each site, that'd be good to know. (Doesn't feel like one > that would be googleable.) Beautiful Soup can help with parsing and accessing the web page. You could certainly write your plucker on top of it. http://www.crummy.com/software/BeautifulSoup/ Alternately ElementTidy might help. It can parse web pages and it has limited XPath support. XPath might be a good language for expressing your plucking rules. http://effbot.org/zone/element-tidylib.htm An ideal package would be one that parses real-world HTML and has full XPath support, but I don't know of such a thing...maybe amara or lxml? Kent From alan.gauld at freenet.co.uk Sun Jun 26 16:09:39 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 26 Jun 2005 15:09:39 +0100 Subject: [Tutor] Alternative File I/O for Tuples References: <20050626014032.475ac99f@luke.matheteuo.rel> Message-ID: <00a801c57a58$b11596e0$a89f8851@xp> > arranged more like it is on the console screen - in tabbed columns. None of > the tutorial type stuff I've seen even mentions printing files, One reason is that printing is one of those things that is different on evry operating system. So tutorials (including mine) tend to steer clear of it. If you are on Unix its fairly easy to print stuff just by piping stdout to the lpr or pr commands. On Windows I tend to print by creating an HTML file and then using os.system() to print the file using my browser... On Mac tyou can use the Unix trick or convert to PDF. To do proper formatted printing on windows is inordinately difficult and involves effectively printing your page as a graphic to a printer "device context". I seem to recall someone pointing out a printer module which I meant to investigate but never got round to it, maybe trawling the archives would throw it up. > Here is some sample data from the resulting file: > > ((S'Everybody' > S'Anonymous' > Nt(S'James' > S'Austin' > S'704-111-1234' > t(S'Janet' > S'Austin' > S'704-111-1234' > > I would like to see something more like when the file is printed: > > Austin James 704-111-1234 > Austin Janet 704-111-1234 > etc. This is to do with formatting the data into strings before you print it. You can use a format string to define the layout(column widths, justification, number of decimal places etc) andthen send those lines to the printer as described above. If using the HTML trick you need to add the HTML codes too, in this case you would format each row like: fmt = "%10s%10s%3d-%3d-%4d" And then print a table header followed by a loop printing each line of data followed by a close table tag, something like this: text = ''' ''' for data in people: #substitute your data here text += fmt % (data[0],data[1],data[2],data[3],data[4]) text += '
LastFirstPhone
' prtfile = open('temp.html','w') prtfile.write(text) prtfile.close() os.system('lynx -p ./temp.html') > Is this a simple task, or am I jumping into deep water? :) > evangelinux GNU Evangelist Given your signature its probably not too difficult, you can just send the basic text string to lpr, or use the html trick above. You might even like to investigate the use of groff to format the text instead of html - that's much nicer and the technique I actually use on Unix. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Sun Jun 26 21:11:44 2005 From: pythontut at pusspaws.net (Dave S) Date: Sun, 26 Jun 2005 20:11:44 +0100 Subject: [Tutor] Windows user variable ? Message-ID: <42BEFDF0.8020905@pusspaws.net> Hi there, Probably no one will remember but I had a problem porting a python script to windows, I had a 'no such file error' Turned out that I called the file 'memo.txt', Windows decided it was a text file and it ended up as 'memo.txt.txt'. The windows display strips anything after the '.', found the problem via dos :) Anyhow - When logged into 2000 as an administrator or user is there a system variable that I can read to let the script know who I am logged in as ? Dave From dyoo at hkn.eecs.berkeley.edu Sun Jun 26 22:08:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 Jun 2005 13:08:35 -0700 (PDT) Subject: [Tutor] Alternative File I/O for Tuples (fwd) Message-ID: ---------- Forwarded message ---------- Date: Sun, 26 Jun 2005 14:29:22 -0400 From: Don Parris To: Danny Yoo Subject: Re: [Tutor] Alternative File I/O for Tuples On Sat, 25 Jun 2005 22:52:08 -0700 (PDT) Danny Yoo wrote: > > > > In your example, it looks like every row is ten characters long. A > ^^^ > Hi Don, > > Gaa, that's why I'm so bad at matrix math. I meant "column", not "row". > Sorry about that. I guess I should have used a different example - some names are longer than others. Williams is shorter than Vandenbosch, for example. So the columns will need to be formatted appropriately. I'll play with this a bit. I should also have said that I need to work primarily with GNU/Linux - printing with Windows can come a little later. Kent is kind of on track. I let the user view the report on the console screen (nice to verify what you're about to print), and then give them the choice of printing it, or returning to the menu for other tasks. For instance, they may simply want to look up a number, not print out the phone list. ### Print or Return to Menu ### if whatNext == 'p': os.system("lpr mbrPhone.txt") # prints the pickled file. elif whatNext == 'r': pass # BTW, is this a good use of "pass"? The screen print out is as it should be - nice, neat columns. So, instead of this: print 'Phone List' for record in Results: print '%s\t%s\t%s' % record # prints to screen mbrPhone = open('mbrPhone.txt', 'w') cPickle.dump(Results, mbrPhone) # pickles the data into a file mbrPhone.close() I tried this: mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.writelines(repr(Results)) mbrPhone.close() Which produces this in the text file: (('Everybody', 'Anonymous', None), ('James', 'Austin', '704-111-1234'), ('Janet', 'Austin', '704-111-1234'), ('James', 'Austin', '704-111-1234'), This is an improvement over pickling the data into a file. Still, it's not quite the columnar layout I'd like to achieve. I'll try that recipe that was suggested to see if I can get it working with files. If it's the one I'm thinking of, it offers a fantastic layout ('bout as good as it gets with ASCII text) for printing out to screen. I guess I'm asking two closely-related questions: (1) how to format the file so it can be readable, and (2) how to send that file to the printer. I used os.system('lpr, filename') above. Is there another way? Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From kent37 at tds.net Sun Jun 26 22:32:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Jun 2005 16:32:08 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: References: Message-ID: <42BF10C8.4070003@tds.net> > From: Don Parris > To: Danny Yoo > Subject: Re: [Tutor] Alternative File I/O for Tuples > > I guess I'm asking two closely-related questions: > (1) how to format the file so it can be readable, and If you like the recipe I posted, this could be as simple as mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(...appropriate args to indent...)) mbrPhone.close() Kent From richard at inferspace.com Mon Jun 27 00:09:37 2005 From: richard at inferspace.com (Richard Dybowski) Date: Sun, 26 Jun 2005 23:09:37 +0100 Subject: [Tutor] Improving printouts from IDLE Message-ID: <5.2.1.1.2.20050626230712.00a56cd0@mailhost.zen.co.uk> The printing facility provided with IDLE is rather rudimentary. Is there any way of obtaining better quality printouts from IDLE? Richard ------------------------------- Dr Richard Dybowski 143 Village Way Pinner HA5 5AA, UK Tel: 07976 250092 From jfouhy at paradise.net.nz Mon Jun 27 00:16:12 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 27 Jun 2005 10:16:12 +1200 (NZST) Subject: [Tutor] Windows user variable ? In-Reply-To: <42BEFDF0.8020905@pusspaws.net> References: <42BEFDF0.8020905@pusspaws.net> Message-ID: <1119824172.42bf292c441da@www.paradise.net.nz> Quoting Dave S : > Turned out that I called the file 'memo.txt', Windows decided it was a > text file and it ended up as 'memo.txt.txt'. The windows display strips > anything after the '.', found the problem via dos :) I recomment going to Windows Explorer -> Folder Options and unchecking the "Hide extensions for known file types" option :-) > Anyhow - When logged into 2000 as an administrator or user is there a > system variable that I can read to let the script know who I am logged > in as ? If you have the win32 extensions, try win32api.GetUserName(). -- John. From alan.gauld at btinternet.com Mon Jun 27 08:57:42 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2005 07:57:42 +0100 Subject: [Tutor] Improving printouts from IDLE References: <5.2.1.1.2.20050626230712.00a56cd0@mailhost.zen.co.uk> Message-ID: > The printing facility provided with IDLE is rather rudimentary. Is there > any way of obtaining better quality printouts from IDLE? Specifically what would you like to 'improve'? Do you mean sopmething like the HTML output of vim or the pretty printer of emacs or pythonwin? IDLE just sends the file to Notepad so far as I recall, you could potentially change it to send it via another print enabled program... But if you want to keep the colour coding that might be harder. Sounds like a worthwhile mini project for someone to try and submit to the oidle developers... the joys of open-source. Alan G. From snoylr at cheqnet.net Mon Jun 27 14:03:59 2005 From: snoylr at cheqnet.net (Richard Lyons) Date: Mon, 27 Jun 2005 07:03:59 -0500 Subject: [Tutor] Improving printouts from IDLE Message-ID: <42BFEB2F.906@cheqnet.net> Given the difficulties that I've found trying to print from Python, I was just commenting this week-end on the efficiency of the printing process used in IDLE. What is the specific code that allows the IDLE window to be printed to notepad (in Windows XP)? From x12345jp at yahoo.com.hk Mon Jun 27 15:44:14 2005 From: x12345jp at yahoo.com.hk (john taylor) Date: Mon, 27 Jun 2005 21:44:14 +0800 (CST) Subject: [Tutor] How to send an array of clusters from python to labview?? Message-ID: <20050627134414.86095.qmail@web50405.mail.yahoo.com> hi all, i am using win32com to call labview from python over COM. i want to set the value of a control element in a VI per SetControlValue(), and the control in the VI is an array of cluster, which has the structure (integer, integer, string). CODE: ... >>> aoc = ((2,3,"hello"), (4,5,"world")) >>> vi.SetControlValue("array of cluster", aoc) Traceback (most recent call last): File "", line 1, in ? File ">", line 2, in setcontrolvalue com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, None, None, None, 0, -2147352571), 2) anybody with experience in python/com/labview has idea?? thanks a lot in advance? cheers, john From jsmith at medplus.com Mon Jun 27 16:42:48 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon, 27 Jun 2005 10:42:48 -0400 Subject: [Tutor] Windows user variable ? Message-ID: I would personally suggest using getpass.getuser() for maximum portability. Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of jfouhy at paradise.net.nz Sent: Sunday, June 26, 2005 6:16 PM To: tutor at python.org Subject: Re: [Tutor] Windows user variable ? Quoting Dave S : > Turned out that I called the file 'memo.txt', Windows decided it was a > text file and it ended up as 'memo.txt.txt'. The windows display > strips anything after the '.', found the problem via dos :) I recomment going to Windows Explorer -> Folder Options and unchecking the "Hide extensions for known file types" option :-) > Anyhow - When logged into 2000 as an administrator or user is there a > system variable that I can read to let the script know who I am logged > in as ? If you have the win32 extensions, try win32api.GetUserName(). -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Mon Jun 27 20:13:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Jun 2005 11:13:28 -0700 (PDT) Subject: [Tutor] Help - im a beinner in using python (fwd) Message-ID: [I am forwarding this to the main Tutor list. Enas, if you're not subscribed already to the Tutor list, visit: http://mail.python.org/mailman/listinfo/tutor Once you're subscribed, you can freely post questions to the Python-tutor mailing list at the email address 'tutor at python.org'.] ---------- Forwarded message ---------- Date: Mon, 27 Jun 2005 04:33:35 -0700 (PDT) From: enas khalil To: tutor-owner at python.org Subject: Help - im a beinner in using python dear all could you if you please tell me how can i start learning python im reading on tutorial and i have questions about: - how can i adjust the environmental variable on windows platform -where should i put the NLTK data to be accessible by python -how can i use TKinter in python is it only the "fom Tkinter import *" command ,i did this it sometimes woks and sometimes doesnt -i want to know the way to have a Tkinter GUI fo any python code i write thanks in advance __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Jun 27 20:34:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Jun 2005 11:34:10 -0700 (PDT) Subject: [Tutor] Improving printouts from IDLE In-Reply-To: <42BFEB2F.906@cheqnet.net> Message-ID: On Mon, 27 Jun 2005, Richard Lyons wrote: > What is the specific code that allows the IDLE window to be printed to > notepad (in Windows XP)? Hi Richard, The relevant code that does the "Print Window" command lives in the IOBinding submodule of IDLE, within the print_window() method: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/idlelib/IOBinding.py?view=markup where it appears that IDLE will delegate the paper printing of a window's contents by using Notepad, using the following (in config-main.def) start /min notepad /p %s >From what I can tell so far, it looks relatively straightforward. > Given the difficulties that I've found trying to print from Python, I > was just commenting this week-end on the efficiency of the printing > process used in IDLE. According to the source code, IDLE just passes text through notepad directly, with no fontification. But since the command is actually a configuration option, it's very possible to reconfigure the system to first pass that code through a beautification process. Hmm... it sounds like an interesting weekend project to get high-quality source output from IDLE. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Mon Jun 27 20:48:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Jun 2005 11:48:09 -0700 (PDT) Subject: [Tutor] How to send an array of clusters from python to labview?? In-Reply-To: <20050627134414.86095.qmail@web50405.mail.yahoo.com> Message-ID: On Mon, 27 Jun 2005, john taylor wrote: > i am using win32com to call labview from python over COM. i want to set > the value of a control element in a VI per SetControlValue(), and the > control in the VI is an array of cluster, which has the structure > (integer, integer, string). > > >>> aoc = ((2,3,"hello"), (4,5,"world")) > >>> vi.SetControlValue("array of cluster", aoc) > Traceback (most recent call last): > File "", line 1, in ? > File ">", line 2, in > setcontrolvalue > com_error: (-2147352567, 'Ausnahmefehler > aufgetreten.', (0, None, None, None, 0, -2147352571), Hi John, This seems a bit specific to the Windows platform; you might want to ask this on Python-win32, especially since it looks like other LabView folks have been asking questions there too: http://mail.python.org/pipermail/python-win32/2005-April/003182.html The Python-Win32 list is here: http://mail.python.org/mailman/listinfo/python-win32 It's not that we don't like answering questions, but that I don't think many of us here have the expertise to help with COM issues. The folks at python-win32, however, should be able to help you. It will also be useful to show how you're constructing the labview object 'lv'. >From a first glance, you meantion that SetControlValue takes in an array of cluster information. You've contructed a tuple: ###### aoc = ((2,3,"hello"), (4,5,"world")) ###### and I'm not quite sure if the COM bridge will automatically translate this into an 'array' that COM likes. According to the thread on: http://aspn.activestate.com/ASPN/Mail/Message/python-list/1556557 and Mark Hammond's reponse: http://aspn.activestate.com/ASPN/Mail/Message/python-list/1556557 you might need to build your 'lv' object in a particular way to make sure the proper type information is maintained. But again, I don't run Windows: I have no clue what's going on. *grin* Ask the win32 list, and someone there should be able to figure out what's happening. Best of wishes! From pythontut at pusspaws.net Mon Jun 27 21:04:24 2005 From: pythontut at pusspaws.net (Dave S) Date: Mon, 27 Jun 2005 20:04:24 +0100 Subject: [Tutor] Windows user variable ? In-Reply-To: References: Message-ID: <42C04DB8.8030506@pusspaws.net> Thanks for your help guys Dave From John.Gooch at echostar.com Mon Jun 27 21:38:50 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Mon, 27 Jun 2005 13:38:50 -0600 Subject: [Tutor] CGI Tutorial Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D4EB@riv-excha5.echostar.com> Are there any tutorials on the Python CGI module? I think I found enough fragments to get form data, but I need a way for the Python script to tell whether it is being run in a web server environment or from the command line. What I am thinking is testing for an environment variable that only exists in the CGI environment, but not in a command shell. Any ideas on how to do this? The web environment is Windows 2000 OS with IIS 6.0 and Python 2.4. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From dyoo at hkn.eecs.berkeley.edu Tue Jun 28 00:51:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Jun 2005 15:51:24 -0700 (PDT) Subject: [Tutor] CGI Tutorial In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D4EB@riv-excha5.echostar.com> Message-ID: On Mon, 27 Jun 2005, Gooch, John wrote: > Are there any tutorials on the Python CGI module? I think I found enough > fragments to get form data, but I need a way for the Python script to > tell whether it is being run in a web server environment or from the > command line. > What I am thinking is testing for an environment variable > that only exists in the CGI environment, but not in a command shell. Hi John, According to the CGI specification here: http://hoohoo.ncsa.uiuc.edu/cgi/ http://hoohoo.ncsa.uiuc.edu/cgi/env.html the program should expect to see a few environmental variables. One popular environmental variable that's used to detect if we're running off the command shell is 'REQUEST_METHOD'. (Perl's CGI.pm uses REQUEST_METHOD to figure out if a cgi program is being run from the command line or not.) So something like: ###### def is_running_as_cgi(): """Returns True if we're running as a CGI.""" acceptable = ('POST', 'GET', 'HEAD') return os.environ.get('REQUEST_METHOD', '').upper() in acceptable #### might do the trick. Best of wishes! From webdev at matheteuo.org Tue Jun 28 07:09:20 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 28 Jun 2005 01:09:20 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42BF10C8.4070003@tds.net> References: <42BF10C8.4070003@tds.net> Message-ID: <20050628010920.62cf8f6d@luke.matheteuo.rel> On Sun, 26 Jun 2005 16:32:08 -0400 Kent Johnson wrote: > > From: Don Parris > > To: Danny Yoo > > Subject: Re: [Tutor] Alternative File I/O for Tuples > > > > I guess I'm asking two closely-related questions: > > (1) how to format the file so it can be readable, and > > If you like the recipe I posted, this could be as simple as > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(...appropriate args to indent...)) > mbrPhone.close() > > Kent > > _______________________________________________ Kent, Just getting back to this - Mondays are always hectic. This recipe is the one I saw and like. It looks cool! In my brief efforts tinkering with it, I am not really getting very far. I saved the recipe, and import it into the file containing all my database functions. In one of the functions, I have the following: I used the "from tbl_Tabs import *" approach to import the recipe. If I should be doing this differently, just say so. for record in Results: print '%-15s\t%-15s\t%-15s' % record # I still want to print to screen, then... mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(record, hasHeader=False, separateRows=True)) mbrPhone.close() I first assumed that "record", and then "Results" could be substituted for "rows", per the recipe. I also tried "rows", and assigning "record", and then "Results" to "rows". O.k., you can laugh all you want. I tried playing with the various arguments, and found that to be of little value. The traceback refers to a type error: iteration over a non-sequence. The query returns a tuple, as I understand it. I also understand a tuple to be a sequence. If this is really as simple as the 3 lines you pointed out above, I know I'm missing something in the implementation. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From magoldfish at gmail.com Tue Jun 28 06:58:41 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Tue, 28 Jun 2005 00:58:41 -0400 Subject: [Tutor] super() and inherited attributes? Message-ID: <5e183f3d050627215822acba6c@mail.gmail.com> Hi, The following example doesn't work as I would like-- the child instance doesn't expose the attribute set in the parent. Can someone point out what I am missing? Thanks, Marcus class Parent(object): def __init__(self, name="I am a parent"): self.name = name class Child(Parent): def __init__(self, number): super(Parent, self).__init__("I am a child") self.number = number # I would like it to produce the following: >> c = Child(23) >> c.number 23 >> c.name "I am a child" # but I 'AttributeError: 'Child' object has no attribute 'name'' From webdev at matheteuo.org Tue Jun 28 07:16:54 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 28 Jun 2005 01:16:54 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42BF10C8.4070003@tds.net> References: <42BF10C8.4070003@tds.net> Message-ID: <20050628011654.1b778bee@luke.matheteuo.rel> On Sun, 26 Jun 2005 16:32:08 -0400 Kent Johnson wrote: > > From: Don Parris > > To: Danny Yoo > > Subject: Re: [Tutor] Alternative File I/O for Tuples > > > > I guess I'm asking two closely-related questions: > > (1) how to format the file so it can be readable, and > > If you like the recipe I posted, this could be as simple as > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(...appropriate args to indent...)) > mbrPhone.close() > > Kent > > _______________________________________________ I tried this also: print 'Phone List' for rows in Results: mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, prefix='| ', postfix=' |')) I suspect this is closer to what I need to use. I still get a non-sequence error on the traceback, though. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From bvande at po-box.mcgill.ca Tue Jun 28 07:44:29 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 28 Jun 2005 01:44:29 -0400 Subject: [Tutor] super() and inherited attributes? In-Reply-To: <5e183f3d050627215822acba6c@mail.gmail.com> References: <5e183f3d050627215822acba6c@mail.gmail.com> Message-ID: <42C0E3BD.3000709@po-box.mcgill.ca> Marcus Goldfish said unto the world upon 28/06/2005 00:58: > Hi, > > The following example doesn't work as I would like-- the child > instance doesn't expose the attribute set in the parent. Can someone > point out what I am missing? > > Thanks, > Marcus > > > class Parent(object): > def __init__(self, name="I am a parent"): > self.name = name > > class Child(Parent): > def __init__(self, number): > super(Parent, self).__init__("I am a child") > self.number = number > > # I would like it to produce the following: > >>>c = Child(23) >>>c.number > > 23 > >>>c.name > > "I am a child" > > # but I 'AttributeError: 'Child' object has no attribute 'name'' Hi Marcus, Try it this way: >>> class Parent(object): def __init__(self, name="I am a parent"): self.name = name >>> class Child(Parent): def __init__(self, number): # Note change here in super() super(Child, self).__init__("Finally, I'm a child!") self.number = number >>> c = Child(42) >>> c.number 42 >>> c.name "Finally, I'm a child!" Take a look at these classes, and perhaps they will help clear up any residual puzzlement. >>> class A(object): def do_it(self): print "From A" >>> class B(A): def do_it(self): print "From B" >>> class C(B): def do_it(self): # look for do_it in B's superclass (i.e. A) super(B, self).do_it() # look for do_it in C's superclass (i.e. B) super(C, self).do_it() >>> c = C() >>> c.do_it() From A From B >>> HTH, Brian vdB From chinook.nr at tds.net Tue Jun 28 08:16:59 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 02:16:59 -0400 Subject: [Tutor] OO refactoring trial ?? Message-ID: <0001HW.BEE6639B001C87DBF00FF3B0@smtp.tds.net> OO refactoring trial ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) and if the decorators help with such. 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): if tv == 'relates to A': return True else: return False def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): if tv == 'relates to B': return True else: return False def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From alan.gauld at freenet.co.uk Tue Jun 28 09:48:09 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 28 Jun 2005 08:48:09 +0100 Subject: [Tutor] super() and inherited attributes? References: <5e183f3d050627215822acba6c@mail.gmail.com> Message-ID: <02ab01c57bb5$ba7fc580$a89f8851@xp> |class Parent(object): | def __init__(self, name="I am a parent"): | self.name = name | |class Child(Parent): | def __init__(self, number): | super(Parent, self).__init__("I am a child") | self.number = number | |# I would like it to produce the following: |>> c = Child(23) |>> c.name |"I am a child" I don't know the direct answer but the more common way of doing that in Python is not to use super() but just call the inherited constructor directly: Parent.__init__(self,'I am a child') SO if you just want to fix the itch use that, if you want to understand super() then that won't help and its over to someone else! :-) HTH, Alan G From jfouhy at paradise.net.nz Tue Jun 28 10:07:30 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 28 Jun 2005 20:07:30 +1200 (NZST) Subject: [Tutor] super() and inherited attributes? In-Reply-To: <02ab01c57bb5$ba7fc580$a89f8851@xp> References: <5e183f3d050627215822acba6c@mail.gmail.com> <02ab01c57bb5$ba7fc580$a89f8851@xp> Message-ID: <1119946050.42c1054236934@www.paradise.net.nz> Quoting Alan G : > I don't know the direct answer but the more common way > of doing that in Python is not to use super() but just > call the inherited constructor directly: > > Parent.__init__(self,'I am a child') > > > SO if you just want to fix the itch use that, if you want > to understand super() then that won't help and its over to > someone else! :-) OTOH, there are reasons for prefering super over a direct call. This explains it better than I could: http://www.python.org/2.2.3/descrintro.html#cooperation -- John. From kent37 at tds.net Tue Jun 28 11:50:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Jun 2005 05:50:54 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <20050628010920.62cf8f6d@luke.matheteuo.rel> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> Message-ID: <42C11D7E.8010605@tds.net> Don Parris wrote: > Just getting back to this - Mondays are always hectic. This recipe is the > one I saw and like. It looks cool! In my brief efforts tinkering with it, > I am not really getting very far. I saved the recipe, and import it into > the file containing all my database functions. In one of the > functions, I have the following: > > I used the "from tbl_Tabs import *" approach to import the recipe. If I > should be doing this differently, just say so. > > for record in Results: > print '%-15s\t%-15s\t%-15s' % record > # I still want to print to screen, then... > > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(record, hasHeader=False, separateRows=True)) > mbrPhone.close() The problem is you are just passing one record to indent(). It processes the whole table at once so you have to pass the list of records, i.e. mbrPhone.write(indent(Results, hasHeader=False, separateRows=True)) and do this outside the loop or you will write the file once for every record. So your code should look like this: for record in Results: print '%-15s\t%-15s\t%-15s' % record # I still want to print to screen, then... # Notice different indent from your code mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(Results, hasHeader=False, separateRows=True)) mbrPhone.close() > > I first assumed that "record", and then "Results" could be substituted for > "rows", per the recipe. I also tried "rows", and assigning "record", and > then "Results" to "rows". O.k., you can laugh all you want. I tried > playing with the various arguments, and found that to be of little value. > > The traceback refers to a type error: iteration over a non-sequence. The > query returns a tuple, as I understand it. I also understand a tuple to be > a sequence. If this is really as simple as the 3 lines you pointed out > above, I know I'm missing something in the implementation. Yes, a tuple is a sequence. If you still get an error with the code above, please post the exact error message and traceback (copy / paste from the output), there is a lot of useful information in it that can be lost if you paraphrase. Kent From chinook.nr at tds.net Tue Jun 28 13:31:43 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:31:43 -0400 Subject: [Tutor] OO refactoring trial ?? Message-ID: <0001HW.BEE6AC5F00035045F0407550@news.gmane.org> [[ This message was both posted and mailed: see the 'To' and 'Newsgroups' headers for details. ]] Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the "testit" methods will all be quite different as you might imagine (as will the "doit" methods). 2) A final subclass will always return True, so there will always be a valid factory (?) result. ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how I might improve it 2) The implications of using this in a recursive approach (referenced from but outside the recursive function). 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From chinook.nr at tds.net Tue Jun 28 13:39:59 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:39:59 -0400 Subject: [Tutor] OO refactoring trial ?? Message-ID: <0001HW.BEE6AF4F0004008BF00FF3B0@smtp.tds.net> Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the "testit" methods will all be quite different as you might imagine (as will the "doit" methods). 2) A final subclass will always return True, so there will always be a valid result. ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how it might be improved 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From chinook.nr at tds.net Tue Jun 28 13:49:17 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:49:17 -0400 Subject: [Tutor] OO refactoring trial ?? References: <0001HW.BEE6AC5F00035045F0407550@news.gmane.org> Message-ID: <0001HW.BEE6B17D00048355F0407550@news.gmane.org> On Tue, 28 Jun 2005 07:31:43 -0400, Chinook wrote (in article <0001HW.BEE6AC5F00035045F0407550 at news.gmane.org>): > [[ This message was both posted and mailed: see > the 'To' and 'Newsgroups' headers for details. ]] > Sorry for the duplication. I'm trying Hogwasher on OS X and it seems I better look around some more. From webdev at matheteuo.org Tue Jun 28 18:26:38 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 28 Jun 2005 12:26:38 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42C11D7E.8010605@tds.net> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> Message-ID: <20050628122638.146f772c@luke.matheteuo.rel> On Tue, 28 Jun 2005 05:50:54 -0400 Kent Johnson wrote: > Don Parris wrote: > > Just getting back to this - Mondays are always hectic. This recipe is > > the one I saw and like. It looks cool! In my brief efforts tinkering > > with it, I am not really getting very far. I saved the recipe, and > > import it into the file containing all my database functions. In one of > > the functions, I have the following: > > > > I used the "from tbl_Tabs import *" approach to import the recipe. If I > > should be doing this differently, just say so. > > > > for record in Results: > > print '%-15s\t%-15s\t%-15s' % record > > # I still want to print to screen, then... > > > > mbrPhone = open('mbrPhone.txt', 'w') > > mbrPhone.write(indent(record, hasHeader=False, > > separateRows=True)) mbrPhone.close() > > The problem is you are just passing one record to indent(). It processes > the whole table at once so you have to pass the list of records, i.e. > mbrPhone.write(indent(Results, hasHeader=False, > separateRows=True)) > > and do this outside the loop or you will write the file once for every > record. So your code should look like this: > > for record in Results: > print '%-15s\t%-15s\t%-15s' % record > # I still want to print to screen, then... > > # Notice different indent from your code > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(Results, hasHeader=False, separateRows=True)) > mbrPhone.close() > O.k., I'm curious about the indentation issue here. There is only one file, and it has the correct information - looking at it from a text editor. Is my version overwriting the file every time it iterates then? You'll get a laugh out of this, because when I was playing with sending the file to the printer, I did not dedent the printer call, and it did try to print a copy of the file for each record. Needless to say, I learned the command "lprm" Saturday! I caught onto the indentation, which fixed that. However, I did not pay attention to the code above - probably because I don't have 50-something files named mbrPhone*.txt. Go ahead and laugh, I did! > > > > I first assumed that "record", and then "Results" could be substituted > > for"rows", per the recipe. I also tried "rows", and assigning "record", > > and then "Results" to "rows". O.k., you can laugh all you want. I > > tried playing with the various arguments, and found that to be of little > > value. > > > > The traceback refers to a type error: iteration over a non-sequence. > > The query returns a tuple, as I understand it. I also understand a > > tuple to be a sequence. If this is really as simple as the 3 lines you > > pointed out above, I know I'm missing something in the implementation. > > Yes, a tuple is a sequence. If you still get an error with the code above, > please post the exact error message and traceback (copy / paste from the > output), there is a lot of useful information in it that can be lost if > you paraphrase. > > Kent > O.k., Here we go. Global name "rows" is not defined. My guess is that "rows" needs to know that it should be holding "Results", but maybe it should already know that. I tried to say rows = Results, but that did not help. This seems to come back to the difficulty I have with passing arguments around. ### Revised Code ### print 'Phone List' for record in Results: print '%-15s\t%-15s\t%-15s' % record # rows = Results did not work mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, prefix='| ', postfix=' |')) mbrPhone.close() ### Traceback ### Traceback (most recent call last): File "ekklesia.py", line 165, in ? Main() File "ekklesia.py", line 160, in Main RunMenu(Menu_Main) File "ekklesia.py", line 31, in RunMenu if len(MenuList[sel]) == 3: MenuList[sel][1](MenuList[sel][2]) File "ekklesia.py", line 32, in RunMenu else: MenuList[sel][1]() File "/home/donp/python/ekklesia/ekklesia_db.py", line 61, in mbr_Phone mbrPhone.write(indent(rows, hasHeader=False, separateRows=False,\ NameError: global name 'rows' is not defined BTW, I really appreciate your patience and willingness to help me understand this. If I had ever dreamed that I would have a desire to program 20 years after the fact, I would have stopped passing notes in Math class. I do it well, but hate it. Yet, I find myself drawn further and further into the code, actually wanting to know more about it - why it does what it does. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From nlhughes at gmail.com Sun Jun 26 19:36:55 2005 From: nlhughes at gmail.com (Nathan Hughes) Date: Sun, 26 Jun 2005 18:36:55 +0100 Subject: [Tutor] html scrapeing Message-ID: <9d62808b050626103628de269f@mail.gmail.com> Hi, Ive been looking for way to scrape the data from a html table, but dont know even where to start, or how to do.. an example can be found here of the table ( http://www.dragon256.plus.com/timer.html ) - i'd like to extract all the data except for the delete column and then just print each row.. Can anyone help ? Tnx. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050626/547f8eaf/attachment.htm From tegmine at gmail.com Tue Jun 28 21:25:49 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 28 Jun 2005 12:25:49 -0700 Subject: [Tutor] slicing nested lists/dicts/tuples Message-ID: <77bfa81a05062812253d94b102@mail.gmail.com> Hi, >>> l [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}] This is how I imagine it: for i in l: for j in l[i]: for k in l[i][j]: print k.get('first') print k.get('last') Is there a short and sweet way of doing this (that actually works). Luis. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050628/7b564469/attachment.htm From bvande at po-box.mcgill.ca Tue Jun 28 22:14:05 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 28 Jun 2005 16:14:05 -0400 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <77bfa81a05062812253d94b102@mail.gmail.com> References: <77bfa81a05062812253d94b102@mail.gmail.com> Message-ID: <42C1AF8D.6070701@po-box.mcgill.ca> Luis N said unto the world upon 28/06/2005 15:25: > Hi, > > >>>>l > > [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last': > 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}] > > > This is how I imagine it: > > for i in l: > for j in l[i]: > for k in l[i][j]: > print k.get('first') > print k.get('last') > > Is there a short and sweet way of doing this (that actually works). > > Luis. Hi Luis, I'm not certain I see what you are wanting from your description. (You've got more nesting in your loops than in l.) But does this do what is wanted? >>> a_list = [ {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'} ] >>> for a_dict in a_list: print a_dict['first'] print a_dict['last'] Foo Bar Foo Bar Foo Bar Foo Bar >>> If it does, why are you doing this? Is it to figure out how to manipulate data structures with Python? If so, good. If you are trying to do real work this way, there is surely a better way. Maybe if you said what you are trying to accomplish, someone could help you find a good way to do it. Best, Brian vdB From albertito_g at hotmail.com Tue Jun 28 22:32:59 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 28 Jun 2005 20:32:59 +0000 Subject: [Tutor] Minesweeper OOT Message-ID: Hey tutors Just want to inform that I'm Out Of Town(OOT) and I haven't had the chance to a PC until this very moment. Sorry I didn't reply to your help, I have just read them and I think I get the idea Thanks to all who helped me and I'll be home next Tuesday (a week from now) and I'll give your codes a try and then if I have a problem I just write you again ;) Best Regards Alberto From reed at intersiege.com Tue Jun 28 22:52:57 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Tue, 28 Jun 2005 16:52:57 -0400 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <77bfa81a05062812253d94b102@mail.gmail.com> References: <77bfa81a05062812253d94b102@mail.gmail.com> Message-ID: <42C1B8A9.9030708@intersiege.com> Luis N wrote: > Hi, > > >>> l > [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, > {'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}] > > > This is how I imagine it: > > for i in l: > for j in l[i]: > for k in l[i][j]: > print k.get('first') > print k.get('last') > > Is there a short and sweet way of doing this (that actually works). > > Luis. strings back: for i in l: x = l[0].values() x.reverse() print " ".join(x) Foo Bar Foo Bar Foo Bar Foo Bar lists back: for i in l: x = l[0].values() x.reverse() print x ['Foo', 'Bar'] ['Foo', 'Bar'] ['Foo', 'Bar'] ['Foo', 'Bar'] ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 From reed at intersiege.com Tue Jun 28 23:02:25 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Tue, 28 Jun 2005 17:02:25 -0400 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <42C1B8A9.9030708@intersiege.com> References: <77bfa81a05062812253d94b102@mail.gmail.com> <42C1B8A9.9030708@intersiege.com> Message-ID: <42C1BAE1.4090403@intersiege.com> Reed L. O'Brien wrote: >Luis N wrote: > > > >>Hi, >> >> >> >>>>>l >>>>> >>>>> >>[{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, >>{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}] >> >> >>This is how I imagine it: >> >>for i in l: >> for j in l[i]: >> for k in l[i][j]: >> print k.get('first') >> print k.get('last') >> >>Is there a short and sweet way of doing this (that actually works). >> >>Luis. >> >> > > >strings back: > >for i in l: > x = l[0].values() > x.reverse() > print " ".join(x) > >Foo Bar >Foo Bar >Foo Bar >Foo Bar > >lists back: > >for i in l: > x = l[0].values() > x.reverse() > print x > > >['Foo', 'Bar'] >['Foo', 'Bar'] >['Foo', 'Bar'] >['Foo', 'Bar'] > >~r > > > > I take that back now that I read it it is returning only the first one 4 times oops ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 From chuck at freshsources.com Wed Jun 29 01:10:08 2005 From: chuck at freshsources.com (Chuck Allison) Date: Tue, 28 Jun 2005 17:10:08 -0600 Subject: [Tutor] Interesting problem In-Reply-To: <42BB1DCF.4030303@tds.net> References: <42BB1DCF.4030303@tds.net> Message-ID: <42C1D8D0.3090403@freshsources.com> I may be missing something, but isn't this what __dict__ does? Just return self.__dict__. This is an old message, so this may have mentioned already. Sorry if that's the case. I'm a little behind. Kent Johnson wrote: >Smith, Jeff wrote: > > >>Here would be the usage: >> >>myinst = MyClass() >>print myinst.getprops_as_dict() >> >>would print >> >>{'var1': 1, 'var2': 2, 'var3': 3} >> >>Needless to say I want the instance values which might be different for >>each instance. I know that I could code it brute force, but I want to >>be able to add properties without having to remember to update >>getprops_as_dict(). >> >> > >OK, so will a variation on my last recipe work? This looks for property attributes of the class and gets the corresponding property on the instance: > def getprops_as_dict(self): > return dict(pname, getattr(self, pname) > for pname in dir(self.__class__) > if isinstance(getattr(self.__class__, pname), property)) > ) > >Kent > > > >>For those who are interested, the dictionary created by >>getprops_as_dict() will be fed to string.Template.substitute >> >>Jeff >> >> > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From denise.hartley at gmail.com Wed Jun 29 02:49:53 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 28 Jun 2005 17:49:53 -0700 Subject: [Tutor] Cookielib - CookieJar objects Message-ID: <8daabe5605062817492e3cc74@mail.gmail.com> Hi everyone! Just a quick question about cookie jars: when I create a myjar = cookielib.CookieJar(), and go to a website to get the particular cookie, I get something like this in return: or, if I do print myjar, this: ]> . Now, if I wanted to pull out just the value from the cookie (i.e., "B" in this particular case, labelled as "cookie info" in the print statement and 'value=' in the cookiejar instance), how could I do that? I have tried looking through the documentation and its examples, tried __doc__ and help() and dir() and can't find it. Perhaps I'm just missing something, but does anyone know? Thanks! ~Denise From cyresse at gmail.com Wed Jun 29 03:17:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 29 Jun 2005 13:17:30 +1200 Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: <8daabe5605062817492e3cc74@mail.gmail.com> References: <8daabe5605062817492e3cc74@mail.gmail.com> Message-ID: Hi Denise, Have you tried 'print myjar.value'? Regards, Liam Clarke On 6/29/05, D. Hartley wrote: > > Hi everyone! Just a quick question about cookie jars: > > when I create a myjar = cookielib.CookieJar(), and go to a website to > get the particular cookie, I get something like this in return: > > port=None, port_specified=False, domain='.pythonchallenge.com', > domain_specified=True, domain_initial_dot=True, path='/', > path_specified=True, secure=False, expires=1120610689, discard=False, > comment=None, comment_url=None, rest={})]> > > or, if I do print myjar, this: for .pythonchallenge.com/>]> . > > Now, if I wanted to pull out just the value from the cookie (i.e., "B" > in this particular case, labelled as "cookie info" in the print > statement and 'value=' in the cookiejar instance), how could I do > that? > > I have tried looking through the documentation and its examples, tried > __doc__ and help() and dir() and can't find it. Perhaps I'm just > missing something, but does anyone know? > > Thanks! > > ~Denise > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050629/14a73193/attachment.htm From peter at rt.sk Wed Jun 29 18:39:11 2005 From: peter at rt.sk (Peter Szinek) Date: Wed, 29 Jun 2005 18:39:11 +0200 Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: References: <8daabe5605062817492e3cc74@mail.gmail.com> Message-ID: <42C2CEAF.1090809@rt.sk> Hello Denise, How about this: myjar = cookielib.CookieJar() for cookie in myjar: print cookie.value In this case the above code should print a single 'B'. HTH, Peter Liam Clarke wrote: > Hi Denise, > > Have you tried 'print myjar.value'? > > Regards, > > Liam Clarke > On 6/29/05, *D. Hartley* > wrote: > > Hi everyone! Just a quick question about cookie jars: > > when I create a myjar = cookielib.CookieJar(), and go to a website to > get the particular cookie, I get something like this in return: > > port=None, port_specified=False, domain='.pythonchallenge.com', > domain_specified=True, domain_initial_dot=True, path='/', > path_specified=True, secure=False, expires=1120610689, discard=False, > comment=None, comment_url=None, rest={})]> > > or, if I do print myjar, this: for .pythonchallenge.com/>]> . > > Now, if I wanted to pull out just the value from the cookie ( i.e., "B" > in this particular case, labelled as "cookie info" in the print > statement and 'value=' in the cookiejar instance), how could I do > that? > > I have tried looking through the documentation and its examples, tried > __doc__ and help() and dir() and can't find it. Perhaps I'm just > missing something, but does anyone know? > > Thanks! > > ~Denise > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Jun 29 08:21:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Jun 2005 23:21:49 -0700 (PDT) Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: <42C2CEAF.1090809@rt.sk> Message-ID: On Wed, 29 Jun 2005, Peter Szinek wrote: > Hello Denise, > > How about this: > > myjar = cookielib.CookieJar() > for cookie in myjar: > print cookie.value > > In this case the above code should print a single 'B'. Yes, whenever the documentation talks about something being "iterable", they really mean that we can use a for loop across it. It does seem a little odd that this appears to be a primary way to access the cookies in a cookie jar: http://www.python.org/doc/lib/node534.html I wonder why; I haven't been able to figure out a good reason for this kind of interface. Are cookie jars files known to be large? I do hope it's not a matter of preserving the metaphor of reaching into a cookie jar to grab cookies one at a time... *grin* From kent37 at tds.net Wed Jun 29 12:22:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Jun 2005 06:22:53 -0400 Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: References: Message-ID: <42C2767D.8090609@tds.net> Danny Yoo wrote: > Yes, whenever the documentation talks about something being "iterable", > they really mean that we can use a for loop across it. It does seem a > little odd that this appears to be a primary way to access the cookies in > a cookie jar: > > http://www.python.org/doc/lib/node534.html > > I wonder why; I haven't been able to figure out a good reason for this > kind of interface. Are cookie jars files known to be large? I was perplexed by this too when I did the challenge Denise is on. Your question prompted a look at the cookielib source. It turns out that iterating over the CookieJar is actually doing a recursive tree walk of the contents of the CookieJar. This only pushes the mystery one step back, though - the attribute of the Cookie that is recursively iterated is called 'item', but the Cookie class defined in cookielib has no attribute 'item'. Take a look at cookielib.deepvalues() if you are curious. Kent From kent37 at tds.net Wed Jun 29 12:38:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Jun 2005 06:38:36 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <20050628122638.146f772c@luke.matheteuo.rel> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> Message-ID: <42C27A2C.4050801@tds.net> Don Parris wrote: > On Tue, 28 Jun 2005 05:50:54 -0400 > Kent Johnson wrote: >>The problem is you are just passing one record to indent(). It processes >>the whole table at once so you have to pass the list of records, i.e. >> mbrPhone.write(indent(Results, hasHeader=False, >> separateRows=True)) >> >>and do this outside the loop or you will write the file once for every >>record. So your code should look like this: >> >> for record in Results: >> print '%-15s\t%-15s\t%-15s' % record >># I still want to print to screen, then... >> >> # Notice different indent from your code >> mbrPhone = open('mbrPhone.txt', 'w') >> mbrPhone.write(indent(Results, hasHeader=False, separateRows=True)) >> mbrPhone.close() >> > > > O.k., I'm curious about the indentation issue here. Python uses indentation to show the scope of a block - how much code is inside a loop or conditional. For example if I write for i in range(3): print i print 'Done' the output is 0 Done 1 Done 2 Done The two print statements are both indented under the for statement so they are both part of the loop set up by the for statement. OTOH if I say for i in range(3): print i print 'Done' the output is 0 1 2 Done because the second print is at the same indentation as the for so it is not included in the loop. This section of the tutorial talks a little about indenting: http://docs.python.org/tut/node5.html#SECTION005200000000000000000 > There is only one file, > and it has the correct information - looking at it from a text editor. Is > my version overwriting the file every time it iterates then? Yes, exactly. > Here we go. Global name "rows" is not defined. My guess is that "rows" > needs to know that it should be holding "Results", but maybe it should > already know that. I tried to say rows = Results, but that did not help. > This seems to come back to the difficulty I have with passing arguments > around. > > ### Revised Code ### > print 'Phone List' > for record in Results: > print '%-15s\t%-15s\t%-15s' % record > # rows = Results did not work > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, > prefix='| ', postfix=' |')) > mbrPhone.close() 'Global name "rows" is not defined means that Python doesn't know what 'rows' means - you haven't assigned any value to that name. I'm surprised your code didn't work when you add the line "rows = Results" as indicated above; what error do you get then? But a simpler way is just to use Results in the call to indent: mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, prefix='| ', postfix=' |')) What happens if you try that? > BTW, I really appreciate your patience and willingness to help me understand > this. No problem, that's what we do here. At least on a good day :-) > If I had ever dreamed that I would have a desire to program 20 years > after the fact, I would have stopped passing notes in Math class. I do it > well, but hate it. Yet, I find myself drawn further and further into the > code, actually wanting to know more about it - why it does what it does. I don't know about the 'hating it' part, but you are certainly not alone in finding yourself fascinated with programming in Python. But snakes can do that, can't they? We are all trapped by its hypnotic stare... ;-) BTW have you found a tutorial you like? There are many free Python tutorials, take a look at this page: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From webdev at matheteuo.org Wed Jun 29 18:24:41 2005 From: webdev at matheteuo.org (Don Parris) Date: Wed, 29 Jun 2005 12:24:41 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42C27A2C.4050801@tds.net> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> Message-ID: <20050629122441.4cfc92f1@luke.matheteuo.rel> On Wed, 29 Jun 2005 06:38:36 -0400 Kent Johnson wrote: > Don Parris wrote: > > On Tue, 28 Jun 2005 05:50:54 -0400 > > Kent Johnson wrote: Thanks for the explanation of indentation! I kind of understood that, but wanted to be sure I understood correctly what was happening with the text file inside the for loop. And if that sounds a little loopy, well... :) > > 'Global name "rows" is not defined means that Python doesn't know what > 'rows' means - you haven't assigned any value to that name. I'm surprised > your code didn't work when you add the line "rows = Results" as indicated > above; what error do you get then? But a simpler way is just to use > Results in the call to indent: > > mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, > prefix='| ', postfix=' |')) > > What happens if you try that? > Well this is kind of instructive. Assigning rows = Results and using Results as an argument to indent() produce the same traceback message. I was right that the "rows" argument needed the value of "Results", so I *am* learning something. However, it seems that the function doesn't like the value I give it. ### Using Results as the argument to indent() ### Traceback (most recent call last): File "ekklesia.py", line 165, in ? Main() File "ekklesia.py", line 160, in Main RunMenu(Menu_Main) File "ekklesia.py", line 31, in RunMenu if len(MenuList[sel]) == 3: MenuList[sel][1](MenuList[sel][2]) File "ekklesia.py", line 32, in RunMenu else: MenuList[sel][1]() File "/home/donp/python/ekklesia/ekklesia_db.py", line 63, in mbr_Phone prefix='| ', postfix=' |')) File "/home/donp/python/ekklesia/tbl_Tabs.py", line 24, in indent logicalRows = [rowWrapper(row) for row in rows] File "/home/donp/python/ekklesia/tbl_Tabs.py", line 21, in rowWrapper newRows = [wrapfunc(item).split('\n') for item in row] AttributeError: 'NoneType' object has no attribute 'split' ### end traceback ### My SQL query functions return a tuple, so indent() has to recognize that much. I suspected this has to do with the wrapfunc argument. I had dropped it at some point, thinking that would help me grasp the problem. I fed it rows(using the rows= Results at the moment), and got this traceback: ### revised function call and traceback ### mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, prefix='| ', postfix=' |'))wrapfunc=lambda x:wrap_onspace(rows, 12)) Traceback (most recent call last): File "ekklesia.py", line 9, in ? from ekklesia_db import * File "/home/donp/python/ekklesia/ekklesia_db.py", line 64 mbrPhone.close() ^ SyntaxError: invalid syntax ### end function call and traceback ### mbrPhone.close() is properly indented. I even put the whole indent() call on one single line. So now I'm not sure where to go. I know that error messages can sometimes be misleading. I also know that close() takes exactly 0 arguments. So maybe I need to look back at indent()? > > BTW, I really appreciate your patience and willingness to help me > > understand this. > > No problem, that's what we do here. At least on a good day :-) > > > If I had ever dreamed that I would have a desire to program 20 years > > after the fact, I would have stopped passing notes in Math class. I do > > it well, but hate it. Yet, I find myself drawn further and further into > > the code, actually wanting to know more about it - why it does what it > > does. > > I don't know about the 'hating it' part, but you are certainly not alone > in finding yourself fascinated with programming in Python. But snakes can > do that, can't they? We are all trapped by its hypnotic stare... ;-) > You bet! > BTW have you found a tutorial you like? There are many free Python > tutorials, take a look at this page: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > I've read the Python tutorial, Alan's tutorial, and have worked through some of the others as well. It looks simple enough, but when I try things out for myself, I find it difficult to see how the examples apply in my situation. Which is why I sought out this list. My Guess is that I need to "just do it" for a while before it'll come to me. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From kent37 at tds.net Wed Jun 29 18:37:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Jun 2005 12:37:45 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <20050629122441.4cfc92f1@luke.matheteuo.rel> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> <20050629122441.4cfc92f1@luke.matheteuo.rel> Message-ID: <42C2CE59.3040703@tds.net> Don Parris wrote: > On Wed, 29 Jun 2005 06:38:36 -0400 > Kent Johnson wrote: >>Don Parris wrote: > However, it seems that the function doesn't like the > value I give it. > > ### Using Results as the argument to indent() ### > Traceback (most recent call last): > File "ekklesia.py", line 165, in ? > Main() > File "ekklesia.py", line 160, in Main > RunMenu(Menu_Main) > File "ekklesia.py", line 31, in RunMenu > if len(MenuList[sel]) == 3: MenuList[sel][1](MenuList[sel][2]) > File "ekklesia.py", line 32, in RunMenu > else: MenuList[sel][1]() > File "/home/donp/python/ekklesia/ekklesia_db.py", line 63, in mbr_Phone > prefix='| ', postfix=' |')) > File "/home/donp/python/ekklesia/tbl_Tabs.py", line 24, in indent > logicalRows = [rowWrapper(row) for row in rows] > File "/home/donp/python/ekklesia/tbl_Tabs.py", line 21, in rowWrapper > newRows = [wrapfunc(item).split('\n') for item in row] > AttributeError: 'NoneType' object has no attribute 'split' > ### end traceback ### > > My SQL query functions return a tuple, so indent() has to recognize that > much. This is a tough one to interpret. The value being returned from wrapfunc() is expected to be a string, but instead it is None. Calling None.split() generates the AttributeError. Looking at wrapfunc, in defaults to an identity function that just returns its argument. So it looks like the tuples you get back from MySQL have None values in them which is confusing indent(). Try with wrapfunc=lambda x: x or '' which will convert None to an empty string, or wrapfunc=lambda x: str(x) which will convert None to the string 'None' > I suspected this has to do with the wrapfunc argument. I had dropped > it at some point, thinking that would help me grasp the problem. I fed it > rows(using the rows= Results at the moment), and got this traceback: > > ### revised function call and traceback ### > mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, > prefix='| ', postfix=' |'))wrapfunc=lambda > x:wrap_onspace(rows, 12)) Take another look at the line above, the commas and parens aren't right. > I've read the Python tutorial, Alan's tutorial, and have worked through some > of the others as well. It looks simple enough, but when I try things out > for myself, I find it difficult to see how the examples apply in my > situation. Which is why I sought out this list. My Guess is that I need to > "just do it" for a while before it'll come to me. "just doing it" is critical. Learning to program is like learning to write or learning a foreign language. It just can't be done by reading about it; the only way to learn is to do it. One thing to try is to just type in examples from a tutorial. Then think of variations on the example; try them out. Play with it, whatever crazy idea you have is good. This will give you experience with the basics and also some experience with error messages! When you become more comfortable with the basics you should start to see how they fit together to make useful programs. Just in the snippets we are working on we have touched on looping, file I/O and function calls which should be topics in any tutorial. Kent From webdev at matheteuo.org Wed Jun 29 19:31:03 2005 From: webdev at matheteuo.org (Don Parris) Date: Wed, 29 Jun 2005 13:31:03 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42C2CE59.3040703@tds.net> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> <20050629122441.4cfc92f1@luke.matheteuo.rel> <42C2CE59.3040703@tds.net> Message-ID: <20050629133103.5116a3b7@luke.matheteuo.rel> On Wed, 29 Jun 2005 12:37:45 -0400 Kent Johnson wrote: > Don Parris wrote: > > On Wed, 29 Jun 2005 06:38:36 -0400 > > Kent Johnson wrote: > >>Don Parris wrote: > > This is a tough one to interpret. The value being returned from wrapfunc() > is expected to be a string, but instead it is None. Calling None.split() > generates the AttributeError. > > Looking at wrapfunc, in defaults to an identity function that just returns > its argument. So it looks like the tuples you get back from MySQL have > None values in them which is confusing indent(). > > Try with > wrapfunc=lambda x: x or '' > which will convert None to an empty string, or > wrapfunc=lambda x: str(x) > which will convert None to the string 'None' > > > I suspected this has to do with the wrapfunc argument. I had dropped > > it at some point, thinking that would help me grasp the problem. I fed > > it rows(using the rows= Results at the moment), and got this traceback: > > > > ### revised function call and traceback ### > > mbrPhone.write(indent(rows, hasHeader=False, separateRows=False, > > prefix='| ', postfix=' > > |'))wrapfunc=lambda x:wrap_onspace(rows, > > 12)) > > Take another look at the line above, the commas and parens aren't right. > That was my own copy/paste error in the e-mail. It doesn't look that way in my code. My bad. ### playing with wrapfunc (all other args are the same) ### wrapfunc=lambda x:wrap_onspace(str(rows), x)) also wrapfunc=lambda x:str(wrap_onspace(rows, x))) both generate the same error: Traceback (most recent call last): File "ekklesia.py", line 9, in ? from ekklesia_db import * #Comment out this line if MySQL not installed. File "/home/donp/python/ekklesia/ekklesia_db.py", line 64 mbrPhone.close() ^ SyntaxError: invalid syntax > > I've read the Python tutorial, Alan's tutorial, and have worked through > > some of the others as well. It looks simple enough, but when I try > > things out for myself, I find it difficult to see how the examples apply > > in my situation. Which is why I sought out this list. My Guess is that > > I need to"just do it" for a while before it'll come to me. > > "just doing it" is critical. Learning to program is like learning to write > or learning a foreign language. It just can't be done by reading about it; > the only way to learn is to do it. One thing to try is to just type in > examples from a tutorial. Then think of variations on the example; try > them out. Play with it, whatever crazy idea you have is good. This will > give you experience with the basics and also some experience with error > messages! > I realize that I'm kind of putting the cart before the horse here - trying to accomplish a real program without understanding the tools well. I also feel like I should play around more with other code (the recipes and Python programs already available). I also think I should spend a little time doing the line-by-line analysis of code in the snippets/programs above to be sure I understand what I'm reading in the tutorials. So, aside from trying to jump to step #10 from step #1, I think I'm doing fairly well. :) > When you become more comfortable with the basics you should start to see > how they fit together to make useful programs. Just in the snippets we are > working on we have touched on looping, file I/O and function calls which > should be topics in any tutorial. > > Kent > I'll get there. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From kent37 at tds.net Wed Jun 29 20:09:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Jun 2005 14:09:41 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <20050629133103.5116a3b7@luke.matheteuo.rel> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> <20050629122441.4cfc92f1@luke.matheteuo.rel> <42C2CE59.3040703@tds.net> <20050629133103.5116a3b7@luke.matheteuo.rel> Message-ID: <42C2E3E5.3070200@tds.net> Don Parris wrote: > ### playing with wrapfunc (all other args are the same) ### > wrapfunc=lambda x:wrap_onspace(str(rows), x)) > > also > wrapfunc=lambda x:str(wrap_onspace(rows, x))) This is way off base. wrap_onspace takes two arguments - the string to wrap, and the width to wrap to. You are passing it two arguments - the tuple of tuples to print, and the string to wrap. > > both generate the same error: > Traceback (most recent call last): > File "ekklesia.py", line 9, in ? > from ekklesia_db import * #Comment out this line if MySQL not > installed. File "/home/donp/python/ekklesia/ekklesia_db.py", line 64 > mbrPhone.close() > ^ > SyntaxError: invalid syntax I can't do anything with this without more context - a few lines of code before the line with the error at least. Kent From denise.hartley at gmail.com Wed Jun 29 20:16:34 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 29 Jun 2005 11:16:34 -0700 Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: <42C2767D.8090609@tds.net> References: <42C2767D.8090609@tds.net> Message-ID: <8daabe56050629111631a433eb@mail.gmail.com> first attempt - myjar has no attribute 'value' second attempt - re: myjar = cookielib.CookieJar() for cookie in myjar: print cookie.value In this case the above code should print a single 'B'. This does work. However, it only ever returns me one value. For instance, the first three are BZh. My code is: def urlsearch(times): x = 12345 count = 0 myjar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar)) while count < times: param = urllib.urlencode({'busynothing': x}) z = opener.open("http://www.pythonchallenge.com/pc/def/linkedlist.php?%s" % param) text = z.read() lister = string.split(text) x = lister[-1] count = count + 1 return myjar Now, if I'm using the jar the way I think I am, I'm creating it outside the while loop, and then when I use the opener within the while loop (to open each successive url), I should be adding a new cookie, right? so that I have a jar full of multiple cookies? But it's acting like it's just *replacing* the old cookie with the new one, because when I'm done with that function, I do: jar6 = urlsearch(2) for cookie in jar6: print cookie.value (2 is number of times) If I do urlsearch(1), I get B for the value (as expected). If I do urlsearch(2), I get Z (and only Z. Not BZ). Ditto urlsearch(3), I get h (and only h, not BZh). Is it truly replacing the old cookie with the new one? That isn't what I want to do, and not how I would think a cookie jar would work. Am I setting it up incorrectly? > > Yes, whenever the documentation talks about something being "iterable", > > they really mean that we can use a for loop across it. This seems perfectly rational to me. However, having the "cookie.value" part used in an actual example would have been very helpful. > > I wonder why; I haven't been able to figure out a good reason for this > > kind of interface. Are cookie jars files known to be large? I assumed that a cookie jar would work kind of like a list. I could add new cookies to it at each step of my while loop, and then iterate over the "list" of cookies to get out the pieces of info I wanted. I'm hoping this is correct, because that's how I *want* to use this cookie jar! > This only pushes the mystery one step back, though - the attribute of the Cookie that is recursively iterated is called 'item', but the Cookie class defined in cookielib has no attribute 'item'. Yeah, it was kind of confusing why it was called an "item" in one version and a "value" in another. But then, most things are confusing to me ;) > Take a look at cookielib.deepvalues() if you are curious. I'm looking at the cookielib page - why can't I find .deepvalues()? It's funny to me, but some of these documentation pages I find exactly what I'm looking for, including examples, and can immediately put it to practical use in my code. Some of the libraries I read a hundred times and can never seem to find what I'm looking for. In any case, if anyone has any ideas why my cookiejar isn't collecting a bunch of cookies but instead only returning the last one, I'd be very grateful! Thanks again for all your help and suggestions. ~Denise From earak at swbell.net Wed Jun 29 18:41:42 2005 From: earak at swbell.net (Tony & Bec Krawczyk) Date: Wed, 29 Jun 2005 11:41:42 -0500 Subject: [Tutor] python/ pygame on XP: window not responding Message-ID: <200506291641.j5TGfhBj203194@pimout5-ext.prodigy.net> I am a new python/ pygame user. In attempting the simple command pygame.display.set_mode((640,480)) The newly created window is not responding. I am using these programs with the Windows XP operating system. Can you provide any suggestions or help with this issue?? Your assistance is greatly appreciated!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050629/d1870aa4/attachment.htm From plc at med.unc.edu Wed Jun 29 21:32:51 2005 From: plc at med.unc.edu (Philip Carl) Date: Wed, 29 Jun 2005 15:32:51 -0400 Subject: [Tutor] Missing methods in string module? Message-ID: <42C2F763.5030702@med.unc.edu> If I check the Python Libray Reference for String Methods (2.3.6.1) I find many methods listed e.g. decode, encode, endswith etc. that do not seem to be listed by the command line dir(string) in Python 2.4 under Windows XP, although many other methods e.g. capitalize and center are. Why is this? Thanks. Philip Carl Associate Professor of Pharmacology 1026A Mary Ellen Jones Bld. CB 7365 University of North Carolina Medical School Chapel Hill, NC 27599 Phone: 919-966-3544 FAX: 919-966-5640 From amonroe at columbus.rr.com Wed Jun 29 23:43:16 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 29 Jun 2005 17:43:16 -0400 Subject: [Tutor] python/ pygame on XP: window not responding In-Reply-To: <200506291641.j5TGfhBj203194@pimout5-ext.prodigy.net> References: <200506291641.j5TGfhBj203194@pimout5-ext.prodigy.net> Message-ID: <826667315.20050629174316@columbus.rr.com> > I am a new python/ pygame user. In attempting the simple > command pygame.display.set_mode((640,480)) > The newly created window is not responding. I am using these programs with > the Windows XP operating system. Can you provide any suggestions or help > with this issue?? Does the chimp.py example from pygame run on your box? I'm betting you're just not processing the event queue, so the OS thinks the app is hung. Alan From bvande at po-box.mcgill.ca Thu Jun 30 03:16:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 29 Jun 2005 21:16:45 -0400 Subject: [Tutor] Missing methods in string module? In-Reply-To: <42C2F763.5030702@med.unc.edu> References: <42C2F763.5030702@med.unc.edu> Message-ID: <42C347FD.5040001@po-box.mcgill.ca> Philip Carl said unto the world upon 29/06/2005 15:32: > If I check the Python Libray Reference for String Methods (2.3.6.1) I > find many methods listed e.g. decode, encode, endswith etc. that do not > seem to be listed by the command line dir(string) in Python 2.4 under > Windows XP, although many other methods e.g. capitalize and center are. > Why is this? Thanks. > > Philip Carl Hi Philip, dir(string) reports on the string module, not string methods. See the snip below; if that doesn't clear it up for you, ask again. Best, Brian vdB PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> dir(string) Traceback (most recent call last): File "", line 1, in ? NameError: name 'string' is not defined >>> dir('an actual string') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> import string >>> dir(string) ['Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] >>> From webdev at matheteuo.org Thu Jun 30 07:23:27 2005 From: webdev at matheteuo.org (Don Parris) Date: Thu, 30 Jun 2005 01:23:27 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <42C2E3E5.3070200@tds.net> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> <20050629122441.4cfc92f1@luke.matheteuo.rel> <42C2CE59.3040703@tds.net> <20050629133103.5116a3b7@luke.matheteuo.rel> <42C2E3E5.3070200@tds.net> Message-ID: <20050630012327.31d47cda@luke.matheteuo.rel> On Wed, 29 Jun 2005 14:09:41 -0400 Kent Johnson wrote: > Don Parris wrote: > > ### playing with wrapfunc (all other args are the same) ### > > wrapfunc=lambda x:wrap_onspace(str(rows), x)) > > > > also > > wrapfunc=lambda x:str(wrap_onspace(rows, x))) > > This is way off base. wrap_onspace takes two arguments - the string to > wrap, and the width to wrap to. You are passing it two arguments - the > tuple of tuples to print, and the string to wrap. > > > Success!!! mbrPhone = open('mbrPhone.txt', 'w') mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, prefix='', postfix='', justify='left', wrapfunc=lambda x:str(x))) mbrPhone.close() I went back to your e-mail where you told me to use x:str(x) and re-tried that. I must have broken (or re-broken) something, while fixing something else. when I tried your suggestion, it wouldn't work. So I was trying to fix the wrong break. Anyway, it works beautifully- 100% accurate data: James | Austin | 704-111-1234 Janet | Austin | 704-111-1234 James | Austin | 704-111-1234 Julie | Austin | 704-111-1234 Robert | Bates | 704-222-2345 Rachael | Bates | 704-222-2345 Bob | Brown | None David | Carter | 704-111-2345 That's just a sample of the complete file. And thanks for not giving up on me! Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From tomcloyd at bestmindhealth.com Thu Jun 30 11:43:09 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Thu, 30 Jun 2005 02:43:09 -0700 Subject: [Tutor] mscvrt module question Message-ID: Executing within Komodo 3.1, running python 2.4.1, it appears that when running my source file, python knows kbhit(), but not getch(). How can this be? KeyIn = getch() File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 1799, in runMain self.dbg.runfile(debug_args[0], debug_args) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 1524, in runfile h_execfile(file, args, module=main, tracer=self) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 590, in __init__ execfile(file, globals, locals) File "C:\Documents and Settings\Tom C\My Documents\Python projects - Toms\quiz\quiz.py", line 13, in __main__ KeyIn = getch() NameError: name 'getch' is not defined Also, the interpreter know neither. I don't get it -- a=kbhit() Traceback (most recent call last): [snip] File "", line 0, in __main__ NameError: name 'defined' is not defined I don't know how to fix this, so any suggestions would be much appreciated. -- t. ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From feziwe at sanbi.ac.za Thu Jun 30 14:32:17 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Thu, 30 Jun 2005 14:32:17 +0200 Subject: [Tutor] HANDLING ERRORS Message-ID: <42C3E650.30300@sanbi.ac.za> HI help mi. here's what i tried but it's not working print "Type Control C or -1 to exit" def print_menu(): print '1. Print Phone Numbers' print '2. Add a Phone Number' print '3. Remove a Phone Number' print '4. Lookup a Phone Number' print '5. Quit' print numbers = {} menu_choice = 0 print_menu() while menu_choice != 5: try: menu_choice = input("Type in a number (1-5):") if menu_choice == 1: print "Telephone Numbers:" for x in numbers.keys(): print "Name: ",x," \tNumber: ",numbers[x] print except ValueError: print "Oops! That was no valid number. Try again..." elif menu_choice == 2: print "Add Name and Number" name = raw_input("Name:") phone = raw_input("Number:") numbers[name] = phone elif menu_choice == 3: print "Remove Name and Number" name = raw_input("Name:") if numbers.has_key(name): del numbers[name] else: print name," was not found" elif menu_choice == 4: print "Lookup Number" name = raw_input("Name:") if numbers.has_key(name): print "The number is",numbers[name] else: print name," was not found" elif menu_choice != 5: print_menu() From light_zls at 163.com Thu Jun 30 13:36:48 2005 From: light_zls at 163.com (Light) Date: Thu, 30 Jun 2005 19:36:48 +0800 Subject: [Tutor] HANDLING ERRORS In-Reply-To: <42C3E650.30300@sanbi.ac.za> References: <42C3E650.30300@sanbi.ac.za> Message-ID: <200506301936.48397.light_zls@163.com> HI Move the "except ..." outside the "if...". Try this one: print "Type Control C or -1 to exit" def print_menu(): print '1. Print Phone Numbers' print '2. Add a Phone Number' print '3. Remove a Phone Number' print '4. Lookup a Phone Number' print '5. Quit' print numbers = {} menu_choice = 0 print_menu() while menu_choice != 5: try: menu_choice = input("Type in a number (1-5):") if menu_choice == 1: print "Telephone Numbers:" for x in numbers.keys(): print "Name: ",x," \tNumber: ",numbers[x] print elif menu_choice == 2: print "Add Name and Number" name = raw_input("Name:") phone = raw_input("Number:") numbers[name] = phone elif menu_choice == 3: print "Remove Name and Number" name = raw_input("Name:") if numbers.has_key(name): del numbers[name] else: print name," was not found" elif menu_choice == 4: print "Lookup Number" name = raw_input("Name:") if numbers.has_key(name): print "The number is",numbers[name] else: print name," was not found" elif menu_choice != 5: print_menu() except ValueError: print "Oops! That was no valid number. ?Try again..." From adam.jtm30 at gmail.com Thu Jun 30 14:04:03 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 30 Jun 2005 13:04:03 +0100 Subject: [Tutor] wxPython shaped window In-Reply-To: References: Message-ID: On 6/26/05, Adam Cripps wrote: > > On 6/25/05, Adam Bark wrote: > > Thanks for the info Adam I just seem to be having a problem with the > panel > > size it greys out nearly all the image. Ideally I would like to make the > > > panel transparent but I can't work out how to do that. > > > > > > On 6/25/05, Adam Cripps wrote: > > > On 6/25/05, Adam Bark < adam.jtm30 at gmail.com > wrote: > > > > Is it possible to put controls into a shaped window in wxPython. I > have > > > > tried putting a button on the demo and it becomes the exact size and > > > shape > > > > of the window. Also when I tried to bind it to an action it wouldn't > > even > > > > start. > > > > > > > > Adam > > > > > > > > > > I'm working through something similar myself at the moment. > > > > > > Try adding a wx.Panel to the frame and then the button to the panel. > > > You can position them through pos parameter, but it should default to > > > the top left of the panel and have a good size if you use > > > button.SetSize(button.GetBestSize()) > > > > > > HTH > > > > > > Adam > > Adam - how much code do you have? Why not post it either here or the > wxpython-users list (to which I'm also subscribed) and we can take a > look. > > Adam > > -- > http://www.monkeez.org > PGP key: 0x7111B833 I tried posting to the wxpython-users list but I'm not sure it worked nobody replied anyway. Here's my test script: import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Shaped Window", style = wx.FRAME_SHAPED | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP ) self.hasShape = False self.delta = (0,0) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.bkground = wx.Bitmap("/home/adam/bkgrnd.gif", wx.BITMAP_TYPE_GIF) w, h = self.bkground.GetWidth(), self.bkground.GetHeight() self.SetClientSize((w, h)) self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape) panel = Panel(self, w, h) panel.Show() dc = wx.ClientDC(self) dc.DrawBitmap(self.bkground, 0,0, True) def SetWindowShape(self, evt): # Use the bitmap's mask to determine the region r = wx.RegionFromBitmap(self.bkground) self.hasShape = self.SetShape(r) def OnPaint(self, event): dc = wx.PaintDC(self) dc.DrawBitmap(self.bkground, 0,0, True) def OnMouseMove(self, evt): if evt.Dragging() and evt.LeftIsDown(): x, y = self.ClientToScreen(evt.GetPosition()) fp = (x - self.delta[0], y - self.delta[1]) self.Move(fp) class Panel(wx.Panel): def __init__(self, parent, width, height): wx.Panel.__init__(self, parent, -1, size=(width, height)) button = wx.Button(self, -1, "hello") button.SetSize(button.GetBestSize()) self.SetSize((width, height)) #print dir(self) if __name__ == "__main__": app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() Thanks. Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050630/14dd80c5/attachment.htm From kent37 at tds.net Thu Jun 30 15:10:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Jun 2005 09:10:22 -0400 Subject: [Tutor] Cookielib - CookieJar objects In-Reply-To: <8daabe56050629111631a433eb@mail.gmail.com> References: <42C2767D.8090609@tds.net> <8daabe56050629111631a433eb@mail.gmail.com> Message-ID: <42C3EF3E.60409@tds.net> D. Hartley wrote: > This does work. However, it only ever returns me one value. For > instance, the first three are BZh. My code is: > > def urlsearch(times): > x = 12345 > count = 0 > myjar = cookielib.CookieJar() > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar)) > while count < times: > param = urllib.urlencode({'busynothing': x}) > z = opener.open("http://www.pythonchallenge.com/pc/def/linkedlist.php?%s" > % param) > text = z.read() > lister = string.split(text) > x = lister[-1] > count = count + 1 > return myjar > > Now, if I'm using the jar the way I think I am, I'm creating it > outside the while loop, and then when I use the opener within the > while loop (to open each successive url), I should be adding a new > cookie, right? so that I have a jar full of multiple cookies? But it's > acting like it's just *replacing* the old cookie with the new one, The *server* is reusing the same cookie for each URL, so it replaces the cookie in the cookiejar with a new cookie. > Is it truly replacing the old cookie with the new one? That isn't what > I want to do, and not how I would think a cookie jar would work. Am I > setting it up incorrectly? Read the cookie data inside the loop and use a list to accumulate the values, instead of relying on the cookiejar to accumulate the values. >>Take a look at cookielib.deepvalues() if you are curious. > > > I'm looking at the cookielib page - why can't I find .deepvalues()? It's an implementation detail - you have to look at the source code in Python24\Lib\cookielib.py > It's funny to me, but some of these documentation pages I find exactly > what I'm looking for, including examples, and can immediately put it > to practical use in my code. Some of the libraries I read a hundred > times and can never seem to find what I'm looking for. Sometimes it helps to look at the source code for the module. Many library modules are written in Python and the source is easily available in Python24\Lib (on Windows, the path is different on Linux). Kent From kent37 at tds.net Thu Jun 30 15:11:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Jun 2005 09:11:35 -0400 Subject: [Tutor] html scrapeing In-Reply-To: <9d62808b050626103628de269f@mail.gmail.com> References: <9d62808b050626103628de269f@mail.gmail.com> Message-ID: <42C3EF87.8030109@tds.net> Nathan Hughes wrote: > Hi, > > Ive been looking for way to scrape the data from a html table, but dont > know even where to start, or how to do.. Take a look at Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ Kent From hugonz-lists at h-lab.net Thu Jun 30 16:06:49 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 30 Jun 2005 09:06:49 -0500 Subject: [Tutor] Directory notification Message-ID: <42C3FC79.2020406@h-lab.net> Hi all, I was writing a daemon to continuously check for changes in a directory and then process the new files, I was polling every X seconds, but I decided I should give dnotify a try in Python. Here is my test program, I just want to share it with others on the list, as it is a very nice way to watch a directory as polling is ugly (it is Linux specific, though) ========== #!/usr/bin/env python # This checks the implementation for dnotify, uses fcntl and signals import signal from fcntl import * import os #set event handler for SIGIO, otherwise the program will terminate signal.signal(signal.SIGIO, lambda signum, stack:None) # Configure fcntl for a directory # wanted: DN_MODIFY DN_CREATE DN_ATTRIB DN_DELETE DN_RENAME DN_MULTISHOT dnot_dir = "/var/data/in" # builtin open() will refuse to open a directory(!) filep = os.open(dnot_dir, os.O_RDONLY) while True: # register the service fcntl(filep, F_NOTIFY, DN_MODIFY|DN_CREATE|DN_ATTRIB|DN_DELETE|DN_RENAME) # block until signal is received signal.pause() print "EVENT!" ================= From fant at pobox.com Thu Jun 30 18:23:42 2005 From: fant at pobox.com (Andrew D. Fant) Date: Thu, 30 Jun 2005 12:23:42 -0400 Subject: [Tutor] Unix User Adminstration Scripts Message-ID: <42C41C8E.7080803@pobox.com> I'm in the planning stages of writing a program to manage user accounts on some unix boxes that cannot be directly hooked into our central account management system at work. Obviously, the heavy lifting can be done with shell calls to the underlying commands or via direct edits of the relevant files. Is there a more pythonic interface for this, and/or does anyone have any pointers to sample code that demonstrates such an interface? Thanks, Andy From cpu.crazy at gmail.com Thu Jun 30 21:26:14 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 30 Jun 2005 13:26:14 -0600 Subject: [Tutor] Jimage reader. How to find the pixels? In-Reply-To: <09e501c57038$8a1700d0$c7a58851@xp> References: <42AC2362.1070709@gmail.com> <09e501c57038$8a1700d0$c7a58851@xp> Message-ID: <66ca60fc050630122610f8a20c@mail.gmail.com> I've been looking a lot for a mod that will automatically find the pixels in an image but I can't find one. Do you know of one? imageop and imghdr don't have anything like that. Thanks, Joe From alan.gauld at freenet.co.uk Thu Jun 30 22:21:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 30 Jun 2005 21:21:52 +0100 Subject: [Tutor] mscvrt module question References: Message-ID: <002001c57db1$5aa91140$e8a08851@xp> > File "C:\Documents and Settings\Tom C\My Documents\Python projects - > Toms\quiz\quiz.py", line 13, in __main__ > KeyIn = getch() > NameError: name 'getch' is not defined > Have you actually imported the msvcrt module? And if so did you import kbhit and getch since you aren't prefixing the names with the module? Normally I'd expect to see Keyln = msvcrt.getch() > a=kbhit() > > Traceback (most recent call last): > [snip] > File "", line 0, in __main__ > NameError: name 'defined' is not defined That looks more like you tried to execute an error message by mistake! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jun 30 22:25:57 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 30 Jun 2005 21:25:57 +0100 Subject: [Tutor] HANDLING ERRORS References: <42C3E650.30300@sanbi.ac.za> Message-ID: <003201c57db1$ed20f290$e8a08851@xp> > numbers = {} > menu_choice = 0 > print_menu() > while menu_choice != 5: > > try: > > menu_choice = input("Type in a number (1-5):") > if menu_choice == 1: > print "Telephone Numbers:" .... > > except ValueError: > print "Oops! That was no valid number. Try again..." The except should align with the 'try' not the 'if' Does that help? Otherwise you need to give us a clue as to how it doesn't work. Do you get an error message? What happens? Alan G From dyoo at hkn.eecs.berkeley.edu Thu Jun 30 22:51:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 30 Jun 2005 13:51:39 -0700 (PDT) Subject: [Tutor] Jimage reader. How to find the pixels? In-Reply-To: <66ca60fc050630122610f8a20c@mail.gmail.com> Message-ID: On Thu, 30 Jun 2005, Joseph Quigley wrote: > I've been looking a lot for a mod that will automatically find the > pixels in an image but I can't find one. Do you know of one? imageop and > imghdr don't have anything like that. Thanks, Hi Joseph, You might want to try the Python Imaging Library; it's a toolkit for doing imaging manipulation, and I'm sure it has support for pixel manipulation. Here's the url to it: http://www.pythonware.com/products/pil/ Best of wishes! From john.ertl at fnmoc.navy.mil Thu Jun 30 23:32:24 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Thu, 30 Jun 2005 14:32:24 -0700 Subject: [Tutor] would pickle or cpickle help? Message-ID: All, I have a text file that contains several thousand lines of space delimited text that contain a ship ID and a ship name. This file is updated every few months. I have another file that contains the ship ID and some other info but not the ship name. I have to append the ship name to the end of the line. Easy enough. I currently make a dictionary of the shipID(key) and ship name(value) and use this to append the ship name to the end of the line that contains the ship ID. Could I use something like cpickle to store the dictionary once it is made so I would not have to make it each time? I have never tried to use pickle so I am bit fuzzy on what it can store and what it can't. Also would it really buy me anything...it only takes a second or two to make the dictionary? There is a chance the file that I use to make the dictionary will eventually grow to be 10,000 lines or more. Thanks for the ideas. John Ertl From ghost04 at mwr.is Wed Jun 29 22:06:10 2005 From: ghost04 at mwr.is (Jimmy) Date: Wed, 29 Jun 2005 20:06:10 -0000 Subject: [Tutor] {Possible Spam?} Need help new to Programming Message-ID: <200506292002.j5TK1xw5008247@mwr.mwr.is> My project right now is "Write another program that reads 100 numbers from the user and prints out the sum" Now I can get the program to do these functions, but it won't stop even using the break statement. Any help or guidance would be great. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050629/93bd4e03/attachment.htm From bgailer at sbcglobal.net Thu Jun 30 04:49:18 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 29 Jun 2005 19:49:18 -0700 Subject: [Tutor] html scrapeing In-Reply-To: <9d62808b050626103628de269f@mail.gmail.com> References: <9d62808b050626103628de269f@mail.gmail.com> Message-ID: <6.1.2.0.0.20050629194217.0286c940@pop.sbcglobal.yahoo.com> At 10:36 AM 6/26/2005, Nathan Hughes wrote: >Ive been looking for way to scrape the data from a html table, but dont >know even where to start, or how to do.. > >an example can be found here of the table ( >http://www.dragon256.plus.com/timer.html >) - i'd like to extract all the data except for the delete column and then >just print each row.. Use module urllib2 for obtaining the page source: import urllib2 page = urllib2.urlopen("http://www.dragon256.plus.com/timer.html") html = page.readlines() You now have a list of lines. Now you can use any number of string parsing tools to locate lines starting with to find each new row, then to find each cell, then search past the tag(s) to find the cell text. You have 3 cases to deal with: Glastonbury 2005 BBC THREE Is that enough to get you started? Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050629/71d52573/attachment.htm