From alan.gauld at freenet.co.uk Wed Feb 1 00:29:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Jan 2006 23:29:06 -0000 Subject: [Tutor] Newbie question re. Functions References: <43DF780D.8070004@alum.rpi.edu> Message-ID: <054a01c626be$2186ec50$0b01a8c0@xp> > So a general recommendation to authors is to have a member of the target > audience "test" the book. You Jon have done that but at some cost to you > and those of us on this list. One advantage of doing my book as a web site first was that I had plenty of testers before committing to print (over 100k visitors). Mind you the paper version still had plenty of mistakes but mostly those were typos... Alan G. From jonathan.r.moore at gmail.com Wed Feb 1 01:09:37 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 1 Feb 2006 00:09:37 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: References: Message-ID: Danny Many thanks for that, I notice a few erratas that I am yet to come up against. This will save my sanity (well some of it)1 Jon On 31/01/06, Danny Yoo wrote: > > > > On Tue, 31 Jan 2006, Jon Moore wrote: > > > I have been looking for contact details for the author to ask him what > > he was eluding to with the exercise, but to no avail. > > Hi Jon, > > I did find errata here: > > > http://www.muskalipman.com/ptr_detail.cfm?group=Programming&all=1&isbn=1-59200-073-8 > > (bottom of the page) > > but as far as contact information, I haven't been able to find anything. > I do agree the challenege exercise as you've put it seems somewhat > nonsensical. *grin* > > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/88431513/attachment.html From jonathan.r.moore at gmail.com Wed Feb 1 01:13:29 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 1 Feb 2006 00:13:29 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: <054a01c626be$2186ec50$0b01a8c0@xp> References: <43DF780D.8070004@alum.rpi.edu> <054a01c626be$2186ec50$0b01a8c0@xp> Message-ID: Alan Are you the author of Learn to Program Using Python: A Tutorial for Hobbyists, Self-starters and All Who Want to Learn the Art of Computer Programming? Is the book still available as a web site? Jon On 31/01/06, Alan Gauld wrote: > > > So a general recommendation to authors is to have a member of the target > > audience "test" the book. You Jon have done that but at some cost to you > > and those of us on this list. > > One advantage of doing my book as a web site first was that I had plenty > of testers before committing to print (over 100k visitors). Mind you the > paper > version still had plenty of mistakes but mostly those were typos... > > > Alan G. > > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/011a981e/attachment.htm From carbonnb at sympatico.ca Wed Feb 1 01:24:36 2006 From: carbonnb at sympatico.ca (Bryan Carbonnell) Date: Tue, 31 Jan 2006 19:24:36 -0500 Subject: [Tutor] Getting Running File's Name In-Reply-To: <4677730601310017ybb519d0k60245799813d2cc8@mail.gmail.com> References: <5667508E43F1B740BCFA57FF46E35300032D51E7@nav-akl-exch-c.newton.navman.com> Message-ID: On 31 Jan 2006 at 9:17, Rinzwind wrote: > Why would that be any different under Linux? > > sys.argv[0] > On 1/31/06, Hans Dushanthakumar wrote: > > Under WinXP, the variable > > sys.argv[0] holds the script file name (including the path). Not sure, Wim/Hans, Thank you both. It worked perfectly. -- Bryan Carbonnell - carbonnb at sympatico.ca If you lend someone $20, and never see that person again, it was probably worth it. From alan.gauld at freenet.co.uk Wed Feb 1 06:09:21 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 1 Feb 2006 05:09:21 -0000 Subject: [Tutor] Newbie question re. Functions References: <43DF780D.8070004@alum.rpi.edu> <054a01c626be$2186ec50$0b01a8c0@xp> Message-ID: <000901c626ed$a9746500$0b01a8c0@xp> > Are you the author of Learn to Program Using Python: A Tutorial for > Hobbyists, Self-starters and All Who Want to Learn the Art of Computer > Programming? Yes. > Is the book still available as a web site? Yes. It has been substantially rewritten sionce the book was done to cover more recent features of Python. But the basic structure and content is still the same. The book has 3 chapters whose copyright belongs to Addison Wesley and thus are not on the web site but OTOH the web site has several topics which were written after the book was published.... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ewald.ertl at hartter.com Wed Feb 1 10:34:28 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 01 Feb 2006 10:34:28 +0100 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> Message-ID: <43E080A4.5080500@hartter.com> Hi! I made a copy of the source you posted. I just got a problem as expected when doing the session.login() because the access-data is invalid. The connection via the smtplib.SMTP() could be established. Perhaps there is something wrong with your namelookup. Can you try a call in the interactive environment for socket.gethostname() or socket.gethostbyname( socket.gethostname() ) Can you resolve the hostname "smtp.mail.yahoo.com" on a commandline? e.g. nslookup smtp.mail.yahoo.com ? Hope this can help you Ewald Intercodes wrote: > > Hello everyone, > > I am working with a registration system for my website in mod_python. I > needed to send mail to registered users for confirmation. Since I can't > use my ISP's smtp server, I used yahoo's smtp server and my yahoo > username and password to connect and send mail using this script (see > below). But I get the following error. > > "Traceback (most recent call last): > File "mail.py", line 12, in ? > session = smtplib.SMTP(smtpserver) > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > addr = socket.gethostbyname(socket.gethostname()) > socket.gaierror: (-2, 'Name or service not known') > " > > I got this script from some website I can't remember and just changed > some values to get it to work. Is is possible to send mail like this? Is > there any other easy way to do this? > > Thanks for your time. > --------------------------- > > import smtplib > > smtpserver = 'smtp.mail.yahoo.com ' > AUTHREQUIRED = 1 > smtpuser = > 'intercodes at .[snip]..' // > smtppass = '[snip]' > > RECIPIENTS = ['intercodes@[snip]'] > SENDER = 'intercodes@[snip]' > mssg = "mod python" > > session = smtplib.SMTP(smtpserver) > *if* AUTHREQUIRED: > session.login(smtpuser, smtppass) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)** > > > -- > Intercodes > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From intercodes at gmail.com Wed Feb 1 10:55:04 2006 From: intercodes at gmail.com (Intercodes) Date: Wed, 1 Feb 2006 15:25:04 +0530 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <43E080A4.5080500@hartter.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> Message-ID: <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> Ewald, First off, thanks for stopping by. >The connection via the smtplib.SMTP() could be established. > I dont think so. I think it fails before the login(). ------------------------------------------------------ >>> ex=smtplib.SMTP('smtp.mail.yahoo.com') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/smtplib.py", line 241, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.4/smtplib.py", line 289, in connect for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): socket.gaierror: (-2, 'Name or service not known') ------------------------------------------------ >>> socket.gethostname() 'linux' --------------------------------------------- >>> socket.gethostbyname(socket.gethostname()) Traceback (most recent call last): File "", line 1, in ? socket.gaierror: (-2, 'Name or service not known') >>> -------------------------------------------------- linux:/srv/www/htdocs/konnect # nslookup smtp.mail.yahoo.com Server: 203.145.184.13 Address: 203.145.184.13#53 Non-authoritative answer: smtp.mail.yahoo.com canonical name = smtp.plus.mail.yahoo.com. smtp.plus.mail.yahoo.com canonical name = smtp.plus.mail.yahoo4.akadns.net. Name: smtp.plus.mail.yahoo4.akadns.net Address: 216.136.173.18 ----------------------------------------------------- Thank you, ------ Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/d9538e41/attachment.htm From ewald.ertl at hartter.com Wed Feb 1 11:27:22 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 01 Feb 2006 11:27:22 +0100 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> Message-ID: <43E08D0A.4070309@hartter.com> Hi! Intercodes wrote: > Ewald, > > First off, thanks for stopping by. > > >The connection via the smtplib.SMTP() could be established. > > > I dont think so. I think it fails before the login(). > > ------------------------------------------------------ >>>> ex= smtplib.SMTP('smtp.mail.yahoo.com ') > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/smtplib.py", line 241, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/lib/python2.4/smtplib.py", line 289, in connect > for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): > socket.gaierror: (-2, 'Name or service not known') > > ------------------------------------------------ Here you get a different Traceback than in the original post. After digging in smtplib.py here ( Python 2.3.3 ) the call should be socket.getaddrinfo( "smtp.mail.yahoo.com", 25, 0, socket.SOCK_STREAM ); which succeeds here at my installation. How do you resolve your hostnames ( /etc/nsswitch.conf gives the order of hostname resolution ) > >>> socket.gethostname() > 'linux' > --------------------------------------------- > >>>> socket.gethostbyname(socket.gethostname()) > Traceback (most recent call last): > File "", line 1, in ? > socket.gaierror: (-2, 'Name or service not known') >>>> > -------------------------------------------------- This should resolve your own local hostname! The socket.gethostbyname() is a call into a shared object of Python and this would use ( So think I ) the standard-Libraries for resolution. Is "linux" a valid hostname? Does "ping linux" succeed. I still think, that this a name resolution error on your host. HTH Ewald From intercodes at gmail.com Wed Feb 1 11:42:17 2006 From: intercodes at gmail.com (Intercodes) Date: Wed, 1 Feb 2006 16:12:17 +0530 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <43E08D0A.4070309@hartter.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> <43E08D0A.4070309@hartter.com> Message-ID: <37e70e3b0602010242o4c0bd764i6672cc1516a6e762@mail.gmail.com> > > Ewald, > > ------------------------------------------------------ > >>>> ex= smtplib.SMTP('smtp.mail.yahoo.com ') > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/usr/lib/python2.4/smtplib.py", line 241, in __init__ > > (code, msg) = self.connect(host, port) > > File "/usr/lib/python2.4/smtplib.py", line 289, in connect > > for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): > > socket.gaierror: (-2, 'Name or service not known') > > > > ------------------------------------------------ > I am sorry , that's a mistake on my part. This output corresponds to a typo input data. The error you saw previously was the original one (the one with error on line 255...). I corrected the typo while posting it ( ..I thought the error was same) ------------------------------------------------------------------ > >the call should be socket.getaddrinfo( "smtp.mail.yahoo.com", 25, 0, > > socket.SOCK_STREAM ); > >>>socket.getaddrinfo('smtp.mail.yahoo.com',25,0,socket.SOCK_STREAM) [(2, 1, 6, '', ('216.136.173.18', 25))] -------------------------------------------------------------- How do you resolve your hostnames ( /etc/nsswitch.conf gives the order of > hostname resolution ) My nssswitch.conf ---------------------------------- passwd: compat group: compat hosts: files dns networks: files dns services: files protocols: files rpc: files ethers: files netmasks: files netgroup: files publickey: files bootparams: files automount: files nis aliases: files --------------------------------------------------------------------------------------------- >This should resolve your own local hostname! > >The socket.gethostbyname() is a call into a shared object of Python and > this >would use ( So think I ) the standard-Libraries for resolution. You totally lost me here :) ----------------------------------------------------------------------------- > >Is "linux" a valid hostname? > >Does "ping linux" succeed. I suppose not. linux:/srv/ # ping linux ping: unknown host linux -------------------------------------------------------------------------------------- -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/260c6ed0/attachment.html From ewald.ertl at hartter.com Wed Feb 1 12:46:59 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 01 Feb 2006 12:46:59 +0100 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <37e70e3b0602010242o4c0bd764i6672cc1516a6e762@mail.gmail.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> <43E08D0A.4070309@hartter.com> <37e70e3b0602010242o4c0bd764i6672cc1516a6e762@mail.gmail.com> Message-ID: <43E09FB3.7060503@hartter.com> Hi! Intercodes wrote: > > My nssswitch.conf > ---------------------------------- > passwd: compat > group: compat > > hosts: files dns > networks: files dns > > services: files > protocols: files > rpc: files > ethers: files > netmasks: files > netgroup: files > publickey: files > > bootparams: files > automount: files nis > aliases: files > > --------------------------------------------------------------------------------------------- > The system looks first in the /etc/hosts-File and when there is no match found, the configured DNS would be requested. > > >This should resolve your own local hostname! > >The socket.gethostbyname () is a call into a shared object of > Python and this >would use ( So think I ) the standard-Libraries for > resolution. > > > You totally lost me here :) > ----------------------------------------------------------------------------- > > > >Is "linux" a valid hostname? > >Does "ping linux" succeed. > > > I suppose not. > > linux:/srv/ # ping linux > ping: unknown host linux > -------------------------------------------------------------------------------------- Here, I think is a strange problem. You can not resolve your own hostname. Is there no entry in /etc/hosts for linux with the IP-Address of your server? If not, try to insert such an entry. HTH Ewald From jonathan.r.moore at gmail.com Wed Feb 1 12:57:05 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 1 Feb 2006 11:57:05 +0000 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) Message-ID: Hi, Ok its the last exercise in the chapter of the python book (Python for the absolute beginner) I am working my way through. I have been learning about functions using a tic-tac-toe game as an example and I understand it fairly clearly, however the author says the following: Write a new computer_move() function for the tic-tac-toe game to plug the hole in the computers stratergy. See if you can create an opponent that is unbeatable! My main problem is that I can not see how the computers stratergy can be improved as at best I can only manage a tie with the computer! If I could see past this, I could hopefully work out the code. Copy of the function: def computer_move(board, computer, human): """Make computer move.""" # make a copy to work with since function will be changing list board = board[:] # the best positions to have, in order BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print "I shall take square number", # if computer can win, take that move for move in legal_moves(board): board[move] = computer if winner(board) == computer: print move return move # done checking this move, undo it board[move] = EMPTY # if human can win, block that move for move in legal_moves(board): board[move] = human if winner(board) == human: print move return move # done checkin this move, undo it board[move] = EMPTY # since no one can win on next move, pick best open square for move in BEST_MOVES: if move in legal_moves(board): print move return move -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/9282a32f/attachment.htm From udnahc at gmail.com Wed Feb 1 14:11:31 2006 From: udnahc at gmail.com (Chandrashekar Jayaraman) Date: Wed, 1 Feb 2006 18:41:31 +0530 Subject: [Tutor] Re : Project Work Message-ID: I m doing a project using Python and Bluetooth . I tried running the sample programs given with the pybluez-0.5 distro with python 2.4 . The socket program s just dont seem to run . However the inquiry.py program run s perfectly. ne solutions ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/938d6235/attachment.html From intercodes at gmail.com Wed Feb 1 14:21:36 2006 From: intercodes at gmail.com (Intercodes) Date: Wed, 1 Feb 2006 18:51:36 +0530 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <43E09FB3.7060503@hartter.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> <43E08D0A.4070309@hartter.com> <37e70e3b0602010242o4c0bd764i6672cc1516a6e762@mail.gmail.com> <43E09FB3.7060503@hartter.com> Message-ID: <37e70e3b0602010521j1785b23fv1811b810d1713f6e@mail.gmail.com> Ewald, > >Here, I think is a strange problem. You can not resolve your own > hostname. > >Is there no entry in /etc/hosts for linux with the IP-Address of your > server? > >If not, try to insert such an entry. > Thanks for all your suggestions. I inserted my IP address for 'linux' into /etc/hosts. Now smtplib.SMTP() works. But the authentication fails. I tried all combinations of user/pass , but no joy. I tried using gmail (smtp.gmail.com), but it too shows some TLS error or something. I ve searched google , but every script that is available for smtplib uses either sendmail or use their own/isp smtp server. None for connecting to yahoo/gmail/hotmail or other servers using authentication. But anyway, ill try hotmail next. (If I can't get this smtp to work, I have to manually send mails to users :p, disastrous. ) Thanks for your time. -- Intercodes -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/cbcb0df2/attachment.htm From kent37 at tds.net Wed Feb 1 14:27:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Feb 2006 08:27:33 -0500 Subject: [Tutor] Re : Project Work In-Reply-To: References: Message-ID: <43E0B745.5060707@tds.net> Chandrashekar Jayaraman wrote: > I m doing a project using Python and Bluetooth . I tried running the > sample programs given with the pybluez-0.5 distro with python 2.4 . The > socket program s just dont seem to run . However the inquiry.py program > run s perfectly. > ne solutions ? "just dont seem to run" is pretty vague. Exactly what did you try? Exactly what happened? If there is an error message or stack trace, copy / paste it into your email and show us. Kent From python at venix.com Wed Feb 1 14:47:10 2006 From: python at venix.com (Python) Date: Wed, 01 Feb 2006 08:47:10 -0500 Subject: [Tutor] smtplib with yahoo smtp server In-Reply-To: <37e70e3b0602010521j1785b23fv1811b810d1713f6e@mail.gmail.com> References: <37e70e3b0601310854h41208b0fi661c39e283699977@mail.gmail.com> <43E080A4.5080500@hartter.com> <37e70e3b0602010155l3823c9cau467c2f7b53d35d1c@mail.gmail.com> <43E08D0A.4070309@hartter.com> <37e70e3b0602010242o4c0bd764i6672cc1516a6e762@mail.gmail.com> <43E09FB3.7060503@hartter.com> <37e70e3b0602010521j1785b23fv1811b810d1713f6e@mail.gmail.com> Message-ID: <1138801630.9677.42.camel@www.venix.com> On Wed, 2006-02-01 at 18:51 +0530, Intercodes wrote: > Received: by wproxy.gmail.com with SMTP id i23so141320wra for > ; Wed, 01 Feb 2006 05:21:36 -0800 (PST) > Received: by 10.65.228.15 with SMTP id f15mr63752qbr; Wed, 01 Feb 2006 > 05:21:36 -0800 (PST) > Received: by 10.65.100.11 with HTTP; Wed, 1 Feb 2006 05:21:36 -0800 > (PST) > Message-ID: > <37e70e3b0602010521j1785b23fv1811b810d1713f6e at mail.gmail.com> Intercodes, you are using a web interface to send your email. Can you get a "normal" (Evolution, Thunderbird, pine, etc.) email client to work on your system. If those do not work, your Python program probably won't work either. The errors you're getting appear to come from system config issues rather than programming errors. -- Lloyd Kvam Venix Corp From singletoned at gmail.com Wed Feb 1 15:14:19 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 1 Feb 2006 14:14:19 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: References: Message-ID: <34bb7f5b0602010614p7faf2f3dl@mail.gmail.com> On 31/01/06, Jon Moore wrote: > Improve the function ask_number() so that the function can be called with a > step value. Make the default value of step 1. > > The function looks like this: > > def ask_number(question, low, high): > """Ask for a number within the range""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response To be honest, this made sense to me. I assumed the author wants you to be able to do the following: ask_number("Give me an even number between 1 and 10", 1, 10, 2) The solution would be: def ask_number(question, low, high, step=1): """Ask for a number within the range""" response = None while response not in range(low, high, step): response = int(raw_input(question)) return response But I definitely agree that he said it very, very badly. Ed From jonathan.r.moore at gmail.com Wed Feb 1 15:38:01 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Wed, 1 Feb 2006 14:38:01 +0000 Subject: [Tutor] Newbie question re. Functions In-Reply-To: <34bb7f5b0602010614p7faf2f3dl@mail.gmail.com> References: <34bb7f5b0602010614p7faf2f3dl@mail.gmail.com> Message-ID: Thats fine, but what differance does it make? I can see no way that it improves the code. I assume later on when the function is called, it should look as follows: move = ask_number("Where will you move? (0-8): ", 0, NUM_SQUARES, 1) Jon On 01/02/06, Ed Singleton wrote: > > On 31/01/06, Jon Moore wrote: > > Improve the function ask_number() so that the function can be called > with a > > step value. Make the default value of step 1. > > > > The function looks like this: > > > > def ask_number(question, low, high): > > """Ask for a number within the range""" > > response = None > > while response not in range(low, high): > > response = int(raw_input(question)) > > return response > > To be honest, this made sense to me. I assumed the author wants you > to be able to do the following: > > ask_number("Give me an even number between 1 and 10", 1, 10, 2) > > The solution would be: > > def ask_number(question, low, high, step=1): > """Ask for a number within the range""" > response = None > while response not in range(low, high, step): > response = int(raw_input(question)) > return response > > But I definitely agree that he said it very, very badly. > > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060201/bc024d76/attachment-0001.html From srini_iyyer_bio at yahoo.com Wed Feb 1 16:58:49 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 1 Feb 2006 07:58:49 -0800 (PST) Subject: [Tutor] mapping problem In-Reply-To: <37e70e3b0602010521j1785b23fv1811b810d1713f6e@mail.gmail.com> Message-ID: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> Dear group, I have a problem in finding a method to solve a problem where I want to walk through a lineage of terms and find group them from right to left. A snippet of the problem is here. The terms in file as tab delim manner. a b c d car a b c f truck a b c d van a b c d SUV a b c f 18-wheeler a b j k boat a b j a submarine a b d a B-747 a b j c cargo-ship a b j p passenger-cruise ship a b a a bicycle a b a b motorcycle Now my question is to enrich members that have identical lineage with different leaf. 'i.e': a b c d - van suv . I have two terms in this path and I am not happy with two. I wish to have more. Then: a b c - car, van, truck, SUV and 18-wheeler (automobiles that travel on road). I am happy with this grouping and I enriched more items if I walk on lienage : (a-b-c) Thus, I want to try to enrich for all 21 K lines of lineages. My question: Is there a way to automate this problem. My idea of doing this: Since this is a tab delim file. I want to read a line with say 5 columns (5 tabs). Search for items with same column item 4 (because leaf items could be unique). If I find a hit, then check if columns 3 and 2 are identical if so create a list. Although this problem is more recursive and time and resource consuming, I cannot think of an easy solution. Would you please suggest a nice and simple method to solve this problem. For people who are into bioinformatics (I know Danny Yoo is a bioinformatician) the question is about GO terms. I parsed OBO file and laid out the term lineages that constitute the OBO-DAG structure. I want to enrich the terms to do an enrichment analysis for a set of terms that I am interested in. Thank you in advance. cheers Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bgailer at alum.rpi.edu Wed Feb 1 20:02:50 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 01 Feb 2006 11:02:50 -0800 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) In-Reply-To: References: Message-ID: <43E105DA.3030101@alum.rpi.edu> Jon Moore wrote: > Hi, > > Ok its the last exercise in the chapter of the python book (Python for > the absolute beginner) I am working my way through. > > I have been learning about functions using a tic-tac-toe game as an > example and I understand it fairly clearly, however the author says > the following: > > Write a new computer_move() function for the tic-tac-toe game to plug > the hole in the computers stratergy. See if you can create an opponent > that is unbeatable! > > My main problem is that I can not see how the computers stratergy can > be improved as at best I can only manage a tie with the computer! See http://ostermiller.org/tictactoeexpert.html. The "bottom line" is "If you know what you are doing, you can't lose at Tic-Tac-Toe. If your opponent knows what they are doing, you can't win at Tic-Tac-Toe. The game is a zero sum game. If both players are playing with an optimal strategy, every game will end in a tie." [snip] From hugonz-lists at h-lab.net Wed Feb 1 21:45:12 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 01 Feb 2006 14:45:12 -0600 Subject: [Tutor] mapping problem In-Reply-To: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> References: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> Message-ID: <43E11DD8.5080605@h-lab.net> What about choosing a native Python data structure for this? A list of attributes comes to mind, as presence of one can be easily tested with if x in attributes: do_something Here's a test: >>> elements= {} >>> elements['boat'] = ['a', 'b', 'j', 'k'] >>> 'a' in elements['boat'] True >>> Then it is just a matter of getting the fiels into the structure, and then recursing through the elements, like this. elements = {} for line in table_fileo: fields = line.split() #get rid of linefeed fields[-1] = fields[-1][:-1] elements[fields[-1]] = fields[:-1] Then you get a dictionary with the last name in the table as key and a list of the other attributes as value. Then, if you want to look for an attribute, just do: for element in elements.items(): if 'j' in element[1]: print element[0] What do you think? Hugo From dyoo at hkn.eecs.berkeley.edu Wed Feb 1 22:05:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Feb 2006 13:05:48 -0800 (PST) Subject: [Tutor] mapping problem In-Reply-To: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> Message-ID: > A snippet of the problem is here. The terms in file as > tab delim manner. [data cut] > Now my question is to enrich members that have identical lineage with > different leaf. 'i.e': a b c d - van suv. Hi Srinivas, You're starting to use the vocabulary of tree data structures here. Let's clarify what you mean by: > I have two terms in this path and I am not happy with two. I wish to > have more. I think you mean "I have two descendent leaves at this point ...", in which case your next statement: > Then: a b c - car, van, truck, SUV and 18-wheeler (automobiles that > travel on road). I am happy with this grouping and I enriched more items > if I walk on lienage : (a-b-c) sounds like traversing up from your current node up to the parent node. In your example, this expands the descendent leaves to include those other elements. > Is there a way to automate this problem. I would strongly recommend not thinking about this as a text file problem, but as a data structure problem. Trying to do this by messing with lines and tabs seems to me like asking to turn a simple problem into a difficult one. The fact that the data that you have is in a text file should be treated as an accident more than anything: nothing binds you to try to solve your problem by slogging through with the original data representation. The problem becomes much clearer if you're dealing with trees: http://en.wikipedia.org/wiki/Tree_data_structure in which case you can use the vocabulary of tree traversal to make the problem very simple. I might be misundestanding what you're sying but it sounds like you're just asking for parent node traversal, which is a fundamental operation on trees. From 3dbernard at gmail.com Wed Feb 1 23:15:31 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 1 Feb 2006 17:15:31 -0500 Subject: [Tutor] Exit a child thread using threading.Thread() object In-Reply-To: <43DFC5C5.1050900@tds.net> References: <61d0e2b40601311153o3e209f30rd1aa16fb220ced69@mail.gmail.com> <43DFC5C5.1050900@tds.net> Message-ID: <61d0e2b40602011415g2869fbbaj6205aff7c24e20a6@mail.gmail.com> Thanks a lot Kent. The exit call would be made from the same thread whose fate is to terminate. Bernard On 1/31/06, Kent Johnson wrote: > Bernard Lebel wrote: > > A quick question. > > > > I have started a child thread using the threading.Thread class. Is > > there any way to cleanly exit the child thread? > > > > What I mean by "cleanly" is for example if you use the > > thread.start_new() function to create a child thread, the function > > running in the child thread can call thread.exit() to terminate the > > thread. > > > > I could not find anything comparable in the Thread object's documentation. > > Both thread.start_new() and threading.Thread wrap a callable object in a > new thread. For start_new(), the callable is a parameter passed to the > function. For threading.Thread, the callable can be passed as an > initialization parameter or by overriding Thread.run(). > > In any case, the thread runs until the wrapped method terminates, either > by a normal function return or by raising an uncaught exception. The > usual way to exit a thread is for the wrapped callable to return (just a > normal function return). > > thread.exit() just raises SystemExit which terminates the callable with > an uncaught exception. You could probably do the same in a Thread by > raising SystemExit explicitly or calling sys.exit() (which raises > SystemExit for you). But just returning normally from the callable is > the usual way to exit a thread from within the thread. > > If you want to stop a thread from another thread it is harder. The > cleanest way to do it is to set a flag that the running thread will > check. There are several recipes in the online cookbook that show how to > do this. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Feb 1 23:48:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Feb 2006 17:48:46 -0500 Subject: [Tutor] mapping problem In-Reply-To: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> References: <20060201155849.8630.qmail@web31613.mail.mud.yahoo.com> Message-ID: <43E13ACE.5020309@tds.net> Srinivas Iyyer wrote: > Dear group, > I have a problem in finding a method to solve a > problem where I want to walk through a lineage of > terms and find group them from right to left. > > A snippet of the problem is here. The terms in file as > tab delim manner. > > a b c d car > a b c f truck > a b c d van > a b c d SUV > a b c f 18-wheeler > a b j k boat > a b j a submarine > a b d a B-747 > a b j c cargo-ship > a b j p passenger-cruise ship > a b a a bicycle > a b a b motorcycle > > > Now my question is to enrich members that have > identical lineage with different leaf. > 'i.e': a b c d - van suv . I have two terms in this > path and I am not happy with two. I wish to have more. > > Then: a b c - car, van, truck, SUV and 18-wheeler > (automobiles that travel on road). I am happy with > this grouping and I enriched more items if I walk on > lienage : (a-b-c) I'm not sure I understand what you want to do, but I think a tree where each internal node is a dict and each leaf node is a list will do what you want. You would end up with something like tree['a']['b']['c']['d'] = ['car', 'van', 'suv'] To find the value for a b c you would traverse the tree to that point, then accumulate all the leaf nodes underneath. OK I guess I feel like writing code, here is a simple implementation. It requires that all the leaves be at the same depth. It's not particularly clever but it works and shows what can be done just by hooking together basic data structures. raw_data = '''a b c d car a b c f truck a b c d van a b c d SUV a b c f 18-wheeler a b j k boat a b j a submarine a b d a B-747 a b j c cargo-ship a b j p passenger-cruise ship a b a a bicycle a b a b motorcycle'''.splitlines() tree = {} # This builds the tree of nested dictionaries with lists as the leaves for line in raw_data: data = line.split(None, 5) keys = data[:4] value = data[4] # This loop makes the dict nodes subtree = tree for key in keys[:-1]: subtree = subtree.setdefault(key, {}) # The last key points to a list, not a dict lastkey = keys[-1] subtree.setdefault(lastkey, []).append(value) def iter_leaves(subtree): ''' Recursive generator that yields all the leaf nodes of subtree ''' if isinstance(subtree, list): # A leaf node yield subtree return for item in subtree.itervalues(): for leaf in iter_leaves(item): yield leaf def get_leaves(*keys): ''' Return a list of all the leaves in the subtree pointed to by *keys ''' subitem = tree for key in keys: subitem = subitem[key] leaves = [] for leaf in iter_leaves(subitem): leaves.extend(leaf) return leaves print get_leaves('a', 'b', 'c', 'd') print get_leaves('a', 'b', 'c') ## prints ['car', 'van', 'SUV'] ['car', 'van', 'SUV', 'truck', '18-wheeler'] Kent > > > Thus, I want to try to enrich for all 21 K lines of > lineages. > > My question: > > Is there a way to automate this problem. > > My idea of doing this: > > Since this is a tab delim file. I want to read a line > with say 5 columns (5 tabs). Search for items with > same column item 4 (because leaf items could be > unique). If I find a hit, then check if columns 3 and > 2 are identical if so create a list. > > Although this problem is more recursive and time and > resource consuming, I cannot think of an easy > solution. > > Would you please suggest a nice and simple method to > solve this problem. > > For people who are into bioinformatics (I know Danny > Yoo is a bioinformatician) the question is about GO > terms. I parsed OBO file and laid out the term > lineages that constitute the OBO-DAG structure. I want > to enrich the terms to do an enrichment analysis for a > set of terms that I am interested in. > > Thank you in advance. > > cheers > Srini > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kp8 at mac.com Thu Feb 2 06:24:54 2006 From: kp8 at mac.com (kevin parks) Date: Thu, 2 Feb 2006 00:24:54 -0500 Subject: [Tutor] printing the random seed? In-Reply-To: References: Message-ID: hi. I am having some fun with python and making multiple runs on an algorhythm and sometimes getting some fun stuff that i would like to be able to reproduce, but there are some random elements in it. I wonder is there a way to see the random seed, and make note of it so that you could then set the seed for a subsequent run to get the same (initially) random results? cheers, kevin (Hi Danny, if you are still here!) From srini_iyyer_bio at yahoo.com Thu Feb 2 06:50:44 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 1 Feb 2006 21:50:44 -0800 (PST) Subject: [Tutor] need to get unique elements out of a 2.5Gb file In-Reply-To: <43E13ACE.5020309@tds.net> Message-ID: <20060202055044.11763.qmail@web34514.mail.mud.yahoo.com> Hi Group, I have a file which is 2.5 Gb., TRIM54 NM_187841.1 GO:0004984 TRIM54 NM_187841.1 GO:0001584 TRIM54 NM_187841.1 GO:0003674 TRIM54 NM_187841.1 GO:0004985 TRIM54 NM_187841.1 GO:0001584 TRIM54 NM_187841.1 GO:0001653 TRIM54 NM_187841.1 GO:0004984 There are many duplicate lines. I wanted to get rid of the duplicates. I chose to parse to get uniqe element. f1 = open('mfile','r') da = f1.read().split('\n') dat = da[:-1] f2 = open('res','w') dset = Set(dat) for i in dset: f2.write(i) f2.write('\n') f2.close() Problem: Python says it cannot hande such a large file. Any ideas please help me. cheers srini __________________________________________________ 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 Thu Feb 2 08:16:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Feb 2006 23:16:50 -0800 (PST) Subject: [Tutor] printing the random seed? In-Reply-To: Message-ID: > I am having some fun with python and making multiple runs on an > algorhythm and sometimes getting some fun stuff that i would like to be > able to reproduce, but there are some random elements in it. I wonder is > there a way to see the random seed, and make note of it so that you > could then set the seed for a subsequent run to get the same (initially) > random results? Hi Kevin, Sure; take a look at the seed() function in the random module. http://www.python.org/doc/lib/module-random.html#l2h-1298 Just set it to some consistant value at the very beginning of your program, and you should then see duplicate results between program runs. You could also probably do something with random.getstate() and random.setstate(), but it's probably a bit simpler just to inject a known seed value into the pseudorandom generator. > (Hi Danny, if you are still here!) *wave wave* Good luck! From kp8 at mac.com Thu Feb 2 08:23:44 2006 From: kp8 at mac.com (kevin parks) Date: Thu, 2 Feb 2006 02:23:44 -0500 Subject: [Tutor] printing the random seed? In-Reply-To: References: Message-ID: Danny (hope you are good!) & co, I see that biz about random.seed()... but in the absence of setting that ... does it just grab a value from the system clock? Is there a way to just let it generate it's usual, known seed... but then observe what that is in case you get an especially good run of data? like i clearly can't just go: zeed = random.seed() print "zeed = ", zeed hmm... cheers, -[kp]-- From dyoo at hkn.eecs.berkeley.edu Thu Feb 2 08:40:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Feb 2006 23:40:04 -0800 (PST) Subject: [Tutor] need to get unique elements out of a 2.5Gb file In-Reply-To: <20060202055044.11763.qmail@web34514.mail.mud.yahoo.com> Message-ID: On Wed, 1 Feb 2006, Srinivas Iyyer wrote: > I have a file which is 2.5 Gb., > [data cut] > > There are many duplicate lines. I wanted to get rid of the duplicates. Hi Srinivas, When we deal with such large files, we do have to be careful and aware of issues like the concept of memory. > I chose to parse to get uniqe element. > > f1 = open('mfile','r') > da = f1.read().split('\n') ^^^^^^^^^^^^^^^^^^^^^ This line is particularly problematic. Your file is 2.5GB, so you must have at least have that much memory. That's already a problem for most typical desktops. But you also need to store roughly 2.5GB as you're building the list of line elements from the whole string we've read from f1.read(). And that just means you've just broken the limits of most 32-bit machines that can't address more than 2**32 MB of memory at once! ###### >>> 2**32 4294967296L >>> 2 * (2.5 * 10**9) ## Rough estimate of memory necessary to do ## what your program needs at that point 5000000000.0 ###### That's the hard limit you're facing here. You must read the file progressively: trying to process it all at once is not going to scale at all. Simpler is something like this: ###### uniqueElements = Set() for line in open('mfile'): uniqueElements.add(line.rstrip()) ###### which tries to accumulate only unique elements, reading the file line by line. However, this approach too has limits. If the number of unique elements exceeds the amount of system memory, this too won't work. (An approach that does work involves using a mergesort along with auxiliary scratch files.) If you really need to get this job done fast, have you considered just using the Unix 'sort' utility? It has a uniqueness flag that you can enable, and it's always a good approach to use tools that already exist rather than write your own. That is, your problem may be solved by the simple shell command: sort -u [somefile] (Alternatively: sort [somefile] | uniq) So I guess my question is: why did you first approached this "unique line" problem with Python? From dyoo at hkn.eecs.berkeley.edu Thu Feb 2 08:44:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Feb 2006 23:44:44 -0800 (PST) Subject: [Tutor] printing the random seed? In-Reply-To: Message-ID: On Thu, 2 Feb 2006, kevin parks wrote: > Danny (hope you are good!) & co, > > I see that biz about random.seed()... but in the absence of setting that > ... does it just grab a value from the system clock? Yes. Here's what the documentation says officially: """current system time is also used to initialize the generator when the module is first imported""" > Is there a way to just let it generate it's usual, known seed... but > then observe what that is in case you get an especially good run of > data? We can call seed() explicitely using system time then when we start using the random module, and if the results are interesting, we report that initial seed value too. That way, by knowing the initial conditions, we can reproduce the results. ###### >>> import time >>> import random >>> >>> t = time.time() >>> >>> random.seed(t) >>> random.random() 0.39026231885512619 >>> random.random() 0.72296902513427053 >>> random.random() 0.48408173490166762 >>> >>> t 1138866167.719857 >>> >>> random.seed(t) >>> random.random() 0.39026231885512619 >>> random.random() 0.72296902513427053 >>> random.random() 0.48408173490166762 ###### From johanpo at googlemail.com Thu Feb 2 09:54:59 2006 From: johanpo at googlemail.com (johan nilsson) Date: Thu, 2 Feb 2006 09:54:59 +0100 Subject: [Tutor] Windows problem with large(?) files Message-ID: <4d7db9340602020054g12c44d3al37f7536594901374@mail.gmail.com> Dear group, I have a few files that contains data in IEEE 754 format. I need to transform them into a csv file, to be able to read these files in another program. Each file has 30000 samples of I and Q. I did develop the attached script. I am sure not the best, but it worked at home on my Linux installation Python 2.4. I was then very confident that it would work also on my work pc (XP with python 2.3). It does not, I get the following error Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "E:\OFDMA_test\iqw.py", line 16, in ? x[i/4]=unpack('f',a[i:i+4])[0] error: unpack str size does not match format apparently the XP box thinks the file is alot shorter, and that can't be as it is the same file from the same media (USB stick). What is going wrong here? /Johan import os from struct import * from scipy import * f=file("c:\\tmp\\FSL_good_SNR\\Last_IQ.iqw",'r') a=f.read() f.close() x=zeros(len(a)/4)+0.0 for i in range (0, len(a),4): x[i/4]=unpack('f',a[i:i+4])[0] y=x[0:len(x)/2-1]+1j*x[len(x)/2:len(x)-1] writer = file("c:\\tmp\\FSL_good_SNR\\IQ.csv", 'w') for item in y: writer.write(repr(real(item))+','+repr(imag(item))+'\n') writer.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060202/3e30a7b0/attachment.html From w.damen at gmail.com Thu Feb 2 09:59:57 2006 From: w.damen at gmail.com (Rinzwind) Date: Thu, 2 Feb 2006 09:59:57 +0100 Subject: [Tutor] need to get unique elements out of a 2.5Gb file In-Reply-To: References: <20060202055044.11763.qmail@web34514.mail.mud.yahoo.com> Message-ID: <4677730602020059q5c75b194y11600465cf1734f4@mail.gmail.com> I'd use a database if I was you. Install for instance MYSQL or MudBase or something like that and (if need be use Python) to insert the lines into the database. Only storing unique lines would be failry easy. Other sollution (with the usage of Python): If you must use Python I'd suggest making new smaller files. How about making files that are named with the 1st letter of each line you find and split your file up into as many parts and your lines start with unique characters. You end up with lots of smaller files that just need to be merged together (could be done with 'cat' I think?) or you could read all those files and toss them back into 1 big file. Something like this: Read the 2,5G masterfile Read lines 1 by 1 Make a new file named "1st char of line founnd".txt if it doesn't exist and add the new line otherwise scan this file and see if the line is not there yet and if not there add it. when done: merge all files. Can't be too hard to pull off ;) From alan.gauld at freenet.co.uk Thu Feb 2 10:15:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 2 Feb 2006 09:15:53 -0000 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) References: <43E105DA.3030101@alum.rpi.edu> Message-ID: <006701c627d9$445eae40$0b01a8c0@xp> Bob, >> Write a new computer_move() function for the tic-tac-toe game to plug >> the hole in the computers stratergy. See if you can create an opponent >> that is unbeatable! >> >> My main problem is that I can not see how the computers stratergy can >> be improved as at best I can only manage a tie with the computer! Does the computer ever go first? Does the computer start with a random location? If yes to the above then the computer can be beaten since the entire course of a Tic-Tac-Toe game (or OXO as we call it in the UK!) depends upon the first move location. If no to the above then, provided the gameplay is OK, I don't know what the author means either. Alan G. From alan.gauld at freenet.co.uk Thu Feb 2 10:32:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 2 Feb 2006 09:32:02 -0000 Subject: [Tutor] need to get unique elements out of a 2.5Gb file References: <20060202055044.11763.qmail@web34514.mail.mud.yahoo.com> Message-ID: <007301c627db$86159400$0b01a8c0@xp> Hi, < I have a file which is 2.5 Gb., > > There are many duplicate lines. I wanted to get rid > of the duplicates. First, can you use uniq which is a standard Unix/Linux OS command? > I chose to parse to get uniqe element. > > f1 = open('mfile','r') > da = f1.read().split('\n') This reads 2.5G of data into memory. Do you have 2.5G of available memory? It then splits it into lines, so why not read the file line by line instead? for da in open('myfile'): stuff here > dat = da[:-1] This creates a copy of the file contents - anbother 2.5GB! if you used da = da[:-1] you would only have one version. However if you read it one line at a time you can go direct to putting it into the Set which means you never reach the 2.5GB size. > f2 = open('res','w') > dset = Set(dat) > for i in dset: > f2.write(i) > f2.write('\n') f2.write(i+'\n') should be slightly faster and with this size of data set that probably is a visible difference! > Problem: Python says it cannot hande such a large > file. Thats probably not a Python issue but an available RAM issue. But your code doesn't need the entire file in RAM so just read one line at a time and avoid the list.. If its still too big you can try batching the operations. Only process half the lines in the file say, then merge the resultant reduced files. The key point is that without resort to much more sophisticated algorithms you must at some point hold the final data set in RAM, if it is too big the program will fail. A final strategy is to sort the file (which can be done - slowly! - in batches and remove duplicate lines afterwards, or even as part of the sort... But if you need to go that far come back for more details. HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Feb 2 11:30:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 Feb 2006 02:30:15 -0800 (PST) Subject: [Tutor] Windows problem with large(?) files In-Reply-To: <4d7db9340602020054g12c44d3al37f7536594901374@mail.gmail.com> Message-ID: On Thu, 2 Feb 2006, johan nilsson wrote: > apparently the XP box thinks the file is alot shorter, and that can't be > as it is the same file from the same media (USB stick). What is going > wrong here? Hi Johan, Is it possible that you need to treat the file as a binary file? It's rare, but very possible that something like: f = open(somefilename,'r') a = f.read() will give you different results on different platforms, because newline translation occurs on the Windows end of things. ("\n" --> "\r\n" or visa versa) So if your file coincidently has bytes with the sequential values: ###### >>> ord('\r'), ord('\n') (13, 10) ###### then we should expect to see those two bytes collapsed down to a single one through the mechanism of newline translation. But if this is happening, there's an easy fix: f = open(somefilename,'rb') a = f.read() where we open the file in binary mode. Good luck! From jonathan.r.moore at gmail.com Thu Feb 2 11:31:05 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 2 Feb 2006 10:31:05 +0000 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) In-Reply-To: <006701c627d9$445eae40$0b01a8c0@xp> References: <43E105DA.3030101@alum.rpi.edu> <006701c627d9$445eae40$0b01a8c0@xp> Message-ID: On 02/02/06, Alan Gauld wrote: > > Bob, > > >> Write a new computer_move() function for the tic-tac-toe game to plug > >> the hole in the computers stratergy. See if you can create an opponent > >> that is unbeatable! > >> > >> My main problem is that I can not see how the computers stratergy can > >> be improved as at best I can only manage a tie with the computer! > > Does the computer ever go first? Yes if you let it! Does the computer start with a random location? No, if you look at the code below, it has a predefined set of 'best moves'. If yes to the above then the computer can be beaten since the entire > course of a Tic-Tac-Toe game (or OXO as we call it in the UK!) > depends upon the first move location. Thanks to Andr?, there is a way to win every time if you take the first move (see below), so there MUST be a whole in the computers stratergy! Based on what we all know about the game, I would say that you can not make it so that the computer can win every time, but it should be possable to make it tie. x: 0 o: 4 x: 7 o: 2 x: 6 If no to the above then, provided the gameplay is OK, I don't know > what the author means either. > > Alan G. > The code is as follows: # set global constants X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 # set game instructions def display_instruct(): """Display game instructions.""" print \ """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ # set question def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response # set ask number def ask_number(question, low, high): """Ask for a number within the range""" response = None while response not in range(low, high): response = int(raw_input(question)) return response # set pieces def pieces(): """Determine if player or computer goes first.""" go_first = ask_yes_no("Do you wish to go first? (y/n): ") if go_first == "y": print "\nThen take the first move. You will need it ;)" human = X computer = O else: print "\nYour bravery will be your undoing....I will go first." computer = X human = O return computer, human # create new board def new_board(): """Create a new game board.""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board # display the board def display_board(board): """Display the board on the screen""" print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "---------" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "---------" print "\t", board[6], "|", board[7], "|", board[8], "\n" # set legal moves def legal_moves(board): """Create list of legal moves.""" moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves # set winner def winner(board): """Determine the game winner""" WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None # set human move def human_move(board, human): """Get human move.""" legal = legal_moves(board) move = None while move not in legal: move = ask_number("Where will you move? (0-8): ", 0, NUM_SQUARES) if move not in legal: print "\nThat square is already occupied. Please choose another.\n" print "Fine..." return move # set computer move def computer_move(board, computer, human): """Make computer move.""" # Make a copy of the board to work with since the function will be changing the list board = board[:] # The best positions to have, in order BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print "I shall take a square number", # if computer can win, take that move for move in legal_moves(board): board[move] = computer if winner(board) == computer: print move return move # done checking this move, undo it board[move] = EMPTY #if human can win, block that move for move in legal_moves(board): board[move] = human if winner(board) == human: print move return move # done checking this move, undo it board[move] = EMPTY # since no one can win on next move, pick best open square for move in BEST_MOVES: if move in legal_moves(board): print move return move # set next turn def next_turn(turn): """Switch turns.""" if turn == X: return O else: return X # congratulate winner def congrat_winner(the_winner, computer, human): """Congratulate the winner""" if the_winner != TIE: print the_winner, "won!\n" else: print "Its a tie!\n" if the_winner == computer: print "As I predicted human, I am triumphant once more. \n" \ "Proof that computers are superior to humans in all regards." elif the_winner == human: print "Nooooo! It cannot be! Somehow you tricked me human! \n" \ "But never again.......I will win next time!" elif the_winner == TIE: print "You were most lucky human, and somehow managed to tie me! \n" \ "Celebrate today....for this will not happen again!" # set main function def main(): display_instruct() computer, human = pieces() turn = X board = new_board() display_board(board) while not winner(board): if turn == human: move = human_move(board, human) board[move] = human else: move = computer_move(board, computer, human) board[move] = computer display_board(board) turn = next_turn(turn) the_winner = winner(board) congrat_winner(the_winner, computer, human) # start the program main() raw_input("\n\nPress the enter key to exit.") -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060202/e5bc7f59/attachment-0001.htm From kent37 at tds.net Thu Feb 2 12:03:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Feb 2006 06:03:33 -0500 Subject: [Tutor] printing the random seed? In-Reply-To: References: Message-ID: <43E1E705.6090202@tds.net> Danny Yoo wrote: > > On Thu, 2 Feb 2006, kevin parks wrote: > > >>Danny (hope you are good!) & co, >> >>I see that biz about random.seed()... but in the absence of setting that >>... does it just grab a value from the system clock? > > > Yes. Here's what the documentation says officially: > > """current system time is also used to initialize the generator when the > module is first imported""" As of Python 2.4, random.seed() will attempt to use os.urandom() to initialize the seed; if that is not available it uses the system time. >>Is there a way to just let it generate it's usual, known seed... but >>then observe what that is in case you get an especially good run of >>data? > > > We can call seed() explicitely using system time then when we start using > the random module, and if the results are interesting, we report that > initial seed value too. That way, by knowing the initial conditions, we > can reproduce the results. Here is the code from random.py that initializes the seed (a): try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds Kent From klappnase at freenet.de Thu Feb 2 12:28:15 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 2 Feb 2006 12:28:15 +0100 Subject: [Tutor] Using ioctl Message-ID: <20060202122815.105d02b5.klappnase@freenet.de> Hello, I am writing an app that records from the soundcard using ossaudiodev. In the OSS programmer's guide they recommend when reading data fragments from the soundcard to use the fragment size as it is requested by the driver. According to the programmer's guide the ioctl call to determine the requested fragment size is: int frag_size; if ioctl(audio_fd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1) error(); Unfortunately this procedure is not implemented in the ossaudiodev module, so I tried to write it myself. >From reading the fcntl module's docs, I came to the following solution: try: f = array.array('h', [0]) fcntl.ioctl(audio_fd, ossaudiodev.SNDCTL_DSP_GETBLKSIZE, f, 1) frag_size = f.tolist()[0] except: frag_size = -1 if frag_size <= 0: frag_size = 4096 This *seems* to work, I tried several soundcards and got frag_size values like 4096, 8192 or 16384 . However I am not really sure about what I am doing there, so I would feel more confident if anyone could explain how ioctl is supposed to be used ( I also felt that I should use the try...except block for the call in case it fails, but I don't have an idea "except *what*"). Any hints are much appreciated. thanks in advance Michael From johanpo at googlemail.com Thu Feb 2 13:12:08 2006 From: johanpo at googlemail.com (johan nilsson) Date: Thu, 2 Feb 2006 13:12:08 +0100 Subject: [Tutor] Windows problem with large(?) files In-Reply-To: References: <4d7db9340602020054g12c44d3al37f7536594901374@mail.gmail.com> Message-ID: <4d7db9340602020412t47a6b094n699b31a8e8657798@mail.gmail.com> Thanks Danny! that solved it. Johan On 2/2/06, Danny Yoo wrote: > > > > On Thu, 2 Feb 2006, johan nilsson wrote: > > > > apparently the XP box thinks the file is alot shorter, and that can't be > > as it is the same file from the same media (USB stick). What is going > > wrong here? > > Hi Johan, > > Is it possible that you need to treat the file as a binary file? It's > rare, but very possible that something like: > > f = open(somefilename,'r') > a = f.read() > > will give you different results on different platforms, because newline > translation occurs on the Windows end of things. ("\n" --> "\r\n" or visa > versa) So if your file coincidently has bytes with the sequential values: > > ###### > >>> ord('\r'), ord('\n') > (13, 10) > ###### > > then we should expect to see those two bytes collapsed down to a single > one through the mechanism of newline translation. > > > But if this is happening, there's an easy fix: > > f = open(somefilename,'rb') > a = f.read() > > where we open the file in binary mode. > > > Good luck! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060202/dc4f72cf/attachment.htm From kraus at hagen-partner.de Thu Feb 2 15:30:14 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 02 Feb 2006 15:30:14 +0100 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) In-Reply-To: References: <43E105DA.3030101@alum.rpi.edu> <006701c627d9$445eae40$0b01a8c0@xp> Message-ID: Jon Moore wrote: [...] > Thanks to Andr?, there is a way to win every time if you take the first > move (see below), so there MUST be a whole in the computers stratergy! > Based on what we all know about the game, I would say that you can not > make it so that the computer can win every time, but it should be > possable to make it tie. > > x: 0 > o: 4 > x: 7 > o: 2 ^ Make this 6,3,8 or 5 and it will be a tie > x: 6 > > 0 | 1 | 2 > --------- > 3 | 4 | 5 > --------- > 6 | 7 | 8 > > Wolfram From benvinger at yahoo.co.uk Thu Feb 2 15:37:17 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 2 Feb 2006 14:37:17 +0000 (GMT) Subject: [Tutor] Trapping a Dr Watson error Message-ID: <20060202143717.11398.qmail@web25805.mail.ukl.yahoo.com> Hello I have a script based on: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/Windows_NT_Eventlog.html It collects eventlogs data from many Windows servers. I know how to handle normal Python Tracebacks, but my script bombs out with a Dr Watson error when connecting to one particular server. (It even runs fine against the Application log of this server, but bombs out on the System log). Anyways, I want to know if it is possible to trap, handle and survive a Dr Watson error programatically Thanks Ben ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From jonathan.r.moore at gmail.com Thu Feb 2 15:46:36 2006 From: jonathan.r.moore at gmail.com (Jon Moore) Date: Thu, 2 Feb 2006 14:46:36 +0000 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) In-Reply-To: References: <43E105DA.3030101@alum.rpi.edu> <006701c627d9$445eae40$0b01a8c0@xp> Message-ID: All that does is reverse the hole!?!? x:2 o:4 x:7 o:0 x:8 0:5 O | | X --------- | O | O --------- | X | X On 02/02/06, Wolfram Kraus wrote: > > Jon Moore wrote: > [...] > > > Thanks to Andr?, there is a way to win every time if you take the first > > move (see below), so there MUST be a whole in the computers stratergy! > > Based on what we all know about the game, I would say that you can not > > make it so that the computer can win every time, but it should be > > possable to make it tie. > > > > x: 0 > > o: 4 > > x: 7 > > o: 2 > ^ > Make this 6,3,8 or 5 and it will be a tie > > > x: 6 > > > > 0 | 1 | 2 > > --------- > > 3 | 4 | 5 > > --------- > > 6 | 7 | 8 > > > > > > > Wolfram > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards Jon Moore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060202/cb6701de/attachment.html From andre.roberge at gmail.com Thu Feb 2 16:13:25 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 2 Feb 2006 11:13:25 -0400 Subject: [Tutor] Todays Learning Python Question From a Newbie ;) In-Reply-To: References: <43E105DA.3030101@alum.rpi.edu> <006701c627d9$445eae40$0b01a8c0@xp> Message-ID: <7528bcdd0602020713o13bfeb0n7e6df16f29d2249b@mail.gmail.com> As I indicated in private email yesterday to Jon, there is indeed a hole in the computer stratey when the following three first moves are made: x:2 o:4 (first available "best move" for the computer) x:7 I also sketched a "solution", which I will rephrase here in a different way. The next "best move" from the list leads to a win for the human, if she/he plays correctly. So, one has to put in "somewhere" (there are a few possible places) a test to see if this combination of the first three moves has occurred; if so, hard-code a computer response that defeats this strategy; if not, go and use the standard "best move" list. Andr? On 2/2/06, Jon Moore wrote: > All that does is reverse the hole!?!? > > x:2 > o:4 > x:7 > o:0 > x:8 > 0:5 > > O | | X > --------- > | O | O > --------- > | X | X > > > On 02/02/06, Wolfram Kraus wrote: > > Jon Moore wrote: > > [...] > > > > > Thanks to Andr?, there is a way to win every time if you take the first > > > move (see below), so there MUST be a whole in the computers stratergy! > > > Based on what we all know about the game, I would say that you can not > > > make it so that the computer can win every time, but it should be > > > possable to make it tie. > > > > > > x: 0 > > > o: 4 > > > x: 7 > > > o: 2 > > ^ > > Make this 6,3,8 or 5 and it will be a tie > > > > > x: 6 > > > > > > 0 | 1 | 2 > > > --------- > > > 3 | 4 | 5 > > > --------- > > > 6 | 7 | 8 > > > > > > > > > > > > Wolfram > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Best Regards > > Jon Moore > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From m.haft at abdn.ac.uk Thu Feb 2 14:50:49 2006 From: m.haft at abdn.ac.uk (Michael Haft) Date: Thu, 02 Feb 2006 13:50:49 +0000 Subject: [Tutor] list method help Message-ID: <5.2.1.1.0.20060202134408.00b831b0@mailms.abdn.ac.uk> Hello, was just trying to do something and tried the following code: list = ["1", "test", "1.5"] for x in list: print list.pop(x) I get the following error: print list.pop(x) TypeError: an integer is required Does this mean i can't use a for loop to pop things from a list? or is there another way to do it? I also tried the following: list = ["1", "test", "1.5"] for x in list: print list.pop(0) which worked but returned the following: 1 test Why did it not return the last value in the list? Thanks Mike ------------ Michael Haft School of Biological Sciences Plant & Soil Science Cruickshank Building St.Machar Drive Aberdeen AB24 3UU E-mail: m.haft at abdn.ac.uk From cspears2002 at yahoo.com Thu Feb 2 18:20:17 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 2 Feb 2006 09:20:17 -0800 (PST) Subject: [Tutor] critique my wrapper Message-ID: <20060202172017.903.qmail@web51609.mail.yahoo.com> This is a class I created that wraps a list. Could someone please critique the class? class MyList: def __init__(self, aList=None): if aList is None: self.mylist = [] else: self.mylist = aList[:] def __getitem__(self, index): return self.mylist[index] def __setitem__(self, index, value): self.mylist[index] = value def __len__(self): return len(self.mylist) def __delitem__(self, index): del self.mylist[index] def __add__(self, other): self.mylist = self.mylist + other def __repr__(self): return '%s' % self.mylist def append(self, other): self.mylist.append(other) def count(self, value): return self.mylist.count(value) def index(self, value): return self.mylist.index(value) def extend(self, seq): self.mylist.extend(seq) def insert(self, index, value): self.mylist.insert(index, value) def pop(self, index): return self.mylist.pop(index) def remove(self, value): self.mylist.remove(value) def reverse(self): self.mylist.reverse() def sort(self): self.mylist.sort() From alan.gauld at freenet.co.uk Thu Feb 2 19:17:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 2 Feb 2006 18:17:42 -0000 Subject: [Tutor] list method help References: <5.2.1.1.0.20060202134408.00b831b0@mailms.abdn.ac.uk> Message-ID: <00b301c62824$f597fc70$0b01a8c0@xp> > list = ["1", "test", "1.5"] > for x in list: > print list.pop(x) > > I get the following error: > > print list.pop(x) > TypeError: an integer is required > > Does this mean i can't use a for loop to pop things from a list? No it means pop takes an optional *index* as an argument. > list = ["1", "test", "1.5"] > for x in list: > print list.pop(0) > > which worked but returned the following: > > 1 > test > > Why did it not return the last value in the list? Because you provided an index of 0 which is the beginning. Try list = ["1", "test", "1.5"] for x in list: print list.pop() Or maybe more usefully: for x in range(len(list)): print list.pop() BTW list is a bad name for a variable since it masks the builtin list() function. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Thu Feb 2 20:52:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 Feb 2006 11:52:50 -0800 (PST) Subject: [Tutor] list method help In-Reply-To: <5.2.1.1.0.20060202134408.00b831b0@mailms.abdn.ac.uk> Message-ID: On Thu, 2 Feb 2006, Michael Haft wrote: > was just trying to do something and tried the following code: > > list = ["1", "test", "1.5"] > > for x in list: > print list.pop(x) > > I get the following error: > > print list.pop(x) > TypeError: an integer is required Hi Michael, The error message is accurate: list.pop() is only supposed to take an integer. If we take a look at the documentation of list.pop(), we should be able to see why: http://www.python.org/doc/lib/typesseq-mutable.html The problem is one of us being confusing about the domain that pop() takes in. pop() is supposed to take in the position of the element we're trying to pop, not the element itself. Does this make sense? > Does this mean i can't use a for loop to pop things from a list? or is > there another way to do it? > > I also tried the following: > > list = ["1", "test", "1.5"] > > for x in list: > print list.pop(0) > > which worked but returned the following: > > 1 > test > > Why did it not return the last value in the list? Simultaneous for-loop iteration and removal from a list is fraught with subtle issues. What's going on is that the for-loop expects all the elements to stay in place. In the example above, imagine an arrow aimed at a particular element of a list: ["1", "test", "1.5"] ^ During iteration, the arrow moves across the list till it hits the end of the list. Note, though, that list.pop(0) pulls elements toward the left: ["test", "1.5"] ^ and if the arrow naively marches forward, as in regular list iteration: ["test", "1.5"] ^ and we pop(0) again, then we again push the remaining element forward: ["1.5"] ^ but our arrow's out of the list's range! So we're done iterating across the list's structure, and this "premature" exit is what you're seeing. It's this interplay between the shifting behavior of pop(0) with the obliviousness of the iterator that causes these subtle issues. This is not really a Python-specific issue, but a fundamental one involving mutation across a list. (For example, Java has the same issues, and that's why Java's Iterator has a remove() method to attack this specific issue.) One way to get around this is to not use an iterator, but to use a different condition that's more stable under shifting, like checking for list length: while len(mylist) != 0: ... or we can pop() starting backwards, from the end of the list, which can less disruptive to the list's structure than pop()ping from the front. Just out of curiosity, though, what are you trying to do? Why pop() altogether? It might be that you can solve whatever problem you're doing with very little list mutation. Tell us more about what you're trying to do, and we can give more help. Good luck! From andre.roberge at gmail.com Thu Feb 2 20:55:34 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 2 Feb 2006 15:55:34 -0400 Subject: [Tutor] critique my wrapper In-Reply-To: <20060202172017.903.qmail@web51609.mail.yahoo.com> References: <20060202172017.903.qmail@web51609.mail.yahoo.com> Message-ID: <7528bcdd0602021155o16b64356t42aa53c0adc82ea@mail.gmail.com> On 2/2/06, Christopher Spears wrote: > This is a class I created that wraps a list. Could > someone please critique the class? > > class MyList: > def __init__(self, aList=None): > if aList is None: > self.mylist = [] > else: > self.mylist = aList[:] > def __getitem__(self, index): > return self.mylist[index] > def __setitem__(self, index, value): > self.mylist[index] = value > def __len__(self): > return len(self.mylist) > def __delitem__(self, index): > del self.mylist[index] > def __add__(self, other): > self.mylist = self.mylist + other > def __repr__(self): > return '%s' % self.mylist > def append(self, other): [snip] It's hard to critique without knowing your intentions. Here's a simpler class that should do the same as yours! class MyList2(list): def __init__(self, aList=[]): list(aList) I may have missed something but, unless you are re-defining a list method, it is easier to simply subclass list like I have done - and only re-define the methods whose behaviour you want to redefine, or add new method. Otherwise, simply use a_list = list() !!! Then again, perhaps I am missing something obvious... Andr? From smiles at worksmail.net Fri Feb 3 08:15:03 2006 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 3 Feb 2006 01:15:03 -0600 Subject: [Tutor] list method help References: Message-ID: <01a401c62893$5fe67480$332c4fca@csmith> | Hello, | was just trying to do something and tried the following code: | | list = ["1", "test", "1.5"] | | for x in list: | print list.pop(x) | | I get the following error: | | print list.pop(x) | TypeError: an integer is required | | Does this mean i can't use a for loop to pop things from a list? or is | there another way to do it? In the interactive window you can request help to see if that gives you a clue as to what might be going wrong: ### >>> help(list.pop) Help on method_descriptor: pop(...) L.pop([index]) -> item -- remove and return item at index (default last) ### So you must supply an index (which is an integer) defining which item you want to remove (or else supply no argument and automatically get the default which is the last item). You should not tell pop *what* you want to pop--which is what you did with the "x"--you should tell it which item *number* you want to pop--which you did in your next attempt. | | I also tried the following: | | list = ["1", "test", "1.5"] | | for x in list: | print list.pop(0) | | which worked but returned the following: | | 1 | test | | Why did it not return the last value in the list? | The "for x in list" is shorthand for the following equivalent syntax: i=0 while i range(3) => [0, 1, 2] Another approach you could use is to keep popping off elements until the list is consummed: while list: print list.pop(0) ----------------- OK, here's the aside--you might want to skip this for now. ----------------- If we reshuffle the list while we are walking through it, we can keep printing the same thing (not that we would really want to, but you get the idea that some internal index is advancing you through the list) ### >>> for x in l: ... print x,l ... l[:]=l[-1:]+l[0:-1] #rotate the list to the right ... 1 ['1', 'test', '1.5'] 1 ['1.5', '1', 'test'] 1 ['test', '1.5', '1'] ### But here is the first attempt that I made to do this and it gave a different result: ### >>> for x in l: ... print x,l ... l=l[-1:]+l[0:-1] ... 1 ['1', 'test', '1.5'] test ['1.5', '1', 'test'] 1.5 ['test', '1.5', '1'] ### So it appears that not only does the "for x in l" keep track of an index, it also keeps track of the original 'l' and allows me to point an 'l' in the loop to something separate from the one it is keeping track of. So it seems the "for x in l" is doing something like: i=0 tempList = list while i>> l=range(3) >>> a=l # 'a' is pointing at what 'l' is pointing at >>> l[0]=42 # I make a change to the thing that 'l' points to >>> print a [42, 1, 2] >>> print l [42, 1, 2] >>> ### Since a and l point at the same thing, they both show the change. But compare that to this: ### >>> l=range(3) >>> a=l # 'a' and 'l' point to the same thing >>> l=42 # here I make 'l' point to something else >>> print a [0, 1, 2] >>> print l 42 ### This perplexing issue is something that bites most of us at some time. I hope I haven't made it more perplexing ;-) If you have more questions, ask. /c From singletoned at gmail.com Fri Feb 3 13:44:45 2006 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 3 Feb 2006 12:44:45 +0000 Subject: [Tutor] Another try at Python's selfishness In-Reply-To: <1138967950.697932.213160@g49g2000cwa.googlegroups.com> References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> <1138967950.697932.213160@g49g2000cwa.googlegroups.com> Message-ID: <34bb7f5b0602030444u1709e7c8g@mail.gmail.com> On 3 Feb 2006 03:59:10 -0800, n.estner at gmx.de wrote: > > I still see "newbie-friendliness" as a > > MAJOR plus for Python -- it increases the chance that users > > of your software will become contributors. > > Yes, I 100% agree to that point! > But the point is, the current situation is not newbie-friendly (I can > tell, I am a newbie): I declare a method with 3 parameters but when I > call it I only pass 2 parameters. That's confusing. If I declare a > member variable, I write: "self.x = ValueForX", why can't I be equally > explicit for declaring member functions? I have to say that as a newbie, it took me quite a while to get my head around that extra parameter (self). It took me ages to work out that: class A: def __init__(self, foo): self.foo = foo a = A("hello") is actually a shortcut for: a = A(a, "Hello") or even: a = new A(a, "Hello") I think insisting on: a = A(a, "Hello") would be very good for readability, understandability and newbie-friendliness. Ed From w.damen at gmail.com Fri Feb 3 14:30:07 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 3 Feb 2006 14:30:07 +0100 Subject: [Tutor] Fwd: list method help In-Reply-To: <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> References: <01a401c62893$5fe67480$332c4fca@csmith> <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> Message-ID: <4677730602030530x4690e773wc3ffa90e40fe026d@mail.gmail.com> Chris or Leslie Smith: sorry wrong addess :*( This bit l[:]=l[-1:]+l[0:-1] I think is VERY elegant. When I saw this in your post I tought: DUH. I did the same with 1 line more but I am still new to python ;) Regarding the rest of the 'aside'. What is the reasoning behind this: ### >>> l=range(3) >>> a=l # 'a' is pointing at what 'l' is pointing at >>> l[0]=42 # I make a change to the thing that 'l' points to >>> print a [42, 1, 2] >>> print l [42, 1, 2] >>> ### -Why- are these 2 bound together? Is there a specific reasoning behind it? Cuz in Basic (if we had lists............) I'd expect this: ### >>> l=range(3) >>> a=l # 'a' is pointing at what 'l' is pointing at >>> l[0]=42 # I make a change to the thing that 'l' points to >>> print a [0, 1, 2] >>> print l [42, 1, 2] >>> ### To get there you'd need 1 more line: What is the reasoning behind this: ### >>> l=range(3) >>> a=l # 'a' is pointing at what 'l' is pointing at >>> l[0]=42 # I make a change to the thing that 'l' points to >>> a=l <------- this one added by ME. >>> print a [42, 1, 2] >>> print l [42, 1, 2] >>> ### Oh and I DO think it's a cool feature btw. But I had me guessing alot too. From w.damen at gmail.com Fri Feb 3 16:58:56 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 3 Feb 2006 16:58:56 +0100 Subject: [Tutor] list method help In-Reply-To: <003401c628d9$45fc3a50$3f2c4fca@csmith> References: <01a401c62893$5fe67480$332c4fca@csmith> <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> <003401c628d9$45fc3a50$3f2c4fca@csmith> Message-ID: <4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com> On 2/3/06, Chris or Leslie Smith wrote: > Rinzwind wrote: > | Well Chris or Leslie Smith. > | > | This bit l[:]=l[-1:]+l[0:-1] I think is VERY elegant. When I saw this > | in your post I tought: DUH. > | I did the same with 1 line more but I am still new to python ;) > | > You're seeing the beauty of the language at work :-) I sure do :) I also love dictionaries, tuples, and lists. Thoroughbred Basic doesn't work like that :* > | Regarding the rest of the 'aside'. > | > | What is the reasoning behind this: > | > | ### > |||| l=range(3) > |||| a=l # 'a' is pointing at what 'l' is pointing at > |||| l[0]=42 # I make a change to the thing that 'l' points to > |||| print a > | [42, 1, 2] > |||| print l > | [42, 1, 2] > |||| > | ### > | > | -Why- are these 2 bound together? Is there a specific reasoning > | behind it? > | > | Cuz in Basic > > Others could give you a really good answer. I am a BASIC/FORTRAN writer > myself, and getting used to the *object* orientation of python took a little > while, but after you get the hang of it, it's not bad. In BASIC you think of 10 FOR P1= 1 TO 10000; PRINT 'Hello Chris'; NEXT P1 That Basic not VB ;-) > variables *containing* things, so when you say l=2 and a=l you think of two > variables each containing the (what happens to be) the same thing. In > python, however, mutable objects (like lists) are *pointed to* by the > variable name. so the 'l=range(3)' above tells python to create a list and > point the variable name 'l' at it. Then when you say 'a=l' you are telling > it to point 'a' at the same thing as 'l'--one object (the list); two > references to it. Yes, I read something about it concerning ID's assigned to variables. So A = [1,2,3,4] has an ID 209370 And L = A gives L the ID 209370 matching them together. It's cool :-) and would save me alot of A=L stmts in Basic. '-) <..> > | What is the reasoning behind this: > | > | ### > |||| l=range(3) > |||| a=l # 'a' is pointing at what 'l' is pointing at > |||| l[0]=42 # I make a change to the thing that 'l' points to > |||| a=l <------- this one added by ME. > |||| print a > | [42, 1, 2] > |||| print l > | [42, 1, 2] > |||| > | ### > > I know what you are getting at, but from what I wrote above do you see the > difference yet? In basic, saying 'a=l' has created a new variable/value item > and if you want the new change to be reflected in a after making a change to > l you have to 'copy it there' with another a=l statement. In python there is > only one object (the [0, 1, 2]) with two variables pointing to it (a and l). > Those pointer-varaibles are like aliases for the same thing. Oh I understand it :) Was just wondering -why-. I sometimes am like a 10 year old wanting not to know how it works by why it was created to work that way. There must be a reason ;-) <..> > > p.s. I am Chris. My wife and I share the same account, so that's why there > is a "or" in the email name :-) > > Well I can't guess if it's you, your wife or you are both behind your PC beating eachother over the head to decide who can answer my questions :-D From kent37 at tds.net Fri Feb 3 17:21:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Feb 2006 11:21:25 -0500 Subject: [Tutor] list method help In-Reply-To: <4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com> References: <01a401c62893$5fe67480$332c4fca@csmith> <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> <003401c628d9$45fc3a50$3f2c4fca@csmith> <4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com> Message-ID: <43E38305.9030708@tds.net> > On 2/3/06, Chris or Leslie Smith wrote: >>Others could give you a really good answer. I am a BASIC/FORTRAN writer >>myself, and getting used to the *object* orientation of python took a little >>while, but after you get the hang of it, it's not bad. In BASIC you think of >>variables *containing* things, so when you say l=2 and a=l you think of two >>variables each containing the (what happens to be) the same thing. In >>python, however, mutable objects (like lists) are *pointed to* by the >>variable name. so the 'l=range(3)' above tells python to create a list and >>point the variable name 'l' at it. Then when you say 'a=l' you are telling >>it to point 'a' at the same thing as 'l'--one object (the list); two >>references to it. You definitely have to stop thinking of variables as containers. They are pointers or references to values. Another way to think of this is that variables are names for things. You may call me Kent, someone else might call me Mr. Johnson or Dad, but if I get a haircut, Kent, Mr. Johnson and Dad all have shorter hair because all three names refer to the same person. Python works the same way. Assignment binds a name to a value. So if I say lst = [0, 1, 2] I have bound the name 'lst' to a particular list whose value, at the moment, is [0, 1, 2]. If I then assign a = lst this binds the name 'a' to the same value (the list) that 'lst' is bound to. If I change the bound list, you will see the change whether you access the list through the name 'a' or the name 'lst'. Kent From cspears2002 at yahoo.com Fri Feb 3 17:43:28 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 3 Feb 2006 08:43:28 -0800 (PST) Subject: [Tutor] subclass Message-ID: <20060203164328.23030.qmail@web51608.mail.yahoo.com> Here is a problem I'm working on out of Learning Python: Make a subclass of MyList from exercise 2 called MyListSub which extends MyList to print a message to stdout before each overloaded operation is called and counts the number of calls. MyListSub should inherit basic method behavoir from MyList. Adding a sequence to a MyListSub should print a message, increment the counter for + calls, and perform the superclass's method. There is more after that, but I will tackle that after I clear up this part. Here is MyList.py: class MyList: def __init__(self, start): self.mylist = [] for x in start: self.mylist.append(x) def __getitem__(self, index): return self.mylist[index] def __setitem__(self, index, value): self.mylist[index] = value def __len__(self): return len(self.mylist) def __delitem__(self, index): del self.mylist[index] def __add__(self, other): return MyList(self.mylist + other) def __mul__(self, other): return MyList(self.mylist * other) def __getslice__(self, low, high): return MyList(self.mylist[low:high]) def __repr__(self): return '%s' % self.mylist def append(self, other): self.mylist.append(other) def count(self, value): return self.mylist.count(value) def index(self, value): return self.mylist.index(value) def extend(self, seq): self.mylist.extend(seq) def insert(self, index, value): self.mylist.insert(index, value) def pop(self, index): return self.mylist.pop(index) def remove(self, value): self.mylist.remove(value) def reverse(self): self.mylist.reverse() def sort(self): self.mylist.sort() My first thought for printing messages was to do something like this: MyListSub.py: from MyList import * class MyListSub(MyList): def __init__(self, start): print "implementing __init__ method for MyListSub" self.mylist = [] for x in start: self.mylist.append(x) This is what I call the idiot's method. Basically, I would put a print message in each method as well as some sort of counter. However, I keep wondering if there is a more elegant way to do this like create some sort of function that does this: if a method is called: print a message if a method is called: increment a counter for that method From kent37 at tds.net Fri Feb 3 17:57:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Feb 2006 11:57:11 -0500 Subject: [Tutor] subclass In-Reply-To: <20060203164328.23030.qmail@web51608.mail.yahoo.com> References: <20060203164328.23030.qmail@web51608.mail.yahoo.com> Message-ID: <43E38B67.6050804@tds.net> Christopher Spears wrote: > Here is a problem I'm working on out of Learning > Python: > > Make a subclass of MyList from exercise 2 called > MyListSub which extends MyList to print a message to > stdout before each overloaded operation is called and > counts the number of calls. MyListSub should inherit > basic method behavoir from MyList. Adding a sequence > to a MyListSub should print a message, increment the > counter for + calls, and perform the superclass's > method. > > > However, I keep wondering if there is a more elegant > way to do this like create some sort of function that > does this: > > if a method is called: > print a message > > if a method is called: > increment a counter for that method You could do this by overriding __getattribute__ in MyListSub. This would allow you to put all the printing and counting code in one place. This is an elegant solution that will probably cause you a couple of stack overflows before you get it right. http://docs.python.org/ref/new-style-attribute-access.html You could also write a decorator that adds printing and counting behaviour to a method. You would have to apply the decorator to each method. I suppose you could apply the decorator in a metaclass...but I would try the __getattribute__ approach first. Neither of these approaches are really beginner exercises... Kent From w.damen at gmail.com Fri Feb 3 20:09:19 2006 From: w.damen at gmail.com (Rinzwind) Date: Fri, 3 Feb 2006 20:09:19 +0100 Subject: [Tutor] list method help In-Reply-To: <43E38305.9030708@tds.net> References: <01a401c62893$5fe67480$332c4fca@csmith> <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> <003401c628d9$45fc3a50$3f2c4fca@csmith> <4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com> <43E38305.9030708@tds.net> Message-ID: <4677730602031109x337f780ctd08cbe0bf960c5a3@mail.gmail.com> On 2/3/06, Kent Johnson wrote: > > > On 2/3/06, Chris or Leslie Smith wrote: > >>Others could give you a really good answer. I am a BASIC/FORTRAN writer > >>myself, and getting used to the *object* orientation of python took a > little > >>while, but after you get the hang of it, it's not bad. In BASIC you > think of > >>variables *containing* things, so when you say l=2 and a=l you think of > two > >>variables each containing the (what happens to be) the same thing. In > >>python, however, mutable objects (like lists) are *pointed to* by the > >>variable name. so the 'l=range(3)' above tells python to create a list > and > >>point the variable name 'l' at it. Then when you say 'a=l' you are > telling > >>it to point 'a' at the same thing as 'l'--one object (the list); two > >>references to it. > > You definitely have to stop thinking of variables as containers. They > are pointers or references to values. Another way to think of this is > that variables are names for things. You may call me Kent, someone else > might call me Mr. Johnson or Dad, but if I get a haircut, Kent, Mr. > Johnson and Dad all have shorter hair because all three names refer to > the same person. > > Python works the same way. Assignment binds a name to a value. So if I say > lst = [0, 1, 2] > I have bound the name 'lst' to a particular list whose value, at the > moment, is [0, 1, 2]. If I then assign > a = lst > this binds the name 'a' to the same value (the list) that 'lst' is bound > to. If I change the bound list, you will see the change whether you > access the list through the name 'a' or the name 'lst'. > > Kent Kent that's a perfectly understandable and easy to grasp analogy. But it stays just an analogy ;-) Thing is. We people consist of more than a 1st name to identify ourself. It is 1st name, last name, country, place of birth, town you now live in, street, postal code, number of the house, date of birth and in case of twins or triplets even the time of birth and maybe a bunch more details. But coding is not IRL and isn't a reflection of it either. Coding is alot easier bacause it does not require that 2 variables need to be linked. I have been coding with the knowledge A is A and A is never B. Not even if they contain the same content but they can have the content copied from 1 to another :-P My question might be summed up to: When would I have need of this? Or why do I want it? Where is the benefit? When I look at this: for x in range(3): I know it is shorthand for something like (not exactly but it serves its purpose as an example): x = 0 while x<=3 do: x = x +1 And I understand why it is done this way: it makes code shorter AND it is even easier to read: a win-win situation. And the same goes for alot of other things in Python. But this assignment sort of puzzles me to why it's done like this (maybe cuz I am not used to it and can not see beyond my own experience in coding (having a blind spot or something like that)). Oh and tell me to shut up and just accept it if you want to ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060203/ff133c8d/attachment-0001.html From deepak.gupta at hsbsoft.com Fri Feb 3 13:25:29 2006 From: deepak.gupta at hsbsoft.com (deepak.gupta) Date: Fri, 3 Feb 2006 17:55:29 +0530 Subject: [Tutor] query regarding mysql database backup?? please Help Message-ID: <001f01c628bc$eda0d120$2e01a8c0@hantz.com> Hi, I did my script like this for backing my max_everest_2006 mysql database >>import os > > target_dir = "./backup" > > os.system("mysqldump --add-drop-table -c -u root -pmysql 'MAX_EVEREST_2006' > "+target_dir+"table.bak.sql") root is my user name,mysql is my password,'MAX_EVEREST_2006' is my database name. reply me as soon as possible error: 1044: Access denied for user 'MAX_USER'@'%' to database 'MAX_EVEREST_2006' when using LOCK TABLES Please help Thanks deepak gupta -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060203/ee934fd9/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Feb 3 20:48:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Feb 2006 11:48:19 -0800 (PST) Subject: [Tutor] query regarding mysql database backup?? please Help In-Reply-To: <001f01c628bc$eda0d120$2e01a8c0@hantz.com> Message-ID: On Fri, 3 Feb 2006, deepak.gupta wrote: > I did my script like this for backing my max_everest_2006 mysql database > > error: 1044: Access denied for user 'MAX_USER'@'%' to database > 'MAX_EVEREST_2006' when using LOCK TABLES Your question doesn't have to do with Python. Ask your MySQL administrator to help you: what you're seeing is a MySQL error message. From kent37 at tds.net Fri Feb 3 22:38:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Feb 2006 16:38:22 -0500 Subject: [Tutor] list method help In-Reply-To: <4677730602031109x337f780ctd08cbe0bf960c5a3@mail.gmail.com> References: <01a401c62893$5fe67480$332c4fca@csmith> <4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com> <003401c628d9$45fc3a50$3f2c4fca@csmith> <4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com> <43E38305.9030708@tds.net> <4677730602031109x337f780ctd08cbe0bf960c5a3@mail.gmail.com> Message-ID: <43E3CD4E.4070306@tds.net> Rinzwind wrote: > On 2/3/06, *Kent Johnson* > wrote: > You definitely have to stop thinking of variables as containers. They > are pointers or references to values. Another way to think of this is > that variables are names for things. You may call me Kent, someone else > might call me Mr. Johnson or Dad, but if I get a haircut, Kent, Mr. > Johnson and Dad all have shorter hair because all three names refer to > the same person. > > Python works the same way. Assignment binds a name to a value. So if > I say > lst = [0, 1, 2] > I have bound the name 'lst' to a particular list whose value, at the > moment, is [0, 1, 2]. If I then assign > a = lst > this binds the name 'a' to the same value (the list) that 'lst' is bound > to. If I change the bound list, you will see the change whether you > access the list through the name 'a' or the name 'lst'. > > Kent that's a perfectly understandable and easy to grasp analogy. But it > stays just an analogy ;-) The first paragraph above is analogy, the second is commonly used Python terminology. For example, from the Language Reference: "Assignment statements are used to (re)bind names to values." http://docs.python.org/dev/ref/assignment.html > Coding is alot easier bacause it does not require that 2 variables need > to be linked. I have been coding with the knowledge A is A and A is > never B. Not even if they contain the same content but they can have the > content copied from 1 to another :-P > > My question might be summed up to: > When would I have need of this? Or why do I want it? Where is the benefit? You are suggesting that assignment copy values, rather than references to values. This could be very expensive. For example if you want to pass a large list to a function, passing just a reference to the list is much easier than passing a copy of the list. References are used in other languages, too. With the exception of primitive values (int, float, char, etc) Java variables have exactly the semantics of Python variables - they are references to objects, and assignment copies the reference, not the value. C and C++ can use pointers to structures which are similar to Java and Python references. So Python is not really so odd, it's just different than what you are used to and expect. > But this assignment sort of puzzles me to why it's done like this (maybe > cuz I am not used to it and can not see beyond my own experience in > coding (having a blind spot or something like that)). > > Oh and tell me to shut up and just accept it if you want to ;-) Good idea. Just get over it, it's really not a big deal. ;-) It's only a problem if you try to hold on to the copying model, then you will be occasionally surprised. Kent From dyoo at hkn.eecs.berkeley.edu Fri Feb 3 23:33:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Feb 2006 14:33:25 -0800 (PST) Subject: [Tutor] list method help In-Reply-To: <43E3CD4E.4070306@tds.net> Message-ID: > > But this assignment sort of puzzles me to why it's done like this > > (maybe cuz I am not used to it and can not see beyond my own > > experience in coding (having a blind spot or something like that)). If we have a snippet of code like: ########### def test(): x = [] f(x) print x ########### we have a strong guarantee that 'x' won't be redirected to another value. The situation above, right before calling f(), looks like: x --------------> [] Of course, f() can apply mutation on the list and change the shape of the list value. But no matter what, f can't get 'x' directed to an entirely different list value. In Python, all names are just arrows to values. Assignment is the operation of getting the target on the left hand side to direct its arrow at the value on the right hand side. Variable name lookup is just getting at the value that the arrow is pointing at. If we're familiar with a language like C, we can imagine that, in Python's world, all variable names are pointers to things. So when we see something like: ###### x = 42 ###### if we were to literally translate what Python's does here in a C context, we'd see something like this: /******/ int *x = make_int(42); /******/ where there's a core set of value-making functions available somewhere, like: /******/ int* make_int(int val) { int *result = malloc(sizeof(int)); *result = val; return result; /******/ > Good idea. Just get over it, it's really not a big deal. ;-) It's only a > problem if you try to hold on to the copying model, then you will be > occasionally surprised. The copying model works just as well, so long as we keep in mind that variable names hold arrows (where those arrows aim at values) rather than the values themselves. Best of wishes! From alan.gauld at freenet.co.uk Sat Feb 4 01:11:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 4 Feb 2006 00:11:27 -0000 Subject: [Tutor] list method help References: <01a401c62893$5fe67480$332c4fca@csmith><4677730602030219i31552218q7e3e3592ef6df73c@mail.gmail.com><003401c628d9$45fc3a50$3f2c4fca@csmith><4677730602030758s171653c3k5177db7d8bc507ef@mail.gmail.com><43E38305.9030708@tds.net> <4677730602031109x337f780ctd08cbe0bf960c5a3@mail.gmail.com> Message-ID: <00f901c6291f$8b18c860$0b01a8c0@xp> > > You definitely have to stop thinking of variables as containers. They > > are pointers or references to values. Another way to think of this is > > that variables are names for things. > Kent that's a perfectly understandable and easy to grasp analogy. But it > stays just an analogy ;-) Nope. In Python it is what happens. Python implrements most things using dictionaries under the covers. When you create a new variable name by doing something like n = 42 Python does something like: variables['n'] = 42 where variables is a dictionary. You can even print the dictionaries if you know the right magic words ;-) when you access a variable by typing print n Python translates that to print variables['n'] > Thing is. We people consist of more than a 1st name to identify ourself. Yes we have identity. And so do Python variables (the actual objects that the names point at, not the names) and we can print the identity out by using the id() function: x = 42 y = x z = y print id(x), id(y), id(z) will all print out the same id since Python caches low value integers and all three names point at the same stored value. > coding is not IRL and isn't a reflection of it either. But creating a reflection of real life is the goal of programming designers for decades. The whole OOP thing came out of attempte to model the real world using the simulation language Simula. > Coding is alot easier bacause it does not require that 2 variables > need to be linked. True, but not being able to link them causes its own problems. Some languages, like C/C++ allow both styles: int n = 42 // n is a memory location which holds 42 int &x = n // n is a memory location that points at whatever n contains. printf ("%d\t%d",n,x) / prints 42 twice n = 27 printf ("%d\t%d",n,x) / prints 27 twice Python takes the approach that references are generally easier to work with than static values, but they do bring their own perils... > coding with the knowledge A is A and A is never B. This was true in the very oldest languages like COBOL and Fortran and BASIC but even Lisp, which is of the same c1960 vintage, used references. And almoist all languages since the late 60s have had some form of reference mechanism. Most languages since the late 1980's have tended to make variable naming by reference the default. > When would I have need of this? When the real world works thatv way, which is often. When you want to minimise machine resource by avoiding multiple copies of the same data When you want to minimise the number of names in your code - it is essential for dynamic typing! When you want to use OOP, static objects are virtually never polymorphic and hence are very limited in usefulness. > Or why do I want it? Where is the benefit? The benefits are real and the reasons above indicate some of them. But there is a dark side as you have discovered. There are times when a static definition is more logical. > for x in range(3): > > I know it is shorthand for something like (not exactly but it > serves its purpose as an example): In fact that may be how you think of it as an analogy to how you are accustomed to programming but in fact it is nothing like that. Pythons for loop is much more sophisticated and uses iterators which in turn use polymorphism within Pythons object model. That relies on the names being references. > x = 0 > while x<=3 do: > x = x +1 > > And I understand why it is done this way: So how does your analogy work with this code: for item in [1,'aString', lambda x: x*x, True]: print item You now need to change your code to incorporate a call to len() and incorporate the concept of an index. But what if the object being iterated has no len capability, it may even be infinite in length (a generator function say)? Like this: def f(x): n = 2*x while True: n *= 2 yield n for y in f(2): print y This is getting into subtleties I know, but it illustrates just how much more powerful Pythons apparently simple structures are, and they rely on the use of named bindings rather than static variable containers. > Oh and tell me to shut up and just accept it if you want to ;-) No, its always better to ask. Sometimes we may not understand the answer, or may not agree with the answer or whatever. But its always better to ask. And sometimes the answer in Python is simply that Guido van Rossum prefers it that way! Alan G. From alan.gauld at freenet.co.uk Sat Feb 4 01:24:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 4 Feb 2006 00:24:14 -0000 Subject: [Tutor] Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com><1138967950.697932.213160@g49g2000cwa.googlegroups.com> <34bb7f5b0602030444u1709e7c8g@mail.gmail.com> Message-ID: <00ff01c62921$53f62e20$0b01a8c0@xp> > I have to say that as a newbie, it took me quite a while to get my > head around that extra parameter (self). That's OK, its true of most folks, even non newbies! It is one area where Python is different to most languages who hide the self completely. > It took me ages to work out that: > >class A: > def __init__(self, foo): > self.foo = foo > > a = A("hello") > > is actually a shortcut for: > > a = A(a, "Hello") > I think insisting on: > > a = A(a, "Hello") > > would be very good for readability, understandability and > newbie-friendliness. Only for the constructor. Once you have the object itself the method calls wouyld be much less readable: class C: def a(s):pass c = C() c = c.a(c) etc is not descriptive of the concept of passing a message to the object c, it looks rather like you are passing the object c to a function which is a member of itself, which brings to mind recursion not messages... Remember that the purpose of writing a class is to *hide* the details of its implementation from the user, thus the user never has to use self, only the builder. The only reason you are confused is because you are both builder and user of the class. But consider file objects, do you ever feel the need to write: myfile = file(myfile,filename,mode) or does myfile = file(filename,mode) seem more friendly? Is that because you've nbever actually seen the constructor code for the file class(*) and so don't worry about the presence of self? If you did have to pass the object in, wouldn't you be asking why you had to pass the object into the file creation method? (*)OK I haven't checked, but I strongly suspect the built in file objects aren't written in Python so won't look the same but the illustration is valid. I dunno if that helps explain the rational but maybe... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From singletoned at gmail.com Sat Feb 4 11:36:28 2006 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 4 Feb 2006 10:36:28 +0000 Subject: [Tutor] Another try at Python's selfishness In-Reply-To: <00ff01c62921$53f62e20$0b01a8c0@xp> References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com> <1138967950.697932.213160@g49g2000cwa.googlegroups.com> <34bb7f5b0602030444u1709e7c8g@mail.gmail.com> <00ff01c62921$53f62e20$0b01a8c0@xp> Message-ID: <34bb7f5b0602040236q67af3b04p@mail.gmail.com> On 04/02/06, Alan Gauld wrote: > > I have to say that as a newbie, it took me quite a while to get my > > head around that extra parameter (self). > > That's OK, its true of most folks, even non newbies! > It is one area where Python is different to most languages > who hide the self completely. > > > It took me ages to work out that: > > > >class A: > > def __init__(self, foo): > > self.foo = foo > > > > a = A("hello") > > > > is actually a shortcut for: > > > > a = A(a, "Hello") > > > I think insisting on: > > > > a = A(a, "Hello") > > > > would be very good for readability, understandability and > > newbie-friendliness. > > Only for the constructor. > Once you have the object itself the method calls wouyld be much less > readable: > > class C: > def a(s):pass > > c = C() > c = c.a(c) > etc > > is not descriptive of the concept of passing a message to the object c, > it looks rather like you are passing the object c to a function which is > a member of itself, which brings to mind recursion not messages... > > Remember that the purpose of writing a class is to *hide* the details of > its implementation from the user, thus the user never has to use self, > only the builder. The only reason you are confused is because you > are both builder and user of the class. As always Alan, you've managed to make something confusing seem sensible and logical. That is the best explanation of this subject I've ever heard. > But consider file objects, do you ever feel the need to write: > > myfile = file(myfile,filename,mode) > > or does > > myfile = file(filename,mode) > > seem more friendly? Is that because you've nbever actually > seen the constructor code for the file class(*) and so don't > worry about the presence of self? > If you did have to pass the object in, wouldn't you be asking > why you had to pass the object into the file creation method? I now agree, and (I think) understand completely. Ed PS Are there any good tutorials on the more philosophical side of the object orientedness of Python? I've read pretty much all the major tutorials that are commonly linked to, and they often cover HOW to use classes and stuff, but I'm quite interested in WHY we use classes (and as I've discovered from you and Kent, WHEN to use classes). I've found some general OOP tutorials, but they always seem to use Java or C which I don't know and don't particularly care to know. From alan.gauld at freenet.co.uk Sat Feb 4 19:19:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 4 Feb 2006 18:19:25 -0000 Subject: [Tutor] Another try at Python's selfishness References: <1138918102.863033.298700@o13g2000cwo.googlegroups.com><1138967950.697932.213160@g49g2000cwa.googlegroups.com><34bb7f5b0602030444u1709e7c8g@mail.gmail.com><00ff01c62921$53f62e20$0b01a8c0@xp> <34bb7f5b0602040236q67af3b04p@mail.gmail.com> Message-ID: <012701c629b7$87a884c0$0b01a8c0@xp> > PS Are there any good tutorials on the more philosophical side of the > object orientedness of Python? Good question, but I don't know of any answers. One author from the c.l.p list was writing a book about the innards of Python that promised to answer many of those questions but sadly that project has stalled... > found some general OOP tutorials, but they always seem to use Java or > C which I don't know and don't particularly care to know. The best (theoretical) book on OO I know of is Meyer's OO Software Construction (2nd ed - NOT the first!) Its huge (c 1000 pages) but it does a great job of explaining why OO things are the way they are. BUT its code is in Eiffel... Grady Booch is allegedly doing a 3rd edition of his OOD book using UML and that used to have a good (and shorter!) rationale section in it. You could probably borrow either the 1st or 2nd edition from a library? Alan G. From python.bian at gmail.com Sun Feb 5 05:59:44 2006 From: python.bian at gmail.com (Bian Alex) Date: Sun, 5 Feb 2006 12:59:44 +0800 Subject: [Tutor] A question Message-ID: How can I get a string from a random file. For Example: Del ete On : Copy Owner : Bn Personalized: 5 PersonalizedName : My Documents I want to get the string after 'Owner' ( In example is 'Bn') 'import re' ? Pls help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060205/c809043b/attachment.htm From w.damen at gmail.com Sun Feb 5 10:30:47 2006 From: w.damen at gmail.com (Rinzwind) Date: Sun, 5 Feb 2006 10:30:47 +0100 Subject: [Tutor] A question In-Reply-To: References: Message-ID: <4677730602050130j59ca3542n2e8115b7a8b62e5c@mail.gmail.com> On 2/5/06, Bian Alex wrote: > > How can I get a string from a random file. > For Example: > Del ete On : Copy > Owner : Bn > Personalized: 5 > PersonalizedName : My Documents > > I want to get the string after 'Owner' ( In example is 'Bn') > > 'import re' ? > > Pls help. > help You mean like this? >>> line ='Owner:Bn' >>> line = line.split(":") >>> print line ['Owner', 'Bn'] >>> print line[1] Bn So you read the lines from the file till you find "Owner:Bn" and split it at the ':'. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060205/d72e96ca/attachment.html From marilyn at deliberate.com Sun Feb 5 14:52:53 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 5 Feb 2006 05:52:53 -0800 (PST) Subject: [Tutor] A question In-Reply-To: Message-ID: On Sun, 5 Feb 2006, Bian Alex wrote: > How can I get a string from a random file. > For Example: > Del ete On : Copy > Owner : Bn > Personalized: 5 > PersonalizedName : My Documents > > I want to get the string after 'Owner' ( In example is 'Bn') > > 'import re' ? Yes, but maybe it's simpler to use the builtin functions, and slicing: text = open('the_file').readlines() <-- now the_file is in text as a string start = text.find('Owner :') + 8 <-- start is the index into the text where Owner starts + 8 to point to the text you want. end = text.find('\n', start) <-- end is where the newline is, after start. found = text[start:end].strip() <-- found has the text you want, with any spaces stripped off. I hope it helps. I didn't test it. Marilyn Davis > > Pls help. > -- From marilyn at deliberate.com Sun Feb 5 15:21:36 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 5 Feb 2006 06:21:36 -0800 (PST) Subject: [Tutor] A question In-Reply-To: Message-ID: On Sun, 5 Feb 2006, Marilyn Davis wrote: > On Sun, 5 Feb 2006, Bian Alex wrote: > > > How can I get a string from a random file. > > For Example: > > Del ete On : Copy > > Owner : Bn > > Personalized: 5 > > PersonalizedName : My Documents > > > > I want to get the string after 'Owner' ( In example is 'Bn') > > > > 'import re' ? > > Yes, but maybe it's simpler to use the builtin functions, and slicing: > > text = open('the_file').readlines() <-- now the_file is in text as a string Ooops. This should be: text = open('the_file').read() Maybe someone else will show you the readlines() solution. I have to run. Good luck. Marilyn > > start = text.find('Owner :') + 8 <-- start is the index into the text > where Owner starts + 8 to point > to the text you want. > end = text.find('\n', start) <-- end is where the newline is, after > start. > found = text[start:end].strip() <-- found has the text you want, with > any spaces stripped off. > > I hope it helps. I didn't test it. > > Marilyn Davis > > > > > Pls help. > > > > -- From pkraus at pelsupply.com Mon Feb 6 03:37:16 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Sun, 5 Feb 2006 21:37:16 -0500 Subject: [Tutor] Documentation Message-ID: <200602052137.16539.pkraus@pelsupply.com> I have been working through a couple of books and learning alot. However I can't seem to find any easy way to learn more about different methods and commands. For instance what are all of the methods that can be applied to lists and what do they do and how do they work. Or in TKinter what are all the different things can I do with a button besides just setting the command and the text and such. These are just examples. I can't find an easy way to do this. I know there has to be i have tried the pydoc gui but I found nothing when i searched list. *shrug* -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From andre.roberge at gmail.com Mon Feb 6 03:45:40 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sun, 5 Feb 2006 22:45:40 -0400 Subject: [Tutor] Documentation In-Reply-To: <200602052137.16539.pkraus@pelsupply.com> References: <200602052137.16539.pkraus@pelsupply.com> Message-ID: <7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com> On 2/5/06, Paul Kraus wrote: > I have been working through a couple of books and learning alot. However I > can't seem to find any easy way to learn more about different methods and > commands. > > For instance what are all of the methods that can be applied to lists and what > do they do and how do they work. Or in TKinter what are all the different > things can I do with a button besides just setting the command and the text > and such. These are just examples. > > I can't find an easy way to do this. > Python is your friend! Here's the (truncated) result of an interactive session. PythonWin 2.4.2 (#67, Oct 30 2005, 16:11:18) [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. >>> a = [] >>> dir (a) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> help(a.index) Help on built-in function index: index(...) L.index(value, [start, [stop]]) -> integer -- return first index of value >>> import Tkinter >>> dir(Tkinter) ['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'At', 'AtEnd', 'AtInsert', 'AtSelFirst', 'AtSelLast', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', 'BitmapImage', 'BooleanType', 'BooleanVar', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'Button', [snip] >>> dir(Tkinter.Button) ['_Misc__winfo_getint', '_Misc__winfo_parseitem', '__doc__', '__getitem__', '__init__', '__module__', '__setitem__', '__str__', '_bind', '_configure', '_displayof', '_do', '_getboolean', '_getdoubles', '_getints', '_grid_configure', '_nametowidget', '_noarg_', '_options', '_register', '_report_exception', '_root', '_setup', '_subst_format', '_subst_format_str', '_substitute', [snip] >>> help(Tkinter.Button.configure) Help on method configure in module Tkinter: configure(self, cnf=None, **kw) unbound Tkinter.Button method Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. Try it on your own! As a rule, stay away from methods that start with an underscore. Andr? From pkraus at pelsupply.com Mon Feb 6 03:50:28 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Sun, 5 Feb 2006 21:50:28 -0500 Subject: [Tutor] Documentation In-Reply-To: <7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com> References: <200602052137.16539.pkraus@pelsupply.com> <7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com> Message-ID: <200602052150.28732.pkraus@pelsupply.com> > >>> help(Tkinter.Button.configure) > > Help on method configure in module Tkinter: > > configure(self, cnf=None, **kw) unbound Tkinter.Button method > Configure resources of a widget. > > The values for resources are specified as keyword > arguments. To get an overview about > the allowed keyword arguments call the method keys. > > > Try it on your own! As a rule, stay away from methods that start with > an underscore. Thanks for the fast response. This was exactly what I was looking for. One last question how would I 'call the method keys'. from the example above. -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From john at fouhy.net Mon Feb 6 04:04:33 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 6 Feb 2006 16:04:33 +1300 Subject: [Tutor] Documentation In-Reply-To: <200602052150.28732.pkraus@pelsupply.com> References: <200602052137.16539.pkraus@pelsupply.com> <7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com> <200602052150.28732.pkraus@pelsupply.com> Message-ID: <5e58f2e40602051904s337222e1s@mail.gmail.com> On 06/02/06, Paul Kraus wrote: > Thanks for the fast response. This was exactly what I was looking for. One > last question how would I 'call the method keys'. from the example above. If b is a Tkinter.Button, then it means call b.keys(). eg: >>> from Tkinter import * >>> tk = Tk() >>> b = Button(tk, text='Hello world!') >>> b.keys() ['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength'] So, these are the possible things you can configure with a Tkinter.Button. Also, the online documentation at python.org is very good. I recommend going to http://www.python.org/doc/ and downloading the current documentation. You'll get a bunch of HTML files which you can put somewhere. Then set up a bookmark for the main index file. I have it on my browser's toolbar and I use it all the time :-) The Library Reference is particularly useful. For example, if you want to know about all the methods specific to lists, you can read the section on mutable sequence types: http://docs.python.org/lib/typesseq-mutable.html HTH! -- John. From andre.roberge at gmail.com Mon Feb 6 04:08:03 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sun, 5 Feb 2006 23:08:03 -0400 Subject: [Tutor] Documentation In-Reply-To: <200602052150.28732.pkraus@pelsupply.com> References: <200602052137.16539.pkraus@pelsupply.com> <7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com> <200602052150.28732.pkraus@pelsupply.com> Message-ID: <7528bcdd0602051908s3ac91c18s3a6954200d27dee7@mail.gmail.com> On 2/5/06, Paul Kraus wrote: > > >>> help(Tkinter.Button.configure) > > > > Help on method configure in module Tkinter: > > > > configure(self, cnf=None, **kw) unbound Tkinter.Button method > > Configure resources of a widget. > > > > The values for resources are specified as keyword > > arguments. To get an overview about > > the allowed keyword arguments call the method keys. > > > > > > Try it on your own! As a rule, stay away from methods that start with > > an underscore. > Thanks for the fast response. This was exactly what I was looking for. One > last question how would I 'call the method keys'. from the example above. To be honest ... I don`t know. I don't use Tkinter myself. Here's what I get from the help function: --------- >>> help(Tkinter.Button.keys) Help on method keys in module Tkinter: keys(self) unbound Tkinter.Button method Return a list of all resource names of this widget. ------- So, I would guess that, after creating a button, through something like aButton = Button(parent, text="Some label", command=some_action) You could do: resources = aButton.keys() There is a free book on using Tkinter to be found at http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html Another great resource is to be found on http://www.pythonware.com/library/index.htm You will find there a Tkinter reference book on-line (html version) or a downloadable one (pdf). Here's what I found by browsing... =========== The following dictionary method also works for widgets: keys() => list Return a list of all options that can be set for this widget. The name option is not included in this list (it cannot be queried or modified through the dictionary interface anyway, so this doesn't really matter). =========== You may have to wait until tomorrow to get your answer, when the "real tutors" are online ;-) Good luck! Andr? From govilakanksha at yahoo.com Mon Feb 6 06:54:53 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Sun, 5 Feb 2006 21:54:53 -0800 (PST) Subject: [Tutor] Debugger Needed Message-ID: <20060206055453.57344.qmail@web36504.mail.mud.yahoo.com> Hi, I am new to python, I want to know how to use a debugger and which debugger give a GUI . I am using Suse 9.1. Thanks Akanksha --------------------------------- Relax. Yahoo! Mail virus scanning helps detect nasty viruses! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060205/36223b04/attachment.html From samrobertsmith at gmail.com Mon Feb 6 08:42:33 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 5 Feb 2006 23:42:33 -0800 Subject: [Tutor] is there any tool like "run line or selection" in Pythonwin? In-Reply-To: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.com> References: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.com> Message-ID: <1d987df30602052342t33ec506ej12ed58e356342365@mail.gmail.com> I installed python in both Windows and Mac. I am very curious why the installation under Mac take so long time compared to that under Windows. Thanks, Linda From samrobertsmith at gmail.com Mon Feb 6 08:43:36 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 5 Feb 2006 23:43:36 -0800 Subject: [Tutor] Python in Mac Message-ID: <1d987df30602052343n6c29dd25xfda2c7ab0086804@mail.gmail.com> I installed python in both Windows and Mac. I am very curious why the installation under Mac take so long time compared to that under Windows. Thanks, Linda From dyoo at hkn.eecs.berkeley.edu Mon Feb 6 08:44:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Feb 2006 23:44:15 -0800 (PST) Subject: [Tutor] Debugger Needed In-Reply-To: <20060206055453.57344.qmail@web36504.mail.mud.yahoo.com> Message-ID: On Sun, 5 Feb 2006, Akanksha Govil wrote: > I am new to python, I want to know how to use a debugger and which > debugger give a GUI . Hi Akanksha, Have you looked at 'pdb' yet? http://www.python.org/doc/lib/module-pdb.html Several of the major Python IDEs also provide some kind of debugging support; you may want to check them out. Here's a good link to them: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments I've heard interesting things about Komodo and eric3, though I've never used them personally. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Mon Feb 6 08:55:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Feb 2006 23:55:30 -0800 (PST) Subject: [Tutor] installing python on windows and macs In-Reply-To: <1d987df30602052342t33ec506ej12ed58e356342365@mail.gmail.com> Message-ID: On Sun, 5 Feb 2006, linda.s wrote: > I installed python in both Windows and Mac. I am very curious why the > installation under Mac take so long time compared to that under > Windows. Hi Linda, But that's somewhat odd, because it should take zero time: Python's already installed under Mac OS X 10.3. *grin* Is this a really big problem for you? Installation is something that usually happens just once, so I'm sure the Python developers haven't done anything particularly focused to make installation on any platform blazingly fast. So, frankly, as long as the installation worked out ok, I wouldn't worry too much about this. Still if this does matter to you, let's see... can you be more specific about what version of Mac OS and what installation of Python you've tried? I made a flippant comment above, but I assume that you mean some other version of Mac OS (perhaps 9?) In order to evaluate what's happening, we need details about your system to advise better. And since your question is about speed, knowing what kinds of machines we're comparing against (CPU, RAM) would also be good, since your computer's raw performance is a significant factor. You might also want to talk with the MacPython folks, and you can give them numbers on how long the installation takes. (How long do you mean by "long"? Minutes, hours... days? *grin*) The folks on the macpython list might be able to corroborate that your situation is unusual, or they might be able to point out something that they know as an outstanding issue. They have a mailing list here: http://www.python.org/sigs/pythonmac-sig/ Good luck to you. From samrobertsmith at gmail.com Mon Feb 6 09:09:52 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Feb 2006 00:09:52 -0800 Subject: [Tutor] installing python on windows and macs In-Reply-To: References: <1d987df30602052342t33ec506ej12ed58e356342365@mail.gmail.com> Message-ID: <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> On 2/5/06, Danny Yoo wrote: > > > On Sun, 5 Feb 2006, linda.s wrote: > > > I installed python in both Windows and Mac. I am very curious why the > > installation under Mac take so long time compared to that under > > Windows. > > Hi Linda, > > But that's somewhat odd, because it should take zero time: Python's > already installed under Mac OS X 10.3. *grin* > > Is this a really big problem for you? Installation is something that > usually happens just once, so I'm sure the Python developers haven't done > anything particularly focused to make installation on any platform > blazingly fast. So, frankly, as long as the installation worked out ok, I > wouldn't worry too much about this. > > > Still if this does matter to you, let's see... can you be more specific > about what version of Mac OS and what installation of Python you've tried? > I made a flippant comment above, but I assume that you mean some other > version of Mac OS (perhaps 9?) In order to evaluate what's happening, we > need details about your system to advise better. And since your question > is about speed, knowing what kinds of machines we're comparing against > (CPU, RAM) would also be good, since your computer's raw performance is a > significant factor. > > You might also want to talk with the MacPython folks, and you can give > them numbers on how long the installation takes. (How long do you mean by > "long"? Minutes, hours... days? *grin*) The folks on the macpython list > might be able to corroborate that your situation is unusual, or they might > be able to point out something that they know as an outstanding issue. > They have a mailing list here: > > http://www.python.org/sigs/pythonmac-sig/ > > Good luck to you. > > Thanks for your kindness. The version of My Mac is Mac OX 10.4.4; I guess that Python 2.3.5 has been installed before. Now I tried to install Python 2.4.2; It works fine till "Make Install". After I reenter the terminal, I still saw Python 2.3.5 and 2.4.2. does not appear. Also, it is really boring to go through ./configure, make and make install. Why it is not as convenient as Windows? Sorry for any naive comments. Linda From ml.cyresse at gmail.com Mon Feb 6 09:09:18 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 6 Feb 2006 21:09:18 +1300 Subject: [Tutor] Threading + socket server (blocking IO) Message-ID: Hi all, About to embark on my first foray into threading, and rather unsure of initial approach. I have a basic UDPServer from SocketServer running using serve_forever(). I'd like to stick this in a thread where it can endlessly loop waiting for incoming packets, and pushing the received data into a list where it can be retrieved and operated on by another thread, until such time as the controlling app terminates it. Is this going to be possible? I've been reading about GIL and what not in the Tutor archives and this presentation here - http://starship.python.net/crew/aahz/OSCON2001/ but I'm a little unsure as to what is possible. Regards, Liam Clarke From alan.gauld at freenet.co.uk Mon Feb 6 09:53:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 08:53:56 -0000 Subject: [Tutor] Documentation References: <200602052137.16539.pkraus@pelsupply.com><7528bcdd0602051845x34405585q5638cf6f25d8f710@mail.gmail.com><200602052150.28732.pkraus@pelsupply.com> <7528bcdd0602051908s3ac91c18s3a6954200d27dee7@mail.gmail.com> Message-ID: <003701c62afa$dd547c50$0b01a8c0@xp> > There is a free book on using Tkinter to be found at > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html > >Another great resource is to be found on > http://www.pythonware.com/library/index.htm And a useful paper book is Tcl/Tk in a Nutshell You have to translate from native Tcl/Tk commands to their Tkinter equivalents but thats not too hard. But I find it the most concise guide to Tk and Tix that I know. However the man pages from which the Nutshell comes are also online at: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm So you may prefer to just browse those... Alan G. From alan.gauld at freenet.co.uk Mon Feb 6 10:02:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 09:02:44 -0000 Subject: [Tutor] is there any tool like "run line or selection" inPythonwin? References: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.com> <1d987df30602052342t33ec506ej12ed58e356342365@mail.gmail.com> Message-ID: <004301c62afc$18372470$0b01a8c0@xp> > I am very curious why the installation under Mac take so long time > compared to that under Windows. So am I. On my 600MHz iBook a new python install takes about the same time as it does on my 2GHz XP box. (around 3-5 minutes in both cases) How long did it take on your Mac? And how did you install it? You didn't pick up a source install by any chance? That would require coimpilation of the code as well as installing it. Alan G. From alan.gauld at freenet.co.uk Mon Feb 6 09:59:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 08:59:37 -0000 Subject: [Tutor] Debugger Needed References: <20060206055453.57344.qmail@web36504.mail.mud.yahoo.com> Message-ID: <003f01c62afb$a85357f0$0b01a8c0@xp> > I am new to python, I want to know how to use a debugger and which > debugger give a GUI . If you are new to Python but experienced in programming then you should find the pdb debugger is a lot like the GNU gdb one. Its not a GUI hiowever. (Although I beliebe you can get it to work with ddx etc... but I haven't tried) IDLE also has a somewhat cut down debugger built in and it is graphical but ugly! Other IDEs like Blackadder etc also feature debuggers. However in Python the most useful debugger is often the interactive prompt. If you run your program with python -i foo.py the program will stop inside the interpreter so that you can examine variables etc. coupled with judicial use of print statements you should rarely need the debugger The other thing to do with the >>> prompt is simply import your module and call the functions from the prompt. Again you can see the results by examing variables etc. HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lists at mostrom.pp.se Mon Feb 6 10:08:54 2006 From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=) Date: Mon, 6 Feb 2006 10:08:54 +0100 Subject: [Tutor] installing python on windows and macs In-Reply-To: <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> Message-ID: linda.s 2006-02-06 09:09: > Now I tried to install Python 2.4.2; It works fine till "Make > Install". After I reenter the terminal, I still saw Python 2.3.5 and > 2.4.2. does not appear. > Also, it is really boring to go through ./configure, make and make > install. Why it is not as convenient as Windows? Do you mean that you needed to compile Python ... well, you should have downloaded the binary distribution instead. jem -- Jan Erik Mostr?m, www.mostrom.pp.se From samrobertsmith at gmail.com Mon Feb 6 10:22:11 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Feb 2006 01:22:11 -0800 Subject: [Tutor] installing python on windows and macs In-Reply-To: References: <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> Message-ID: <1d987df30602060122g60d588a0g4a73ff60237586f1@mail.gmail.com> On 2/6/06, Jan Erik Mostr?m wrote: > linda.s 2006-02-06 09:09: > > > Now I tried to install Python 2.4.2; It works fine till "Make > > Install". After I reenter the terminal, I still saw Python 2.3.5 and > > 2.4.2. does not appear. > > Also, it is really boring to go through ./configure, make and make > > install. Why it is not as convenient as Windows? > > Do you mean that you needed to compile Python ... well, you should have > downloaded the binary distribution instead. > > jem > -- > Jan Erik Mostr?m, www.mostrom.pp.se Where is the binary Python 2.4.2 for Mac? I could not find it, Thanks! Linda From franz.steinhaeusler at gmx.at Mon Feb 6 11:12:04 2006 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Mon, 06 Feb 2006 11:12:04 +0100 Subject: [Tutor] Debugger Needed References: <20060206055453.57344.qmail@web36504.mail.mud.yahoo.com> <003f01c62afb$a85357f0$0b01a8c0@xp> Message-ID: <358eu1lphbo8jg62aqigtfveu3i42cnu28@4ax.com> On Mon, 6 Feb 2006 08:59:37 -0000, "Alan Gauld" wrote: >> I am new to python, I want to know how to use a debugger and which >> debugger give a GUI . > >If you are new to Python but experienced in programming then you should find >the pdb debugger is a lot like the GNU gdb one. Its not a GUI hiowever. >(Although I beliebe you can get it to work with ddx etc... but I haven't >tried) You can also look for Hap Debugger (Windows) on Sourceforge. A new "beautiful" Debugger is winpdb. Also on Sourceforge. -- Franz Steinhaeusler From kent37 at tds.net Mon Feb 6 12:11:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 06:11:17 -0500 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: References: Message-ID: <43E72ED5.7040805@tds.net> Liam Clarke wrote: > Hi all, > > About to embark on my first foray into threading, and rather unsure of > initial approach. I have a basic UDPServer from SocketServer running > using serve_forever(). I'd like to stick this in a thread where it can > endlessly loop waiting for incoming packets, and pushing the received > data into a list where it can be retrieved and operated on by another > thread, until such time as the controlling app terminates it. Threaded servers are supported by the standard library. Instead of using UDPServer use this class: class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass Then your request handler will be called in a separate thread. You don't need to queue the requests yourself, the server will create the thread and dispatch to it when a request is received. Kent From kent37 at tds.net Mon Feb 6 12:28:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 06:28:15 -0500 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: References: Message-ID: <43E732CF.3010604@tds.net> Liam Clarke wrote: > Is this going to be possible? I've been reading about GIL and what not > in the Tutor archives and this presentation here - > http://starship.python.net/crew/aahz/OSCON2001/ but I'm a little > unsure as to what is possible. Python has good support for multiple threads running on a single processor. The GIL prevents Python from effectively running multiple threads on multiple processors. You might also be interested in Twisted which provides industrial-strength servers using an asynchronous model rather than threading. There is an example of a simple UDP echo server here: http://twistedmatrix.com/projects/core/documentation/examples/echoserv_udp.py Kent From kent37 at tds.net Mon Feb 6 12:32:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 06:32:57 -0500 Subject: [Tutor] Documentation In-Reply-To: <200602052137.16539.pkraus@pelsupply.com> References: <200602052137.16539.pkraus@pelsupply.com> Message-ID: <43E733E9.8050001@tds.net> Paul Kraus wrote: > I have been working through a couple of books and learning alot. However I > can't seem to find any easy way to learn more about different methods and > commands. > > For instance what are all of the methods that can be applied to lists and what > do they do and how do they work. Or in TKinter what are all the different > things can I do with a button besides just setting the command and the text > and such. These are just examples. Chapter 2 of the Library Reference documents built-in functions (such as len() and sort()) and built-in types (such as string, list, dict). It is well worth reading and keeping handy as a reference. Most library modules are pretty well documented in the Library Reference as well. Tkinter is a bit of an exception. For Tkinter look here: http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ Kent From davholla2002 at yahoo.co.uk Mon Feb 6 14:11:28 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 6 Feb 2006 13:11:28 +0000 (GMT) Subject: [Tutor] Copy files In-Reply-To: <051d01c6268f$af64b770$0b01a8c0@xp> Message-ID: <20060206131128.19984.qmail@web25913.mail.ukl.yahoo.com> Alan, Thanks for that. I had the wrong file names, now it works, in case anyone is interested here is the code. I use it because at work I need to change different versions of sqlnet.ora :- def compare_files(file_name1, file_name2): x = filecmp.cmp (file_name1, file_name2) print x return x def change_files(file_1, file_2, cwd): yesorno = raw_input("Do you want them to be the same Y or N ") #file_1 = cwd+file_1 #file_2 = cwd+file_2 yesorno = string.upper(yesorno) if yesorno == 'Y': try: os.remove(file_2) print "removed file 2" except: print "could not remove file" try: shutil.copy(file_1, file_2) print "the copy part thinks it worked" except: print "it did not work" else: print "ok not changing anything" def did_it_work(file_1, file_2): #this is to debug the copy,only run if you are having problems afterchange = compare_files(file_1,file_2 ) if afterchange == True: print "the copy went fine" else: print "problem with the copy" + str(afterchange) #main import shutil import string import filecmp import os a = os.getcwd() print a file1 = "SQLNETpersonal.ORA" file2 = "SQLNETclients.ORA" file3 = "SQLNET.ORA" x = compare_files(file1,file3 ) if x == False: print file1 + " and "+ file3+ " are different" #print "test1 and test3 are different" change_files(file1, file3,a) #did_it_work(file1, file3) else: x = compare_files(file2,file3 ) if x == False: print file2 + " and " +file3 +" are different" change_files(file2, file3,a) #did_it_work(file2, file3) print "program finished" Alan Gauld wrote: > The only problem is that despite the fact that as the same user, > I can manually change these files (so I must have the right file > permissions ?) Can you do it from within python at the >>> prompt Use os.getcwd() to find out where you are Use os.chdir() to navigate Use os.listdir() to list the folder contents and use shutil.copy() to copy the files. Doing it manually from inside the >>> prompt should show up any problems. You can even try the filecomp call from in there too... >>> is a powerful tool. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------------------------------------------------------------------------------------------------------------------------------- "Then you will know the truth, and the truth will set you free." John 8:32 " As Pastor Niem?ller said, first they came for Piglet and I did not speak out because I was not a Disney character." http://www.telegraph.co.uk/opinion/main.jhtml?xml=/opinion/2005/10/04/do0402.xml "When the facts change, I change my opinions, what do you do sir ?" John Keynes. --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060206/87bd4226/attachment.html From pkraus at pelsupply.com Mon Feb 6 15:44:48 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Mon, 6 Feb 2006 09:44:48 -0500 Subject: [Tutor] GUI Development - Which toolkit Message-ID: <200602060944.48983.pkraus@pelsupply.com> I am developing applications that need to run without work on both windows and linux and was wondering what gui toolkits everyone uses and why. I have been looking at wxpython and tkinter. Thanks in advance, -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From pkraus at pelsupply.com Mon Feb 6 15:46:42 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Mon, 6 Feb 2006 09:46:42 -0500 Subject: [Tutor] IDE - Editors - Python Message-ID: <200602060946.42913.pkraus@pelsupply.com> Which editors does everyone use and why. Please keep the discussion to IDE's rather then any editors. I am well versed on Emacs and VI so anything beyond them would be appreciative. Why you like the editor and how it helps reduce your development time would be productive and helpfull. TIA, -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From kent37 at tds.net Mon Feb 6 17:35:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 11:35:42 -0500 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: <000d01c62b37$431a23a0$0200a8c0@kookaburra> References: <000d01c62b37$431a23a0$0200a8c0@kookaburra> Message-ID: <43E77ADE.3090105@tds.net> Matthew Webber wrote: >>>The GIL prevents Python from effectively running multiple threads on > > multiple processors. > > This statement is slightly misleading. You can run multiple threads on a > multi-processor system quite effectively, the limitation of the GIL is > simply that you can typically utilize only one processor at a time. Yeah, that's what I meant by 'effectively' ;) Thanks for the clarification. Kent From m_webber_sydney at yahoo.com.au Mon Feb 6 17:07:38 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Mon, 6 Feb 2006 16:07:38 -0000 Subject: [Tutor] Threading + socket server (blocking IO) Message-ID: <000e01c62b37$735f5120$0200a8c0@kookaburra> >> The GIL prevents Python from effectively running multiple threads on multiple processors. This statement is slightly misleading. You can run multiple threads on a multi-processor system quite effectively, the limitation of the GIL is simply that you can typically utilize only one processor at a time. From klappnase at freenet.de Mon Feb 6 18:45:48 2006 From: klappnase at freenet.de (Michael Lange) Date: Mon, 6 Feb 2006 18:45:48 +0100 Subject: [Tutor] GUI Development - Which toolkit In-Reply-To: <200602060944.48983.pkraus@pelsupply.com> References: <200602060944.48983.pkraus@pelsupply.com> Message-ID: <20060206184548.2a1ae177.klappnase@freenet.de> On Mon, 6 Feb 2006 09:44:48 -0500 Paul Kraus wrote: > I am developing applications that need to run without work on both windows and > linux and was wondering what gui toolkits everyone uses and why. > > I have been looking at wxpython and tkinter. > I have only used Tkinter so far, so I cannot say much about wx. Tkinter's biggest disadvantage is that some advanced widgets are missing, like a spreadsheet widget or a html viewer. There is also no built-in drag&drop support. A lot of these things are available by installing extension modules, though. If you don't need any of these Tkinter is worth a try; it is well documented, stable and easy to learn, and the biggest advantage over other toolits, it is included in the standard python distribution. If you want to use Tkinter you should also have a look at Tix, which is now included in python's windows installer (and also in any recent linux distro) and which adds a lot of nice extra widgets to Tkinter, like Combobox and Tree widget. A good place to find out more about Tkinter is the wiki: . I hope this helps Michael From w.damen at gmail.com Mon Feb 6 19:00:04 2006 From: w.damen at gmail.com (Rinzwind) Date: Mon, 6 Feb 2006 19:00:04 +0100 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <200602060946.42913.pkraus@pelsupply.com> References: <200602060946.42913.pkraus@pelsupply.com> Message-ID: <4677730602061000v292dddf4k49e3a05f0cfac45f@mail.gmail.com> When you code with Python there's only 1 editor Boa Constructor Even the name owns any other editor :-) http://boa-constructor.sourceforge.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060206/e0efc268/attachment.htm From tim at johnsons-web.com Mon Feb 6 18:16:18 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Feb 2006 08:16:18 -0900 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <200602060946.42913.pkraus@pelsupply.com> References: <200602060946.42913.pkraus@pelsupply.com> Message-ID: <20060206171618.GD1767@johnsons-web.com> * Paul Kraus [060206 06:04]: > Which editors does everyone use and why. Please keep the discussion to IDE's > rather then any editors. I am well versed on Emacs and VI so anything beyond > them would be appreciative. Why you like the editor and how it helps reduce > your development time would be productive and helpfull. Hello Paul: I guess by your mailer that you are using linux. If you were using windows, I would recommend pythonwin. Your use of "VI" suggest that you know about or maybe use the old *nix editor. Do you know about vim (Vi Much iMproved) and gvim, the x-compliant extension? If you don't, it is well worth investigating. An enormous wealth of resources out there... Xemacs is (in my opinion) "friendlier" in design than emacs. Again, an enormouse wealth of extensions.. Also, why not tell us if you program or intend to program in python only, of if you use a multiplicity of languages. FI, in my case, I generally use 4 (javascript, python, rebol, and lisp; plus formulating SQL queries and Markup) in different applications of the same venue. If you are programming in python only, there are several great python-specific "IDEs" available, and I'm sure that you will hear about them on this list. After all, an IDE is just an editor with extensions. I want control over my extensions. Ask yourself: How much control to I want? How many languages to I program in or intend to program in? To what extent does content management matter? How many other programmers am I working with? Avoid debuggers like a plague. If someone applies for a job with us and starts talking about their proficiency in debuggers, the interview stops right there and we keep looking. MTCW tim -- Tim Johnson http://www.alaska-internet-solutions.com From michele.alzetta at gmail.com Mon Feb 6 19:19:06 2006 From: michele.alzetta at gmail.com (Michele Alzetta) Date: Mon, 6 Feb 2006 19:19:06 +0100 Subject: [Tutor] Dictionaries versus classes Message-ID: <8079280b0602061019l4860fd1alf24d167efeb472eb@mail.gmail.com> Hi all, after a longish pause I've taken up my pet python project again (must say that the decisive factor was the discovery of how easy it is to code the GUI with QT designer and pyqt). The core of the problem I'm facing, however, is not the GUI, it is conceptual. In the end my program will have to create a printed representation of a certain number of "things" which are characterized by each having a time attribute (moment when they start, moment when they end); each "thing" will have to be filled in by a certain content, chosen from a user defined list of possibilities; however each thing will also have to have a series of other attributes ... which will change during the process of assigning content (for instance: once content 'A' is assigned to foo, bar immediately following may well change some attribute ... BUT the effect of content A on foo and bar may well be different from the effect of content B. Naturally if content A is present in a certain thing it can't be present in a contemporaneaous one... sounds a mess ? It is ... also, the rules by which A and B influence the content will have to be modifiable by the user.) At the moment I am collecting user input into a dictionary of lists. The question is: do you believe it would be better to code a series of functions to interact with my dictionary and keep data, attributes etc. in lists therein, or would it be more efficient to create an appointment class, create a new instance of each class for each appointment, and eventually store each instance in a dictionary ? Where could I read up something about relative advantages / disadvantages of each approach ? Thanks for any hints. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060206/ec7f0c2e/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Feb 6 19:38:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Feb 2006 10:38:17 -0800 (PST) Subject: [Tutor] installing python on windows and macs In-Reply-To: <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> Message-ID: > Thanks for your kindness. The version of My Mac is > Mac OX 10.4.4; I guess that Python 2.3.5 has been installed before. > Now I tried to install Python 2.4.2; Hi Linda, Ah, ok, then the long "installation" time you are seeing is perfectly normal, and the comparison you're making between the installations between Windows and Mac OS X is absolutely unfair. *grin* What you are doing in building Python 2.4.2 from source is "compiling" the software. Compilation is a process of taking the human-readable source code and turning it into machine code appropriate for your machine. This is a significant and very computationally expensive thing to do! In contrast, the Winows installer you've used is already in a compiled form. A fairer comparison involves installing a compiled "binary" package of Python 2.4. There is one available from: http://undefined.org/python/ > After I reenter the terminal, I still saw Python 2.3.5 and 2.4.2. does > not appear. Also, it is really boring to go through ./configure, make > and make install. Why it is not as convenient as Windows? The process is boring because it's not meant for end Mac OS X users. It's really meant for system administrators and those who are developing the Python core language. And for those who can't wait for others to prepare the nice, double-clicking installers. *grin* Since it sounds like you are doing some significant work on Mac OS X, I'll double my recommendation for you to talk with the Python/Macintosh community. Here's one of the better links I've seen so far: http://pythonmac.org/ From dyoo at hkn.eecs.berkeley.edu Mon Feb 6 19:48:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Feb 2006 10:48:29 -0800 (PST) Subject: [Tutor] IDE - Editors - Python In-Reply-To: <20060206171618.GD1767@johnsons-web.com> Message-ID: > Avoid debuggers like a plague. If someone applies for a job > with us and starts talking about their proficiency in > debuggers, the interview stops right there and we keep looking. Hi Tim, Seriously? I know that the implication is that sufficient test cases and design will ferret out bugs, but this attitude toward debuggers surprises me. Steve McConnell, author of Code Complete, makes it a point to recommend running any new code through a debugger just to force the programmer to dig though the abstractions to see what the program's actually doing at a low level. In particular, I've found a debugger invaluable in diving through old C code that I have not written. Admittedly, I don't use debuggers in Python, but I do see the value in forcing oneself to jump levels of abstraction. But maybe this approach is obsolete now and I'm just an old fuddy-duddy. *grin* From andre.roberge at gmail.com Mon Feb 6 19:59:30 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 6 Feb 2006 14:59:30 -0400 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <20060206171618.GD1767@johnsons-web.com> References: <200602060946.42913.pkraus@pelsupply.com> <20060206171618.GD1767@johnsons-web.com> Message-ID: <7528bcdd0602061059t112f4e46l901e16c14c350a6f@mail.gmail.com> On 2/6/06, Tim Johnson wrote: > * Paul Kraus [060206 06:04]: > > Which editors does everyone use and why. Please keep the discussion to IDE's > > rather then any editors. I am well versed on Emacs and VI so anything beyond > > them would be appreciative. Why you like the editor and how it helps reduce > > your development time would be productive and helpfull. > > Hello Paul: > > I guess by your mailer that you are using linux. If you were using > windows, I would recommend pythonwin. > I'm programming under Windows and I haven't found anything better than Stani's Python Editor (spe). It should be cross-platform. I've seen others recommend eclipse+pydev. Andr? From kent37 at tds.net Mon Feb 6 20:11:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 14:11:26 -0500 Subject: [Tutor] Dictionaries versus classes In-Reply-To: <8079280b0602061019l4860fd1alf24d167efeb472eb@mail.gmail.com> References: <8079280b0602061019l4860fd1alf24d167efeb472eb@mail.gmail.com> Message-ID: <43E79F5E.5050606@tds.net> Michele Alzetta wrote: > In the end my program will have to create a printed representation of a > certain number of "things" which are characterized by each having a time > attribute (moment when they start, moment when they end); each "thing" > will have to be filled in by a certain content, chosen from a user > defined list of possibilities; however each thing will also have to have > a series of other attributes ... which will change during the process of > assigning content (for instance: once content 'A' is assigned to > foo, bar immediately following may well change some attribute ... BUT > the effect of content A on foo and bar may well be different from the > effect of content B. Naturally if content A is present in a certain > thing it can't be present in a contemporaneaous one... sounds a mess ? > It is ... also, the rules by which A and B influence the content will > have to be modifiable by the user.) > > At the moment I am collecting user input into a dictionary of lists. The > question is: do you believe it would be better to code a series of > functions to interact with my dictionary and keep data, attributes etc. > in lists therein, or would it be more efficient to create an appointment > class, create a new instance of each class for each appointment, and > eventually store each instance in a dictionary ? I don't understand your requirements, but I would think the choice would be between a list of dicts and a list of custom classes. I don't see how the dict of lists would work. Do you have parallel lists, one for each attribute? IMO that is generally a bad design, the attributes should be grouped somehow. It sounds like an appointment class might help, it would give you a place to put the code that operates on appointments and give you more convenient access to attributes. Probably a Rule class would help too. You could try using a dict to represent an appointment - the simplest thing that could possibly work. If you have to create a bunch of functions that operate on a single appointment at a time, then switch to a class-based implementation. Kent From mhansen at cso.atmel.com Mon Feb 6 20:24:26 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon, 06 Feb 2006 12:24:26 -0700 Subject: [Tutor] IDE - Editors - Python In-Reply-To: References: Message-ID: <43E7A26A.6060404@cso.atmel.com> > Subject: > [Tutor] IDE - Editors - Python > From: > Paul Kraus > Date: > Mon, 6 Feb 2006 09:46:42 -0500 > To: > tutor at python.org > > To: > tutor at python.org > > > Which editors does everyone use and why. Please keep the discussion to IDE's > rather then any editors. I am well versed on Emacs and VI so anything beyond > them would be appreciative. Why you like the editor and how it helps reduce > your development time would be productive and helpfull. > > TIA, I use VIM, and sometimes Komodo. The personal edition of Komodo is ~$30. I like the debugging and the output window in Komodo. I suppose I could get VIM to do this, but I haven't looked into it enough. Many swear by Eric3, WingIDE, SPE, or Dr. Python. I want to take a another look at Eclipse and PyDev. At the time I looked at PyDev, it was still in it's infancy. Personally, I'd stick to VIM or Emacs instead of messing around with IDEs. Mike From ianjones at umich.edu Mon Feb 6 20:12:27 2006 From: ianjones at umich.edu (Ian Jones) Date: Mon, 06 Feb 2006 14:12:27 -0500 Subject: [Tutor] installing python on windows and macs References: <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> <1d987df30602060122g60d588a0g4a73ff60237586f1@mail.gmail.com> Message-ID: In article <1d987df30602060122g60d588a0g4a73ff60237586f1 at mail.gmail.com>, "linda.s" wrote: > Where is the binary Python 2.4.2 for Mac? I could not find it, > Thanks! You can download a Mac installer for Python 2.4.1 here: http://undefined.org/python/ If you're on Tiger (OS X 10.4), you should also install the TigerPython24Fix from that page. There are a number of prebuilt Mac package binaries here (for example, PIL, wxPython, matplotlib): http://pythonmac.org/packages/ There is no Python 2.4.2 installer yet -- I think that's because people are busy working on the Mac-Intel-PPC ("Universal Binary") port of Python. From alan.gauld at freenet.co.uk Mon Feb 6 20:26:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 19:26:56 -0000 Subject: [Tutor] installing python on windows and macs References: <1d987df30602052342t33ec506ej12ed58e356342365@mail.gmail.com> <1d987df30602060009u46dc4353h3d4f6e9693342132@mail.gmail.com> Message-ID: <001701c62b53$4afb7030$0b01a8c0@xp> > Also, it is really boring to go through ./configure, make and make > install. Why it is not as convenient as Windows? Aha! Thats because you are installing from source. If you visit the MacPython site you will find a normal Mac install package. You just drop it on the Desktop (or anywhere else!) and click on it to start the installer whixch drops all the bits in the right place. That should be much faster. Alan G. From alan.gauld at freenet.co.uk Mon Feb 6 20:29:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 19:29:12 -0000 Subject: [Tutor] Debugger Needed References: <20060206055453.57344.qmail@web36504.mail.mud.yahoo.com><003f01c62afb$a85357f0$0b01a8c0@xp> <358eu1lphbo8jg62aqigtfveu3i42cnu28@4ax.com> Message-ID: <003201c62b53$9edf1da0$0b01a8c0@xp> > A new "beautiful" Debugger is winpdb. > Also on Sourceforge. It looked nice and I tried it a few months back but it hung up on me a few times so I left it to "mature" for later.. :-) Alan G. From alan.gauld at freenet.co.uk Mon Feb 6 20:32:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 19:32:11 -0000 Subject: [Tutor] GUI Development - Which toolkit References: <200602060944.48983.pkraus@pelsupply.com> Message-ID: <003a01c62b54$070c9470$0b01a8c0@xp> >I am developing applications that need to run without work on both windows >and > linux and was wondering what gui toolkits everyone uses and why. > > I have been looking at wxpython and tkinter. If you just wqant to wrap up some scropts Tkinter is probably slightly easier to use (IMHO), but it doesn't look as nice. wxPython looks better and is only slightly more complex. But it does have a couple of GUI builder options in the shape of Glade and PythonCard. If you want to build full blown GUI apps then WxPython is the way to go. But search the archives, this gets debated at least every 6 months or so :-) Alan G. From alan.gauld at freenet.co.uk Mon Feb 6 20:38:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 19:38:23 -0000 Subject: [Tutor] IDE - Editors - Python References: <200602060946.42913.pkraus@pelsupply.com> Message-ID: <003e01c62b54$e4a05d80$0b01a8c0@xp> > Which editors does everyone use and why. Please keep the discussion to > IDE's Another hotly debated topic. What do you define as requyirements of an IDE? To me Unix is the best IDE I've ever used, but others would challenge my definition of an IDE... > rather then any editors. I am well versed on Emacs and VI so anything > beyond OK, Emacs could be argueed as an IDE if you install pythonmode. vim in turn has excellent Python support if you get the version with built-in Python for macro writing. Personally I use emacs on Unicx and vim on Windows and on Mac I use both as the mood takes me! > them would be appreciative. Why you like the editor and how it helps > reduce > your development time would be productive and helpfull. Other Python tools I have used include Scite on Windows - the editor portion of Pyhonwin. Glade and Boa Constructor both get good write-ups. Kimodo and Blackadder are also both good but commercial. NetBeans can speak Jython but doesn't offer the Python programmer much beyomd the editor to be honest. But personally my preferred environment is vim and a bash shell under cygwin on XP. Or, less often, xemacs with python mode on Linux. HTH, Alan G. From marilyn at deliberate.com Mon Feb 6 21:18:10 2006 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon, 6 Feb 2006 12:18:10 -0800 (PST) Subject: [Tutor] IDE - Editors - Python In-Reply-To: Message-ID: On Mon, 6 Feb 2006, Danny Yoo wrote: > > Avoid debuggers like a plague. If someone applies for a job > > with us and starts talking about their proficiency in > > debuggers, the interview stops right there and we keep looking. I can see that bragging about "proficiency in debuggers" would be a strange tactic in an interview, demonstrating an off-center focus. But the debugger is sure handy now and then. I try to *think* first. That usually finds the problem. Sometimes one or two print statements or an assert sorts it all out. But, sometimes I'm stuck, and using the debugger is the quickest way to unstick me. So you wouldn't hire me? Your loss. :^) While people are talking like this, and about IDE's, the thing I miss in the Python debugger is the ability to attach commands to a breakpoint. Does anyone know how to do that? I use Linux and keystroked emacs to avoid mousing. And I use a macro in emacs to get around not knowing how to attach commands to breakpoints. Marilyn > > Hi Tim, > > Seriously? I know that the implication is that sufficient test cases and > design will ferret out bugs, but this attitude toward debuggers surprises > me. Steve McConnell, author of Code Complete, makes it a point to > recommend running any new code through a debugger just to force the > programmer to dig though the abstractions to see what the program's > actually doing at a low level. > > In particular, I've found a debugger invaluable in diving through old C > code that I have not written. Admittedly, I don't use debuggers in > Python, but I do see the value in forcing oneself to jump levels of > abstraction. But maybe this approach is obsolete now and I'm just an old > fuddy-duddy. *grin* > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- From pkraus at pelsupply.com Mon Feb 6 21:34:34 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Mon, 6 Feb 2006 15:34:34 -0500 Subject: [Tutor] First Gui App - Please scrutinize Message-ID: <200602061534.34407.pkraus@pelsupply.com> This is my first gui application. It just takes a percentage and then based on some options calculates a new price. ----------------------------------- #!/usr/bin/python from Tkinter import * class Application( Frame ): """ Price Calc GUI """ def __init__( self, master): Frame.__init__( self, master ) self.grid() self.costprice = 0.0 self.listprice = 0.0 self.margmarkup = 0.0 self.formula = '' self.mmradial = IntVar() self.costlistradial = IntVar() self.create_widgets() def create_widgets( self ): self.marginormarkup() self.entryboxes() self.costlist() # Calculate Button self.b_calc = Button( self ) self.b_calc[ 'text' ] = 'Calculate' self.b_calc[ 'command' ] = self.calculate self.b_calc.grid(row=10,column=0) def marginormarkup(self): # Calc using margin or markup Label( self, text = 'Margin or Markup...').grid(row=0,column=0,sticky=W) Radiobutton( self, text = 'Margin', variable = self.mmradial, command = self.setstatusmm, value = 1).grid(row=1,column=0,sticky=W) Radiobutton( self, text = 'Mark-Up', variable = self.mmradial, command = self.setstatusmm, value = 0).grid(row=2,column=0,sticky=W) self.e_marginmarkup = Entry( self ) self.e_marginmarkup.grid(row=3,column=0,sticky=W) Label( self, text = 'Percentage').grid(row=3,column=1,sticky=W) self.mmradial.set(1) def costlist(self): # From Radial Label( self, text = 'Calculations Based On...').grid(row=4,column=0,sticky=NW) self.test = Radiobutton( self, text = 'Cost', variable = self.costlistradial, value = 1, command = self.setstatus).grid(row=5,column=0,sticky=W) self.test = Radiobutton( self, text = 'List', variable = self.costlistradial, value = 0, command = self.setstatus).grid(row=6,column=0,sticky=W) self.costlistradial.set(1) self.setstatus() def entryboxes(self): # Entry Boxes Cost List Result self.e_cost = Entry( self ) self.e_list = Entry( self ) Label(self, text='Cost').grid(row=7,column=1,sticky=W) self.e_cost.grid(row=7,column=0,sticky=W) Label(self, text='List').grid(row=8,column=1,sticky=W) self.e_list.grid(row=8,column=0,sticky=W) def setstatusmm( self ): if ( not self.costlistradial.get()): self.mmradial.set(0) def setstatus( self ): self.delentryboxes() if (self.costlistradial.get()): self.e_list['state'] = 'disabled' self.e_cost['state'] = 'normal' else: self.e_cost['state'] = 'disabled' self.e_list['state'] = 'normal' self.mmradial.set(0) self.e_list.delete(0,END) self.e_cost.delete(0,END) self.e_marginmarkup.delete(0,END) def delentryboxes( self ): boxes = [ self.e_list, self.e_cost, self.e_marginmarkup ] for ebox in boxes: ebox['state'] = 'normal' ebox.delete(0,END) def calculate( self ): equation = None target = None costa = float(self.e_cost.get()) lista = float(self.e_lista.get()) mma = float(self.e_marginmarkup.get())/100 if (self.mmradial.get()): ### If Margin if ( self.costlistradial.get() ): equation = costa / ( 1 - mma) target = self.e_list else: ### If Markup if ( self.costlistradial.get() ): equation = cost + ( cost * mma ) target = self.e_list else: equation = list - (list * mma) target = self.e_cost target['state'] = 'normal' target.delete(0,END) target.insert(0,equation) target['state'] = 'readonly' root = Tk() root.title('Price Calculations') root.geometry( '200x225' ) pricecalcgui = Application(root) root.mainloop() From 3dbernard at gmail.com Mon Feb 6 21:41:13 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 6 Feb 2006 15:41:13 -0500 Subject: [Tutor] Changing instance attributes in different threads Message-ID: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> Hello, I have an instance attribute (a few characters string) that two separate threads may change, potentially both at the same time. My program doesn't implement thread safety for this particular task. So far I have never run into issues with this, but I have been reading about data corruption when two threads try to write to the same data at once. I'm just about to deploy my program over 70 computers, so now I'm having some seconds thoughts of dread. Should changing instance attributes be done with maximum thread safety? That is, to use some sort of queue (like the Queue class) so that all changes to the attribute goes through this queue and can never happen concurrently? Thanks in advance Bernard From tim at johnsons-web.com Mon Feb 6 21:55:34 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Feb 2006 11:55:34 -0900 Subject: [Tutor] IDE - Editors - Python In-Reply-To: References: Message-ID: <20060206205534.GF1767@johnsons-web.com> * Marilyn Davis [060206 11:30]: > On Mon, 6 Feb 2006, Danny Yoo wrote: > > > > Avoid debuggers like a plague. If someone applies for a job > > > with us and starts talking about their proficiency in > > > debuggers, the interview stops right there and we keep looking. > > I can see that bragging about "proficiency in debuggers" would be a > strange tactic in an interview, demonstrating an off-center focus. Hi Marilyn: > But the debugger is sure handy now and then. I try to *think* first. > That usually finds the problem. Sometimes one or two print statements > or an assert sorts it all out. But, sometimes I'm stuck, and using > the debugger is the quickest way to unstick me. I've never had to use a debugger in python..... "C", well that's another issue entirely .... As I write, I'm not yet seeing my reply to Danny, but you should probably see it as you read this. That should answer your questions and comments.... > So you wouldn't hire me? Your loss. :^) :-) But youre focus isn't off-center is it? > While people are talking like this, and about IDE's, the thing I miss > in the Python debugger is the ability to attach commands to a > breakpoint. Does anyone know how to do that? > > I use Linux and keystroked emacs to avoid mousing. And I use a macro > in emacs to get around not knowing how to attach commands to > breakpoints. On emacs I use simple output stubs for debugging. I *definitely* agree regarding keystrokes as opposed to mousing. But it is nice to have both. On a related note, a few years ago, the local Electric Utility sent its entire Autocad Tech staff to a training session where they were trained to use Cad without the mouse. Following the session, they found that they had a 15% increase in productivity. I borrowed the tag from Danny. I probably use it a little differently than he does. Maybe I should use Cheers tim > Marilyn > > > > > Hi Tim, > > > > Seriously? I know that the implication is that sufficient test cases and > > design will ferret out bugs, but this attitude toward debuggers surprises > > me. Steve McConnell, author of Code Complete, makes it a point to > > recommend running any new code through a debugger just to force the > > programmer to dig though the abstractions to see what the program's > > actually doing at a low level. > > > > In particular, I've found a debugger invaluable in diving through old C > > code that I have not written. Admittedly, I don't use debuggers in > > Python, but I do see the value in forcing oneself to jump levels of > > abstraction. But maybe this approach is obsolete now and I'm just an old > > fuddy-duddy. *grin* > > > > _______________________________________________ > > 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 -- Tim Johnson http://www.alaska-internet-solutions.com From nephish at xit.net Mon Feb 6 22:29:49 2006 From: nephish at xit.net (nephish) Date: Mon, 06 Feb 2006 15:29:49 -0600 Subject: [Tutor] question about ascii and bytes Message-ID: <1139261389.14662.7.camel@localhost.localdomain> ok, so i have sparce documentation from a server that i need to make a socket connection with. the server wants to get info a certain way. Each message has to start with an ascii "STX" (literally the three letters, not the standart ascii 'STX') then it has to have another four bytes that give the length of the message, then the message itself, then end with an ascii "ENX" (again,the three letters, not the ascii character "ETX" ). So here is where the biggest gap in my understanding is... how do i send ascii characters ? the docs say that if the password is not 24 bytes long, the other bytes must be filled with null values. How do i do that ? What is a null value? python strings are ascii already , right ? would this be as simple as simply passing the string to the socket.send('pythonAsciiString') ? thanks for any tips or links for documentation . sk From john at fouhy.net Mon Feb 6 23:05:40 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 7 Feb 2006 11:05:40 +1300 Subject: [Tutor] First Gui App - Please scrutinize In-Reply-To: <200602061534.34407.pkraus@pelsupply.com> References: <200602061534.34407.pkraus@pelsupply.com> Message-ID: <5e58f2e40602061405o6b0003b1w@mail.gmail.com> On 07/02/06, Paul Kraus wrote: > This is my first gui application. It just takes a percentage and then based on > some options calculates a new price. Ok.. A few minor comments --- > class Application( Frame ): > """ Price Calc GUI """ > def __init__( self, master): > Frame.__init__( self, master ) > self.grid() When I'm programming in Tkinter, the way I generally think is "Containers (generally frames) create and place their components." In particular, this means I would never write a line like "self.grid()". The reason for this is because, with more complicated layouts, you will want to use nested frames to package widgets together. If you can combine several widgets together to make something nifty, you may want to use it in several places, or in different progams. But if that "megawidget" has a call to grid() itself, that seriously restricts your ability to reuse it (what if you want to pack() it?). > # Calculate Button > self.b_calc = Button( self ) > self.b_calc[ 'text' ] = 'Calculate' > self.b_calc[ 'command' ] = self.calculate > self.b_calc.grid(row=10,column=0) Why not self.b_calc = Button(self, text='Calculate', command=self.calculate)? And why save it as self.b_calc at all, since you don't use it? > self.test = Radiobutton( self, text = 'Cost', variable = > self.costlistradial, value = 1, command = > self.setstatus).grid(row=5,column=0,sticky=W) > self.test = Radiobutton( self, text = 'List', variable = > self.costlistradial, value = 0, command = > self.setstatus).grid(row=6,column=0,sticky=W) Why are you assigning these to self.test? (in particular, you realise that the results of these grid() calls will be None?) > if (self.costlistradial.get()): > self.e_list['state'] = 'disabled' > self.e_cost['state'] = 'normal' My preference is to use DISABLED and NORMAL (the Tkinter constants), rather than 'disabled' and 'normal'. Just in case they ever change... HTH... -- John. From tim at johnsons-web.com Mon Feb 6 23:16:11 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Feb 2006 13:16:11 -0900 Subject: [Tutor] IDE - Editors - Python In-Reply-To: References: <20060206171618.GD1767@johnsons-web.com> Message-ID: <20060206221611.GG1767@johnsons-web.com> * Danny Yoo [060206 09:57]: > > Avoid debuggers like a plague. If someone applies for a job > > with us and starts talking about their proficiency in > > debuggers, the interview stops right there and we keep looking. > > Hi Tim, Hey Danny: > Seriously? I know that the implication is that sufficient test cases and Not entirely seriously Danny. Did you notice the tag? What I am getting at is a preoccuption with debuggers to a fault, and we've seen it all too often. > design will ferret out bugs, but this attitude toward debuggers surprises > me. Steve McConnell, author of Code Complete, makes it a point to > recommend running any new code through a debugger just to force the > programmer to dig though the abstractions to see what the program's > actually doing at a low level. Actually, that is where I would be digging out a debugger. If I had to work off of someone else's code base. I'd consider that to be a more efficient way of tracking the process flow without modifying the original code. > In particular, I've found a debugger invaluable in diving through old C > code that I have not written. Definitely! > Admittedly, I don't use debuggers in > Python, but I do see the value in forcing oneself to jump levels of > abstraction. But maybe this approach is obsolete now and I'm just an old > fuddy-duddy. *grin* You're not. Just look for *my* s tj -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at freenet.co.uk Mon Feb 6 23:03:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 22:03:38 -0000 Subject: [Tutor] IDE - Editors - Python References: <200602060946.42913.pkraus@pelsupply.com> <20060206171618.GD1767@johnsons-web.com> Message-ID: <005301c62b69$2f59e9e0$0b01a8c0@xp> > Avoid debuggers like a plague. If someone applies for a job > with us and starts talking about their proficiency in > debuggers, the interview stops right there and we keep looking. grin noted but seriously, why? I tend to take the opposite approach. A good understanding of debuggers and how to use them will speed up the productivity of any developer, often by a factor of two or three - much faster to set a breakpoint and watch than to create multiple print statements and then take them all out again after laboriously peering at lots of data. OTOH much faster to insert one or two well chosen print statements and find the bug rather than crank up a debugger. But if you need more than a couple of prints then its probably faster to import pdb... And of course scriptable debuggers are a great testing tool! What has gotten debuggers a bad name is the trend with modern graphical debuggers to just blindly step through the code line by line. Now that is seriously inefficient! Its one reason I tend to use raw text debuggers like gdb or dbx rather than the GUI variants - the te,mptattion to laziness is avoided. Alan g. From kent37 at tds.net Mon Feb 6 23:13:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 17:13:43 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> Message-ID: <43E7CA17.1030808@tds.net> Bernard Lebel wrote: > Hello, > > I have an instance attribute (a few characters string) that two > separate threads may change, potentially both at the same time. > My program doesn't implement thread safety for this particular task. > > So far I have never run into issues with this, but I have been reading > about data corruption when two threads try to write to the same data > at once. I'm just about to deploy my program over 70 computers, so now > I'm having some seconds thoughts of dread. > > Should changing instance attributes be done with maximum thread > safety? That is, to use some sort of queue (like the Queue class) so > that all changes to the attribute goes through this queue and can > never happen concurrently? Are you talking about a simple assignment like self.x = 'abc'? If there is no Python code invoked by setting the attribute, I think the attribute will always be correctly set to the value from one of the threads. In this case the setattr will happen in a single Python byte code and it will be atomic. In other words, both of the sets will succeed and which ever one happens last will persist. If you *care* which of the setattrs succeeds, then you have a race condition that you need to address somehow. If Python code is invoked by setting the attribute then you could have a problem. This could happen, for example, if the attribute is a property, if the class (or one of its base classes) overrides __setattr__(), and probably in several other ways I haven't thought of. In this case you need to look at whether the Python code is thread-safe. Kent From alan.gauld at freenet.co.uk Mon Feb 6 23:15:13 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 22:15:13 -0000 Subject: [Tutor] Dictionaries versus classes References: <8079280b0602061019l4860fd1alf24d167efeb472eb@mail.gmail.com> Message-ID: <006701c62b6a$cdab2130$0b01a8c0@xp> > In the end my program will have to create a printed representation of a > certain number of "things" ... each thing will also have to have a series > of > other attributes ... which will change during the process of assigning > content (for instance: once content 'A' is assigned to foo, bar > immediately > following may well change some attribute ... Things with attributes and varying behaviour is almost a definition of objects. There may be a clue there... > contemporaneaous one... sounds a mess ? It is ... also, the rules > by which A and B influence the content will have to be modifiable > by the user.) Dynamic rules are always tricky to get right however there are a couple of design patterns that can be adapted in the form of the visitor and strategy patterns. If your visitor pattern uses a strategy you get a customisable set of behaviours. But it depends a little on just how complex the rules get... > question is: do you believe it would be better to code a series of > functions > to interact with my dictionary and keep data, attributes etc. in lists Almost never. If its only one or two functions maybe but the minute it gets beyond a couple a class will almost always be better. The overhead of a Python class definition is tiny compared to the benefits. > Where could I read up something about relative advantages / disadvantages > of each approach ? General OO design books are the only place I suspect. Try it both ways and learn from experience is the other alternative. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From 3dbernard at gmail.com Mon Feb 6 23:29:59 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 6 Feb 2006 17:29:59 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E7CA17.1030808@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> Message-ID: <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> hi Kent, See [Bernard] below. On 2/6/06, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > I have an instance attribute (a few characters string) that two > > separate threads may change, potentially both at the same time. > > My program doesn't implement thread safety for this particular task. > > > > So far I have never run into issues with this, but I have been reading > > about data corruption when two threads try to write to the same data > > at once. I'm just about to deploy my program over 70 computers, so now > > I'm having some seconds thoughts of dread. > > > > Should changing instance attributes be done with maximum thread > > safety? That is, to use some sort of queue (like the Queue class) so > > that all changes to the attribute goes through this queue and can > > never happen concurrently? > > Are you talking about a simple assignment like self.x = 'abc'? [Bernard] Yes. > If there is no Python code invoked by setting the attribute, I think the > attribute will always be correctly set to the value from one of the > threads. In this case the setattr will happen in a single Python byte > code and it will be atomic. In other words, both of the sets will > succeed and which ever one happens last will persist. > > If you *care* which of the setattrs succeeds, then you have a race > condition that you need to address somehow. > > If Python code is invoked by setting the attribute then you could have a > problem. [Bernard] This is where I'm getting a bit confused..... changing the attribute doesn't automatically invoke code. But at various points in the program, the value of this attribute is tested, and if matches certain strings, a function is called. Example: - Class instance Bernard has attribute "name", whose value is "bernard". - A function in a thread tests the value of "name". If "name" == "bernard", do nothing. - A function in another thread, for some reason, changes "name" to "bob". - The first function, few moments later, tests again the value of "name". It see that the value has changed from "bernard" to "bob", and this change causes the function to take an action. Is that what you mean by "invoking" code? This could happen, for example, if the attribute is a property, > if the class (or one of its base classes) overrides __setattr__(), and > probably in several other ways I haven't thought of. In this case you > need to look at whether the Python code is thread-safe. [Bernard] There is nothing of that sort in my program. Classes are all "independent", that is, are not derived from another class. A handful of their attributes like the one I described are changed at various moments, only to be tested by other functions, in order to control the flow of execution. Bernard From alan.gauld at freenet.co.uk Mon Feb 6 23:26:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Feb 2006 22:26:51 -0000 Subject: [Tutor] question about ascii and bytes References: <1139261389.14662.7.camel@localhost.localdomain> Message-ID: <008601c62b6c$6dccf9d0$0b01a8c0@xp> > the server wants to get info a certain way. Each message has to start > with an ascii "STX" (literally the three letters, not the standart ascii > 'STX') then it has to have another four bytes that give the length of > the message, then the message itself, then end with an ascii "ENX" > (again,the three letters, not the ascii character "ETX" ). > > So here is where the biggest gap in my understanding is... how do i send > ascii characters ? You can just send the string of characters or you could use the struct module to compose the byte string with more control. But in this case a simple string should suffice. > the docs say that if the password is not 24 bytes long, the other bytes > must be filled with null values. How do i do that ? What is a null > value? Check an ASCII table but I beliebe ASCII NULL is zero, so null = chr(0) should get you a null character. Or even use escape characters: null = '\x00 or even null = '\0' Then pad your string with target = 24 mystring = 'spam' padding = null * (target - len(mystring)-6) passwd = 'STX' + mystring + padding + 'ENX' > python strings are ascii already , right ? would this be as simple as > simply passing the string to the socket.send('pythonAsciiString') ? Yep, or you could specify UTF8 if you want to protect against any risk of Python becoming 16bit Unicode by default! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Feb 7 00:34:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 18:34:18 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> Message-ID: <43E7DCFA.6070905@tds.net> Bernard Lebel wrote: > Example: > > - Class instance Bernard has attribute "name", whose value is "bernard". > - A function in a thread tests the value of "name". If "name" == > "bernard", do nothing. > - A function in another thread, for some reason, changes "name" to "bob". > - The first function, few moments later, tests again the value of > "name". It see that the value has changed from "bernard" to "bob", and > this change causes the function to take an action. > > Is that what you mean by "invoking" code? No, it's not what I meant, I was talking about constructs that can cause an assignment like self.x = 1 to directly call code that you wrote. It sounds like you are not doing that. It sounds like you have some attributes that you are using as flags to allow one thread to control another. There are definitely some pitfalls here. You probably want to use threading.Condition or Queue.Queue to communicate between the threads. Can you give more details of what you are trying to do? Kent From rshepard at appl-ecosys.com Tue Feb 7 02:51:00 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Mon, 6 Feb 2006 17:51:00 -0800 (PST) Subject: [Tutor] Sharing Variables Across Modules Message-ID: I'm developing a wxPython-based application. The UI is a notebook, with the contents of each page in a separate module. In one module (modelPage.py), I have defined the class modModel, which is an instance of a wx.Panel class. Within modModel is a text control widget named tcName. The main module, eikos.py, imports modModel from modPage.py. The main module has two classes: MyNotebook (subclassed from wx.Notebook) and MyFrame, which contains the notebook and menus. The File->New menu calls the method OnFileNew. This displays a directory dialog so the user can select the directory in which the new file is to be placed. Then it displays a text entry dialog for the name of the new file. I am able to enter the new file name and it is correctly assigned to the variable, projname. What I have not been able to do is have that same filename displayed in the text control widget, tcName. Here is OnFileNew from the main module: def OnFileNew(self, event): """ Create a new file and open it.""" self.dirname = '' wd = wx.DirDialog(self, "Chose the default directory", ".", style=wx.DD_NEW_DIR_BUTTON) if wd.ShowModal() == wx.ID_OK: dirname = wd.GetPath() ted = wx.TextEntryDialog(self, "Enter the project name", "New Project Name", "", style=wx.RAISED_BORDER|wx.OK|wx.CANCEL) if ted.ShowModal() == wx.ID_OK: projname = ted.GetValue() tcName = self.modModel.tcName tcName.WriteText(self, projname) ted.Destroy() wd.Destroy() While projname has the correct string, tcName remains undefined: File "eikos.py", line 272, in OnFileNew tcName = self.modModel.tcName AttributeError: 'MyFrame' object has no attribute 'modModel' How do I make tcName visible in eikos.py when it's defined in modelPage.py? Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From andre.roberge at gmail.com Tue Feb 7 03:24:17 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 6 Feb 2006 22:24:17 -0400 Subject: [Tutor] Sharing Variables Across Modules In-Reply-To: References: Message-ID: <7528bcdd0602061824v5012ced2vcdcf19457dcb6f1@mail.gmail.com> On 2/6/06, Rich Shepard wrote: > I'm developing a wxPython-based application. The UI is a notebook, with the > contents of each page in a separate module. In one module (modelPage.py), I > have defined the class modModel, which is an instance of a wx.Panel class. > Within modModel is a text control widget named tcName. > > The main module, eikos.py, imports modModel from modPage.py. The main > module has two classes: MyNotebook (subclassed from wx.Notebook) and MyFrame, > which contains the notebook and menus. > > The File->New menu calls the method OnFileNew. This displays a directory > dialog so the user can select the directory in which the new file is to be > placed. Then it displays a text entry dialog for the name of the new file. > > I am able to enter the new file name and it is correctly assigned to the > variable, projname. What I have not been able to do is have that same > filename displayed in the text control widget, tcName. Here is OnFileNew from > the main module: > > def OnFileNew(self, event): > """ Create a new file and open it.""" > self.dirname = '' > wd = wx.DirDialog(self, "Chose the default directory", ".", > style=wx.DD_NEW_DIR_BUTTON) > if wd.ShowModal() == wx.ID_OK: > dirname = wd.GetPath() > ted = wx.TextEntryDialog(self, "Enter the project name", "New Project Name", "", > style=wx.RAISED_BORDER|wx.OK|wx.CANCEL) > if ted.ShowModal() == wx.ID_OK: > projname = ted.GetValue() > tcName = self.modModel.tcName > tcName.WriteText(self, projname) > ted.Destroy() > wd.Destroy() > > While projname has the correct string, tcName remains undefined: > > File "eikos.py", line 272, in OnFileNew > tcName = self.modModel.tcName > AttributeError: 'MyFrame' object has no attribute 'modModel' I would *guess* that you'd want instead something like tcName = self.myNotebook.modModel.tcName As I understand, modModel is a page in a wx.Notebook; you probably created it within your Notebook instance, and not your Frame instance. Meanwhile, your OnFileNew method appears to belong to your Frame instance. Andr? > > How do I make tcName visible in eikos.py when it's defined in modelPage.py? > > Rich > > -- > Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental > Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" > Voice: 503-667-4517 Fax: 503-667-8863 > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Feb 7 03:45:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Feb 2006 21:45:21 -0500 Subject: [Tutor] Sharing Variables Across Modules In-Reply-To: References: Message-ID: <43E809C1.1060701@tds.net> Rich Shepard wrote: > I'm developing a wxPython-based application. The UI is a notebook, with the > contents of each page in a separate module. In one module (modelPage.py), I > have defined the class modModel, which is an instance of a wx.Panel class. > Within modModel is a text control widget named tcName. > > The main module, eikos.py, imports modModel from modPage.py. The main > module has two classes: MyNotebook (subclassed from wx.Notebook) and MyFrame, > which contains the notebook and menus. > > The File->New menu calls the method OnFileNew. This displays a directory > dialog so the user can select the directory in which the new file is to be > placed. Then it displays a text entry dialog for the name of the new file. > > I am able to enter the new file name and it is correctly assigned to the > variable, projname. What I have not been able to do is have that same > filename displayed in the text control widget, tcName. Here is OnFileNew from > the main module: > > def OnFileNew(self, event): > """ Create a new file and open it.""" > self.dirname = '' > wd = wx.DirDialog(self, "Chose the default directory", ".", > style=wx.DD_NEW_DIR_BUTTON) > if wd.ShowModal() == wx.ID_OK: > dirname = wd.GetPath() > ted = wx.TextEntryDialog(self, "Enter the project name", "New Project Name", "", > style=wx.RAISED_BORDER|wx.OK|wx.CANCEL) > if ted.ShowModal() == wx.ID_OK: > projname = ted.GetValue() > tcName = self.modModel.tcName > tcName.WriteText(self, projname) > ted.Destroy() > wd.Destroy() > > While projname has the correct string, tcName remains undefined: > > File "eikos.py", line 272, in OnFileNew > tcName = self.modModel.tcName > AttributeError: 'MyFrame' object has no attribute 'modModel' > > How do I make tcName visible in eikos.py when it's defined in modelPage.py? My guess is that you have some confusion between module, class and instance scope in modelPage.py. It might help to see the code that defines self.modModel and the code in modelPage.py that defines tcName. Kent From rshepard at appl-ecosys.com Tue Feb 7 03:59:13 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Mon, 6 Feb 2006 18:59:13 -0800 (PST) Subject: [Tutor] Sharing Variables Across Modules In-Reply-To: <7528bcdd0602061824v5012ced2vcdcf19457dcb6f1@mail.gmail.com> References: <7528bcdd0602061824v5012ced2vcdcf19457dcb6f1@mail.gmail.com> Message-ID: On Mon, 6 Feb 2006, Andre Roberge wrote: > I would *guess* that you'd want instead something like > tcName = self.myNotebook.modModel.tcName Andr?, You got me looking in the right direction. What works is: tcName = self.mainNB.pane_1.tcName So, now the entered name displays in the TextCtrl widget, but it's not being assigned to the variable, modName, in the modModel class. But, I think that I have a better understanding now of what's going on and, with some trial and error exploration should get this resolved, too. Many thanks, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From rshepard at appl-ecosys.com Tue Feb 7 04:08:05 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Mon, 6 Feb 2006 19:08:05 -0800 (PST) Subject: [Tutor] Sharing Variables Across Modules In-Reply-To: References: <7528bcdd0602061824v5012ced2vcdcf19457dcb6f1@mail.gmail.com> Message-ID: On Mon, 6 Feb 2006, Rich Shepard wrote: > So, now the entered name displays in the TextCtrl widget, but it's not > being assigned to the variable, modName, in the modModel class. But, I think > that I have a better understanding now of what's going on and, with some > trial and error exploration should get this resolved, too. Well, that was an easy fix. I needed to prefix the widget name and method with 'self'. Whew! Now on to the next part. Many thanks, Andre and Kent, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From 3dbernard at gmail.com Tue Feb 7 04:31:26 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 6 Feb 2006 19:31:26 -0800 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E7DCFA.6070905@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> Message-ID: <61d0e2b40602061931i121d884dw6d9528f9b30bad91@mail.gmail.com> Hi Kent, I have put together a little script to give a rough idea about what the program does. http://www.bernardlebel.com/scripts/nonxsi/help/bl_threadtest.py The true program does this: - the top program file imports a module called fcJob - the top program instantiate the only class in the fcJob module. The class is named fcJob as well, the instance is named simply "job". This instance has few attribute, the one that I'm interested in now is "localjobstatus". - the top program file enters a while loop where it checks a variety of things, and if certain conditions are met, will start a big function in a separate thread. - the function that runs in the separate thread reads and writes the localjobstatus attributes. - while the child thread is running, the main thread checks a database every 5 seconds to test the value of certain fields. - would the value of specific field changed to certain values, the top thread will set the localjobstatus value to something like "killed". - the child thread, also running a while loop, tests the local job attribute at 3 times during a single iteration. If it gets a "Killed" value, it will call a function that basically terminates this child thread in a clean way. Ultimately, it will set the localjobstatus to "Pending". So in essence, there are two thread reading and writing the the localjobstatus attribute, the main thread and a child thread. The child thread is reading the value in order to control its flow. Hope I'm making sense. Thanks Bernard On 2/6/06, Kent Johnson wrote: > Bernard Lebel wrote: > > Example: > > > > - Class instance Bernard has attribute "name", whose value is "bernard". > > - A function in a thread tests the value of "name". If "name" == > > "bernard", do nothing. > > - A function in another thread, for some reason, changes "name" to "bob". > > - The first function, few moments later, tests again the value of > > "name". It see that the value has changed from "bernard" to "bob", and > > this change causes the function to take an action. > > > > Is that what you mean by "invoking" code? > > No, it's not what I meant, I was talking about constructs that can cause > an assignment like self.x = 1 to directly call code that you wrote. It > sounds like you are not doing that. > > It sounds like you have some attributes that you are using as flags to > allow one thread to control another. There are definitely some pitfalls > here. You probably want to use threading.Condition or Queue.Queue to > communicate between the threads. Can you give more details of what you > are trying to do? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Tue Feb 7 06:53:20 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 7 Feb 2006 18:53:20 +1300 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: <43E72ED5.7040805@tds.net> References: <43E72ED5.7040805@tds.net> Message-ID: On 2/7/06, Kent Johnson wrote: > Liam Clarke wrote: > > Hi all, > > > > About to embark on my first foray into threading, and rather unsure of > > initial approach. I have a basic UDPServer from SocketServer running > > using serve_forever(). I'd like to stick this in a thread where it can > > endlessly loop waiting for incoming packets, and pushing the received > > data into a list where it can be retrieved and operated on by another > > thread, until such time as the controlling app terminates it. > > Threaded servers are supported by the standard library. Instead of using > UDPServer use this class: > class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass > > Then your request handler will be called in a separate thread. You don't > need to queue the requests yourself, the server will create the thread > and dispatch to it when a request is received. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Ah... so then calling serve_forever() won't block? My current code, which illustrates what I'm attempting can be found here - http://www.rafb.net/paste/results/oIqI3Q11.html Basically, the server isn't the main focus, what I'm aiming for looks similar to this server-----Queue--data_cruncher--MySQLconnection server---/ / server-/ / server -/ So basically having data_cruncher to crunch whatever data there is in the queue and send it off to the database is the priority. I'm having trouble with SocketServer, need to do some more experimenting, so I'll get back to it. Regards, Liam Clarke From klappnase at freenet.de Tue Feb 7 11:17:25 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 7 Feb 2006 11:17:25 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E7DCFA.6070905@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> Message-ID: <20060207111725.51f07b9c.klappnase@freenet.de> On Mon, 06 Feb 2006 18:34:18 -0500 Kent Johnson wrote: > > It sounds like you have some attributes that you are using as flags to > allow one thread to control another. There are definitely some pitfalls > here. You probably want to use threading.Condition or Queue.Queue to > communicate between the threads. Can you give more details of what you > are trying to do? > I have used a boolean to control access to a variable that is used by two threads, as in this example: thread 1 does: while self.locked: pass self.locked = 1 if condition: self.name = 'bob' else: self.name = 'mike' self.locked = 0 thread 2 does: while self.locked: pass self.locked = 1 n = self.name self.locked = 0 if n == 'bob': else: I *thought* this would be safe, but now reading this thread I start to doubt. Are there any pitfalls I overlooked in this technique? Thanks Michael From kent37 at tds.net Tue Feb 7 12:02:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Feb 2006 06:02:45 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <20060207111725.51f07b9c.klappnase@freenet.de> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> Message-ID: <43E87E55.5090401@tds.net> Michael Lange wrote: > I have used a boolean to control access to a variable that is used by two threads, > as in this example: > > thread 1 does: > > while self.locked: > pass > self.locked = 1 > if condition: > self.name = 'bob' > else: > self.name = 'mike' > self.locked = 0 > > thread 2 does: > > while self.locked: > pass > self.locked = 1 > n = self.name > self.locked = 0 > if n == 'bob': > > else: > > > I *thought* this would be safe, but now reading this thread I start to doubt. > Are there any pitfalls I overlooked in this technique? If the intent is to ensure that only one thread at a time will be in the code where self.locked == 1, this code will not ensure that. Test-and-set code needs a lock to be thread safe. Imagine both threads reach 'while self.locked' when self.locked == 0. Both threads might finish the while loop before either one sets self.locked. Then both threads might continue through to 'self.locked = 0' together. In this case I'm not sure what would happen if the above scenario took place; it might be harmless. But your lock is definitely not doing what you think it is. One way to make this code thread-safe is to use a threading.Condition() instead of a boolean variable: thread 1 does: self.lock.acquire() if condition: self.name = 'bob' else: self.name = 'mike' self.lock.release() thread 2 does: self.lock.acquire() n = self.name self.lock.release() if n == 'bob': else: If this is the only communication or synchronization between the two threads I don't think the lock is needed at all - thread 2 is presumably in a loop and thread 1 is controlling the behaviour of the loop asynchronously. If there is some other kind of synchronization between the loops, and thread 2 is only supposed to run once for each setting of self.name in thread 1, you could use Condition.wait() and Condition.notify() to do the synchronization. Kent From kent37 at tds.net Tue Feb 7 12:31:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Feb 2006 06:31:05 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <61d0e2b40602061931i121d884dw6d9528f9b30bad91@mail.gmail.com> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <61d0e2b40602061931i121d884dw6d9528f9b30bad91@mail.gmail.com> Message-ID: <43E884F9.4050401@tds.net> Bernard Lebel wrote: > Hi Kent, > > I have put together a little script to give a rough idea about what > the program does. > > http://www.bernardlebel.com/scripts/nonxsi/help/bl_threadtest.py In this code, there is no guarantee that callMeWhenAttributeChanged() will see every change to oBernard.firstname. It could change more than once while checkFirstName() is sleeping and looping. The change to oBernard.firstname in main could stomp on a change from changeAttribute() before it is seen in checkFirstName(). I don't know what the consequences of missing a change are. If the names are some kind of command token I would use a Queue - in this example you have two producers and one consumer, a Queue will ensure that every command is seen. If there is no consequence of missing a change you could leave it as-is or use a threading.Condition to replace the polling loop with wait() / notify(). > > > The true program does this: > > - the top program file imports a module called fcJob > > - the top program instantiate the only class in the fcJob module. The > class is named fcJob as well, the instance is named simply "job". This > instance has few attribute, the one that I'm interested in now is > "localjobstatus". > > - the top program file enters a while loop where it checks a variety > of things, and if certain conditions are met, will start a big > function in a separate thread. > > - the function that runs in the separate thread reads and writes the > localjobstatus attributes. > > - while the child thread is running, the main thread checks a database > every 5 seconds to test the value of certain fields. > > - would the value of specific field changed to certain values, the top > thread will set the localjobstatus value to something like "killed". > > - the child thread, also running a while loop, tests the local job > attribute at 3 times during a single iteration. If it gets a "Killed" > value, it will call a function that basically terminates this child > thread in a clean way. Ultimately, it will set the localjobstatus to > "Pending". This sounds unsafe. What happens if the "Pending" value is overwritten by another "Killed" value? It might be fine if you use two different status variables. When working with threads you have to imagine what would happen if one thread stopped indefinitely at any point, and another thread ran long enough to do something unexpected. Or two threads interleave statements in the worst possible way. Your code seems to have several opportunities for bad things to happen. I can't tell what the consequences of them are, which will determine how hard you should work to prevent them. HTH Kent From kent37 at tds.net Tue Feb 7 12:43:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Feb 2006 06:43:18 -0500 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: References: <43E72ED5.7040805@tds.net> Message-ID: <43E887D6.3010500@tds.net> Liam Clarke wrote: > On 2/7/06, Kent Johnson wrote: > >>Liam Clarke wrote: >> >>>Hi all, >>> >>>About to embark on my first foray into threading, and rather unsure of >>>initial approach. I have a basic UDPServer from SocketServer running >>>using serve_forever(). I'd like to stick this in a thread where it can >>>endlessly loop waiting for incoming packets, and pushing the received >>>data into a list where it can be retrieved and operated on by another >>>thread, until such time as the controlling app terminates it. >> >>Threaded servers are supported by the standard library. Instead of using >>UDPServer use this class: >> class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass >> >>Then your request handler will be called in a separate thread. You don't >>need to queue the requests yourself, the server will create the thread >>and dispatch to it when a request is received. >> >>Kent > > Ah... so then calling serve_forever() won't block? It will still block, but your request handler will be called in a new thread for each request. > > My current code, which illustrates what I'm attempting can be found > here - http://www.rafb.net/paste/results/oIqI3Q11.html This is probably fine. You will only be able to handle one request at a time but the request handling is fast - just read the data and drop it in the Queue - so that may well be OK. You could also change it to use ThreadingUDPServer leaving everything else the same - this would allow multiple simultaneous connections. With your design, you will process the requests one at a time in the data_cruncher and you need only one database connection. An alternate design is to use ThreadingUDPServer and have the request handler do the data crunching and database access. Each handler would have its own database connection. The advantage of this would be to have multiple threads of crunching and database access running at one time which *may* allow faster throughput. Yet another alternative would be to have a thread pool pulling requests from the Queue. This gives you better control over the number of worker threads and would let you persist the database connection for each worker. You can find several recipes for thread pools in the online Python cookbook. HTH Kent > > Basically, the server isn't the main focus, what I'm aiming for looks > similar to this > > server-----Queue--data_cruncher--MySQLconnection > server---/ / > server-/ / > server -/ > > So basically having data_cruncher to crunch whatever data there is in > the queue and send it off to the database is the priority. I'm having > trouble with SocketServer, need to do some more experimenting, so I'll > get back to it. > > Regards, > > Liam Clarke > > From 3dbernard at gmail.com Tue Feb 7 15:40:45 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 7 Feb 2006 09:40:45 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E884F9.4050401@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <61d0e2b40602061931i121d884dw6d9528f9b30bad91@mail.gmail.com> <43E884F9.4050401@tds.net> Message-ID: <61d0e2b40602070640u70badb77t20ed2d50a55efab1@mail.gmail.com> Hi Kent, To answer your first concern, not all changes need to be intercepted by one the child thread. I have not given out all the details about the program, but if the parent thread gets certain values from the database, it will take actions that may affect the child thread other than just by setting the localjobstatus attribute. As for your last comments, well, the conclusion I draw is that in fact I should not take any chance with that, and implement some thread safety using Queue or thread conditions. I'll check that out. Thanks for all the help! Bernard On 2/7/06, Kent Johnson wrote: > Bernard Lebel wrote: > > Hi Kent, > > > > I have put together a little script to give a rough idea about what > > the program does. > > > > http://www.bernardlebel.com/scripts/nonxsi/help/bl_threadtest.py > > In this code, there is no guarantee that callMeWhenAttributeChanged() > will see every change to oBernard.firstname. It could change more than > once while checkFirstName() is sleeping and looping. The change to > oBernard.firstname in main could stomp on a change from > changeAttribute() before it is seen in checkFirstName(). > > I don't know what the consequences of missing a change are. If the names > are some kind of command token I would use a Queue - in this example you > have two producers and one consumer, a Queue will ensure that every > command is seen. If there is no consequence of missing a change you > could leave it as-is or use a threading.Condition to replace the polling > loop with wait() / notify(). > > > > > > The true program does this: > > > > - the top program file imports a module called fcJob > > > > - the top program instantiate the only class in the fcJob module. The > > class is named fcJob as well, the instance is named simply "job". This > > instance has few attribute, the one that I'm interested in now is > > "localjobstatus". > > > > - the top program file enters a while loop where it checks a variety > > of things, and if certain conditions are met, will start a big > > function in a separate thread. > > > > - the function that runs in the separate thread reads and writes the > > localjobstatus attributes. > > > > - while the child thread is running, the main thread checks a database > > every 5 seconds to test the value of certain fields. > > > > - would the value of specific field changed to certain values, the top > > thread will set the localjobstatus value to something like "killed". > > > > - the child thread, also running a while loop, tests the local job > > attribute at 3 times during a single iteration. If it gets a "Killed" > > value, it will call a function that basically terminates this child > > thread in a clean way. Ultimately, it will set the localjobstatus to > > "Pending". > > This sounds unsafe. What happens if the "Pending" value is overwritten > by another "Killed" value? It might be fine if you use two different > status variables. > > When working with threads you have to imagine what would happen if one > thread stopped indefinitely at any point, and another thread ran long > enough to do something unexpected. Or two threads interleave statements > in the worst possible way. Your code seems to have several opportunities > for bad things to happen. I can't tell what the consequences of them > are, which will determine how hard you should work to prevent them. > > HTH > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pkraus at pelsupply.com Tue Feb 7 16:28:43 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 7 Feb 2006 10:28:43 -0500 Subject: [Tutor] Python - Embedded mysql server Message-ID: <200602071028.43189.pkraus@pelsupply.com> Anyone know where I can find information about how to embedd mysql into a python application. I need my hand held. I have worked with mysql a lot. I understand how to use python to manipulate a mysql database. What I want to know is how to embedded a database into my application. -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From cspears2002 at yahoo.com Tue Feb 7 17:50:36 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 7 Feb 2006 08:50:36 -0800 (PST) Subject: [Tutor] lunch.py Message-ID: <20060207165036.30979.qmail@web51603.mail.yahoo.com> I'm working on a program where a Customer orders Food from an Employee. Here is what I have so far: class Food: def __init__(self, name): Food.foodName = name class Customer: def __init__(self,name): Customer.name = name def placeOrder(self, employee, food): print "%s, I want, %s please! " % Employee.name, food.foodName class Employee: def __init__(self, name): Employee.name = name class Lunch: def __init__(self): self.employee = Employee('Dave') def order(self, name, foodName): customer = Customer(name) food = Food(foodName) customer.placeOrder(self.employee, food) if __name__ == '__main__': meal = Lunch() meal.order('Chris', 'spam') When I run the program, I get the following error Traceback (most recent call last): File "lunch.py", line 25, in ? meal.order('Chris', 'spam') File "lunch.py", line 21, in order customer.placeOrder(self.employee, food) File "lunch.py", line 9, in placeOrder print "%s, I want, %s please! " % Employee.name, food.foodName I've tested the program, and I know that Employee.name is getting through, but for some reason, food.foodName is not. What am I doing wrong? From nephish at xit.net Tue Feb 7 17:58:52 2006 From: nephish at xit.net (nephish) Date: Tue, 07 Feb 2006 16:58:52 +0000 Subject: [Tutor] stuck again - socket connection Message-ID: <1139331532.23500.0.camel@localhost.localdomain> ok, i am stuck again. from the docs, the byte stream is supposed to look like this: 'S' 'T' 'X' [length indicator] [message type] [message] 'E' 'N' 'X' the length indicator it says is a four byte integer number of a value N ( N would be how long the message body is ) the message type comes from a table in the docs. In my case, the message type is 200. This is also supposed to be sent as a 4 byte value. so..... how do i make 200 occupy 4 bytes ? From gt at tuckers.de Tue Feb 7 17:33:17 2006 From: gt at tuckers.de (Gil Tucker) Date: Tue, 07 Feb 2006 17:33:17 +0100 Subject: [Tutor] installing python the latest python programme Message-ID: <43E8CBCD.8030902@tuckers.de> Hi to all, Whenever I try to install python 2.2 and later on Win. 2000 It never properly sets up on the compter. I usually only get the command section but the IDE never shows up. Maybe somebody has an idea or a tip as to what`s going on here. Cheers Gil From josipl2000 at yahoo.com Tue Feb 7 18:03:50 2006 From: josipl2000 at yahoo.com (josip) Date: Tue, 7 Feb 2006 09:03:50 -0800 (PST) Subject: [Tutor] newbie problem Message-ID: <20060207170350.46724.qmail@web60812.mail.yahoo.com> Hi, I am learning Python trought one course. I can't solve this, someone please help. Write a loop that prints 20 characters on the screen. Always 20. But it is made up of stars (*), which are printed first, and exclamation marks (!) that complete the line. Your program will first ask the user to enter a number. It will represent the number of stars that should be present in the line. The program will then print exclamation marks until the total number of characters is 20. Examples of how your program should work (user input underlined): How many stars? 10 * * * * * * * * * * ! ! ! ! ! ! ! ! ! ! How many stars? 20 * * * * * * * * * * * * * * * * * * * * How many stars? 1 * ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Thanks! --------------------------------- Yahoo! Mail - Helps protect you from nasty viruses. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060207/1532319f/attachment-0001.htm From shaleh at speakeasy.net Tue Feb 7 19:27:20 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Tue, 07 Feb 2006 10:27:20 -0800 Subject: [Tutor] lunch.py In-Reply-To: <20060207165036.30979.qmail@web51603.mail.yahoo.com> References: <20060207165036.30979.qmail@web51603.mail.yahoo.com> Message-ID: <43E8E688.9070804@speakeasy.net> Christopher Spears wrote: > I'm working on a program where a Customer orders Food > from an Employee. Here is what I have so far: > > class Food: > def __init__(self, name): > Food.foodName = name > what you want here is 'self.name = name' then in your code later you can do: protein = Food("hamburger") lipid = Food("olive oil") print protein.name print lipid.name > class Customer: > def __init__(self,name): > Customer.name = name > def placeOrder(self, employee, food): > print "%s, I want, %s please! " % Employee.name, > food.foodName > > class Employee: > def __init__(self, name): > Employee.name = name > same for these, use self.name. 'self' is the item you are constructing. in my example above the Food class is instantiated with the name 'hamburger' and assigned to protein. When your code assigned to Food.foodName you were making *ALL* instances of Food be the same food. Observe: >>> class Food: ... def __init__(self, name): ... Food.foodName = name ... >>> protein = Food('hamburger') >>> protein.foodName 'hamburger' >>> lipid = Food('olive oil') >>> lipid.foodName 'olive oil' >>> protein.foodName 'olive oil' So to recap, use the class name when you want all instances to share a variable i.e. a count of the number of items. Use 'self' when you want each instance to have its own version of the variable, like your 'name'. From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 19:36:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 10:36:33 -0800 (PST) Subject: [Tutor] Python - Embedded mysql server In-Reply-To: <200602071028.43189.pkraus@pelsupply.com> Message-ID: On Tue, 7 Feb 2006, Paul Kraus wrote: > Anyone know where I can find information about how to embedd mysql into > a python application. I need my hand held. I have worked with mysql a > lot. I understand how to use python to manipulate a mysql database. What > I want to know is how to embedded a database into my application. Hi Paul, You may want to look into SQLite and the pysqlite module instead: http://www.sqlite.org/ http://pysqlite.org/ Unlike MySQL, SQLite is meant to be an embedded database. Grab sqlite from their web page; I think you'll be pleasantly surprised. There was some discussion on the pysqlite mailing list about bundling up pysqlite with a Python application. According a message to their mailing list from May 2005, it's not a problem: http://lists.initd.org/pipermail/pysqlite/2005-May/000058.html but you should probably talk to the pysqlite folks to be sure how to make this work. More information on their mailing list is here: http://lists.initd.org/mailman/listinfo/pysqlite Good luck! From ianjones at umich.edu Tue Feb 7 19:35:53 2006 From: ianjones at umich.edu (Ian Jones) Date: Tue, 07 Feb 2006 13:35:53 -0500 Subject: [Tutor] lunch.py References: <20060207165036.30979.qmail@web51603.mail.yahoo.com> Message-ID: In article <20060207165036.30979.qmail at web51603.mail.yahoo.com>, Christopher Spears wrote: > When I run the program, I get the following error [snip] The simple mechanical error is that when you're substituting more than one value, you need to wrap the value list in parens: print "%s, I want, %s please! " % (Employee.name, food.foodName) (from Customer.placeOrder()) At this point your program, as written, gives the expected output. There is a more serious conceptual error, though. In your various __init__() methods, you are assigning the name attribute of the *class*, rather than the name of the *instance*. That is, you are saying "the name of all employees is Dave" rather than "the name of this employee is Dave." class Employee: def __init__(self, name): Employee.name = name # <-- assigns class attribute (name of all Employees) To illustrate, try running this as your __main__: if __name__ == '__main__': meal = Lunch() meal.order('Chris', 'spam') # next line shouldn't replace Dave, but it does firedEmployee = Employee("Bill") meal.order('Jake', 'eggs') In your __init__() methods, you should assign to self instead of to the class. For example: class Employee: def __init__(self, name): self.name = name # <-- assigns instance attribute (this Employee's name) From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 19:40:42 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 10:40:42 -0800 (PST) Subject: [Tutor] newbie problem In-Reply-To: <20060207170350.46724.qmail@web60812.mail.yahoo.com> Message-ID: On Tue, 7 Feb 2006, josip wrote: > I can't solve this, someone please help. Since this is a homework problem, we're limited in what we can say here. Can you simplify the problem a bit? Can you write a program that asks for stars, and just prints out that many stars? That is, ignore for now the part about the exclamation parts for the moment. Would you be able to do that problem? From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 19:43:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 10:43:14 -0800 (PST) Subject: [Tutor] stuck again - socket connection In-Reply-To: <1139331532.23500.0.camel@localhost.localdomain> Message-ID: > from the docs, the byte stream is supposed to look like this: > [problem cut] > > so..... how do i make 200 occupy 4 bytes ? Hi Nephish, Have you had a chance to look at the 'struct' module yet? http://www.python.org/doc/lib/module-struct.html From nephish at xit.net Tue Feb 7 19:48:02 2006 From: nephish at xit.net (nephish) Date: Tue, 07 Feb 2006 12:48:02 -0600 Subject: [Tutor] stuck again - socket connection In-Reply-To: References: Message-ID: <1139338082.630.0.camel@localhost.localdomain> Yeah, looking over it right now as a point of fact. thanks. Looks like exactly what i need. cheers shawn On Tue, 2006-02-07 at 10:43 -0800, Danny Yoo wrote: > > > from the docs, the byte stream is supposed to look like this: > > > [problem cut] > > > > so..... how do i make 200 occupy 4 bytes ? > > > Hi Nephish, > > Have you had a chance to look at the 'struct' module yet? > > http://www.python.org/doc/lib/module-struct.html > From cspears2002 at yahoo.com Tue Feb 7 21:08:56 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 7 Feb 2006 12:08:56 -0800 (PST) Subject: [Tutor] Why None? Message-ID: <20060207200857.78238.qmail@web51608.mail.yahoo.com> Here is some code I wrote: class Food: def __init__(self, name): Food.foodName = name class Customer: def __init__(self,name): Customer.name = name Customer.food = 0 def placeOrder(self, foodName, employee): print "Hi %s!" % employee.name print "I want %s please! " % foodName self.food = employee.takeOrder(foodName) def printFood(self): print self.food.foodName class Employee: def __init__(self, name): Employee.name = name def takeOrder(self, foodName): print "%s coming up!" % foodName food = Food(foodName) return food class Lunch: def __init__(self): self.employee = Employee('Dave') self.customer = Customer('Chris') def order(self, foodName): self.customer.placeOrder(foodName, self.employee) def result(self): print self.customer.name, "has", self.customer.printFood() if __name__ == '__main__': meal = Lunch() meal.order('spam') meal.result() Basically, a Lunch creates a Customer and an Employee. When Lunch's order method is called, the Customer places an order with placeOrder, which activates takeOrder from the Employee. takeOrder creates a Food object using the foodName string that has been passed down from Lunch's order method. The Food object is then passed to Customer. I then run Lunch's result method to see if Customer received the Food object. cspears at iaws09:/imports/home/cspears/Documents/Python/chap23/ex07> python lunch.py Hi Dave! I want spam please! spam coming up! Chris has spam None This is almost correct. Why does None appear? This is the only fly in the ointment. I'm probably missing something subtle. From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 21:37:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 12:37:32 -0800 (PST) Subject: [Tutor] Why None? In-Reply-To: <20060207200857.78238.qmail@web51608.mail.yahoo.com> Message-ID: Hi Chris, I'm going to be a little insidous and bring some ideas from the textbook "How to Design Programs." (http://htdp.org) Let's annotate each interesting method with what the method expects to take in, and what it expects to return. > def placeOrder(self, foodName, employee): We can say that placeOrder takes in foodName and employee, and returns None. We can write this concept as a docstring, using a notation like this: ############################################## def placeOrder(self, foodName, employee): """placeOrder: string Employee -> None ... [add description here]""" ## rest of body ############################################## That is, we make it clear what the expected inputs and outputs are. > def printFood(self): printFood doesn't appear to take anything useful, and also doesn't return anything useful. Again: ################################ def printFood(self): """printFood: -> None""" ## rest of body ################################ (Hint: this part is important. Note that printFood() also returns None.) If you do this slight annotation to the rest of the methods, it might make it easier to see why Lunch.result() is giving slightly weird results. Best of wishes! From shaleh at speakeasy.net Tue Feb 7 21:48:39 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Tue, 07 Feb 2006 12:48:39 -0800 Subject: [Tutor] Why None? In-Reply-To: <20060207200857.78238.qmail@web51608.mail.yahoo.com> References: <20060207200857.78238.qmail@web51608.mail.yahoo.com> Message-ID: <43E907A7.4010101@speakeasy.net> Hey Chris, check out this version. class Food: def __init__(self, name): self.name = name class Customer: def __init__(self,name): self.name = name self.food = None # 0 is for numbers def placeOrder(self, foodName, employee): print "%s: Hi %s!" % (self.name, employee.name) print "%s: I want %s please! " % (self.name, foodName) self.food = employee.takeOrder(foodName) def foodOrdered(self): return self.food.name class Employee: def __init__(self, name): self.name = name def takeOrder(self, foodName): print "%s: %s coming up!" % (self.name, foodName) return Food(foodName) class MealOrder: def __init__(self, employee, customer): self.employee = employee self.customer = customer def set(self, foodName): self.customer.placeOrder(foodName, self.employee) def result(self): print "%s has %s" % (self.customer.name, self.customer.foodOrdered()) if __name__ == '__main__': order = MealOrder(Employee('Dave'), Customer('Chris')) order.set('spam') order.result() From cspears2002 at yahoo.com Tue Feb 7 21:54:01 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 7 Feb 2006 12:54:01 -0800 (PST) Subject: [Tutor] Why None? In-Reply-To: Message-ID: <20060207205401.20029.qmail@web51611.mail.yahoo.com> I get it! Have printFood return a string! def printFood(self): return self.food.foodName Now I don't get the weird output anymore! -Chris --- Danny Yoo wrote: > > Hi Chris, > > I'm going to be a little insidous and bring some > ideas from the textbook > "How to Design Programs." (http://htdp.org) > > Let's annotate each interesting method with what the > method expects to > take in, and what it expects to return. > > > def placeOrder(self, foodName, employee): > > > We can say that placeOrder takes in foodName and > employee, and returns > None. We can write this concept as a docstring, > using a notation like > this: > > ############################################## > def placeOrder(self, foodName, employee): > """placeOrder: string Employee -> None > ... [add description here]""" > ## rest of body > ############################################## > > That is, we make it clear what the expected inputs > and outputs are. > > > > def printFood(self): > > printFood doesn't appear to take anything useful, > and also doesn't return > anything useful. Again: > > ################################ > def printFood(self): > """printFood: -> None""" > ## rest of body > ################################ > > (Hint: this part is important. Note that > printFood() also returns None.) > > > If you do this slight annotation to the rest of the > methods, it might make > it easier to see why Lunch.result() is giving > slightly weird results. > > > Best of wishes! > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 21:57:58 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 12:57:58 -0800 (PST) Subject: [Tutor] Why None? In-Reply-To: <20060207205401.20029.qmail@web51611.mail.yahoo.com> Message-ID: On Tue, 7 Feb 2006, Christopher Spears wrote: > I get it! Have printFood return a string! > > def printFood(self): > return self.food.foodName Yup. *grin* Do one more thing though: call the function something other than 'printFood' now, since it clearly isn't doing any printing itself. 'getFoodName' is a bit pedestrian, but it might work as a name. Good luck! From matthew.williams at cancer.org.uk Tue Feb 7 22:23:09 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Tue, 07 Feb 2006 21:23:09 +0000 Subject: [Tutor] Python DB In-Reply-To: References: Message-ID: <43E90FBD.6050607@cancer.org.uk> You might also want to have a look at DABO; I don't know how well it work on a handheld, though. http://dabodev.com/about Matt From guylevy at sbcglobal.net Tue Feb 7 22:55:54 2006 From: guylevy at sbcglobal.net (guy) Date: Tue, 7 Feb 2006 13:55:54 -0800 Subject: [Tutor] I would like to learn python ASAP Message-ID: Hello, My name is Guy and I live in San Francisco, I would like to learn python ASAP and am looking for a tutor. I know there are many sites out there that can help me self learn it but I am out of a job and it looks like if I learn Python as a scripting language I could speed up the process :-) I am in the QA field, and am learning Java as well in school but must QA jobs today require one to know some scripting language. I do know SQL (Using MySQL) and have writing small starting python and java scripts like calc.py/java and other print statements. (Nothing to be proud of :-)) I would like to understand how one can right unit test cases using python and how to utilize them on a giving application. Testing the DB as well as from http calls Any help would be grateful. Thank you, Guy From klappnase at freenet.de Tue Feb 7 23:31:06 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 7 Feb 2006 23:31:06 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E87E55.5090401@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> Message-ID: <20060207233106.6f4bd867.klappnase@freenet.de> On Tue, 07 Feb 2006 06:02:45 -0500 Kent Johnson wrote: > > One way to make this code thread-safe is to use a threading.Condition() > instead of a boolean variable: > > thread 1 does: > > self.lock.acquire() > if condition: > self.name = 'bob' > else: > self.name = 'mike' > self.lock.release() > > thread 2 does: > > self.lock.acquire() > n = self.name > self.lock.release() > if n == 'bob': > > else: > > > If this is the only communication or synchronization between the two > threads I don't think the lock is needed at all - thread 2 is presumably > in a loop and thread 1 is controlling the behaviour of the loop > asynchronously. If there is some other kind of synchronization between > the loops, and thread 2 is only supposed to run once for each setting of > self.name in thread 1, you could use Condition.wait() and > Condition.notify() to do the synchronization. > Thanks Kent, In fact I have three threads, a main gui thread and two child threads. Child thread 1 reads data from the soundcard and appends these data to two lists which I use as recording buffer. The data from list 1 are used by the gui thread to draw a vumeter, the data from list 2 are written to the target file. So the communication between the threads occurs when the gui thread resp. child thread 2 read and empty the buffer lists to process the data. So my functions currently (with boolean "locks") look like: gui thread (this function is called periodically by Tkinter): def get_peaks(self): if self.vu_locked: return None self.vu_locked = 1 data = [x for x in self.vubuffer] self.vubuffer = [] self.vu_locked = 0 if not data: return None left, right = 0, 0 for d in data: left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left) right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right) return left, right thread 1: vubuffer = [] recbuffer = [] while self.running: data = self._audioobj.read(self._fragsize)# read data from soundcard vubuffer.append(data) if not self.vu_locked: self.vu_locked = 1 self.vubuffer += vubuffer vubuffer = [] self.vu_locked = 0 if self.recording: recbuffer.append(data) if not self.rec_locked: self.rec_locked = 1 self.recbuffer += recbuffer recbuffer = [] self.rec_locked = 0 thread 2: while self.recording: # wait a moment until there is something in the buffer to be written time.sleep(0.1) if not self.rec_locked: self.rec_locked = 1 data = [x for x in self.recbuffer] self.recbuffer = [] self.rec_locked = 0 for d in data: self._waveobj.writeframesraw(d)# write the data to a file So I think I need two Condition objects here; it is most important here that thread 1 does not block to minimize the risk of recording buffer overruns, but from reading the docs I am not sure about the correct procedure. So if I change self.rec_locked and self.vu_locked from the code above to be Condition objects is it correct to do: thread 1: vubuffer = [] recbuffer = [] while self.running: data = self._audioobj.read(self._fragsize)# read data from soundcard vubuffer.append(data) if self.vu_locked.acquire(blocking=0): self.vubuffer += vubuffer vubuffer = [] self.vu_locked.release() if self.recording: recbuffer.append(data) if self.rec_locked.acquire(blocking=0): self.recbuffer += recbuffer recbuffer = [] self.rec_locked.release() thread 2: while self.recording: # wait a moment until there is something in the buffer to be written time.sleep(0.1) data = [] if self.rec_locked.acquire(blocking=0): data = [x for x in self.recbuffer] self.recbuffer = [] self.rec_locked.release() for d in data: self._waveobj.writeframesraw(d)# write the data to a file Thanks Michael From dyoo at hkn.eecs.berkeley.edu Tue Feb 7 23:29:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 14:29:03 -0800 (PST) Subject: [Tutor] I would like to learn python ASAP In-Reply-To: Message-ID: On Tue, 7 Feb 2006, guy wrote: > I am in the QA field, and am learning Java as well in school but must QA > jobs today require one to know some scripting language. I do know SQL (Using > MySQL) and have writing small starting python and java scripts like > calc.py/java and other print statements. (Nothing to be proud of :-)) Hello Guy, I'm assuming then that you've had some previous programming experience. Have you seen Dive into Python? http://diveintopython.org/ It might help you jump into writing Python programs; the intended audience is experienced programmers. > I would like to understand how one can right unit test cases using > python and how to utilize them on a giving application. The chapter on Unit Testing in Dive into Python is quite good: http://diveintopython.org/unit_testing/index.html > Testing the DB as well as from http calls You might find: http://wwwsearch.sourceforge.net/mechanize/ http://www.idyll.org/~t/www-tools/twill/ useful in doing tests on web appications. Good luck! From nequeo at gmail.com Wed Feb 8 00:21:50 2006 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 8 Feb 2006 10:21:50 +1100 Subject: [Tutor] Finding bottom level directories, and command-line arguments Message-ID: <667ca7b60602071521i1b85076dr@mail.gmail.com> G'day Tutors, I watch many different TV shows on my PC, as many of us do. But I am sick and tired of forgetting which episode I was up to. So, in a prodigious effort to avoid ever using, say, a pen, I am working on a script to take over some of my brain's memory handling. When complete, I will simply be able to type, for example, 'play family_guy' from the command line and it will automatically launch the next unwatched episode. So I was wondering if anyone has an efficient, Pythonesque way of creating a dictionary of all bottom level directories in a given path. At the moment I'm doing this \/ to find all directories in a given directory. But I really want to dig down and find all bottom level directories. ------- def build_dir_index(): for item in os.listdir(vid_path): if os.path.isdir(item): # Ask user what to do with this directory... -------- I know about os.walk and os.path.walk, but I'm not sure how to use them effectively to get a list of all bottom level directories. Otherwise, I've also considered using the above listdir/isdir recursively to build up lists of subdirectories, and tag all directories that return an empty list as bottom-level. But I just get the feeling there's a simple, elegant way of doing this that I'm missing. Second question - anyone have some good pointers/links about how to parse command line arguments effectively? I.e. perhaps build a dictionary of all options and their values, so I can deal with them appropriately? Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From dyoo at hkn.eecs.berkeley.edu Wed Feb 8 01:43:58 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Feb 2006 16:43:58 -0800 (PST) Subject: [Tutor] Finding bottom level directories, and command-line arguments In-Reply-To: <667ca7b60602071521i1b85076dr@mail.gmail.com> Message-ID: On Wed, 8 Feb 2006, Simon Gerber wrote: > I watch many different TV shows on my PC, as many of us do. But I am > sick and tired of forgetting which episode I was up to. So, in a > prodigious effort to avoid ever using, say, a pen, I am working on a > script to take over some of my brain's memory handling. When complete, I > will simply be able to type, for example, 'play family_guy' from the > command line and it will automatically launch the next unwatched > episode. Hi Simon, It might be interesting to write a function that takes an arbitrary directory, and returns 'True' if that directory is a bottom-level directory. Can you write this function? If so, then we can use it to solve the problem of getting all bottom-level directories: we can recursively walk all directories from a root, and just keep the ones that say 'True' to our helper function. Does this make sense? > Second question - anyone have some good pointers/links about how to > parse command line arguments effectively? I.e. perhaps build a > dictionary of all options and their values, so I can deal with them > appropriately? There's a module that does this called 'optparse': http://www.python.org/doc/lib/module-optparse.html Try reusing that first, because it's been fairly well exercised and tuned to what people expect from an option parser. If you have more questions, please feel free to ask. Good luck! From nequeo at gmail.com Wed Feb 8 02:54:31 2006 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 8 Feb 2006 12:54:31 +1100 Subject: [Tutor] Finding bottom level directories, and command-line arguments In-Reply-To: References: <667ca7b60602071521i1b85076dr@mail.gmail.com> Message-ID: <667ca7b60602071754w6bec5639x@mail.gmail.com> Hi Danny, Thanks for the advice. > It might be interesting to write a function that takes an arbitrary > directory, and returns 'True' if that directory is a bottom-level > directory. Can you write this function? I've got this: ------- def isBottomDir(path): for item in os.listdir(path): if os.path.isdir(os.path.join(path,item)): return False return True ------- Is that an acceptable way of doing this? I've been reading http://thedailywtf.com for a month or so now - and though I've yet to see a Python example cross their pages, I'm rather terrified of becoming the first :) To iterate through the directories, the following works for me: ------- for root, dirs, files in os.walk('~\Test'): if test_dir.isBottomDir(root) == True: print root ------- Is it worthwhile trying to write my own recursive function for this? Or can I safely leave this task to to os.walk without inviting ridicule from the programming community. > There's a module that does this called 'optparse': > > http://www.python.org/doc/lib/module-optparse.html > > Try reusing that first, because it's been fairly well exercised and tuned > to what people expect from an option parser. Excellent. That looks like what I was looking for. Thanks! -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From smiles at worksmail.net Wed Feb 8 07:18:54 2006 From: smiles at worksmail.net (Smith) Date: Wed, 8 Feb 2006 00:18:54 -0600 Subject: [Tutor] small floating point number problem Message-ID: <006d01c62c7d$d7bab730$1f2c4fca@csmith> I just ran into a curious behavior with small floating points, trying to find the limits of them on my machine (XP). Does anyone know why the '0.0' is showing up for one case below but not for the other? According to my tests, the smallest representable float on my machine is much smaller than 1e-308: it is 2.470328229206234e-325 but I can only create it as a product of two numbers, not directly. Here is an attempt to create the much larger 1e-308: >>> a=1e-308 >>> a 0.0 >>> a==0 True <-- it really is 0; this is not a repr issue >>> b=.1*1e-307 >>> b 9.9999999999999991e-309 >>> a==b False <--they really are different >>> Also, I see that there is some graininess in the numbers at the low end, but I'm guessing that there is some issue with floating points that I would need to read up on again. The above dilemma is a little more troublesome. >>> m=2.470328229206234e-017 >>> s=1e-307 >>> m*s 4.9406564584124654e-324 #2x too large >>> 2*m*s 4.9406564584124654e-324 >>> 3*m*s==4*m*s True >>> /c From kp8 at mac.com Wed Feb 8 09:24:52 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 8 Feb 2006 03:24:52 -0500 Subject: [Tutor] Gaussian integer values In-Reply-To: References: Message-ID: <4D60C9BE-0E96-4201-8EC8-E7DB849707FC@mac.com> hi all. I am working with a list and would like to choose from the list randomly but not uniformly. I am interested in several distributions but the first one i looked at is Gaussian. which you call like so: random.gauss(mean, dev) You can try this code courtesy of effbot (http://effbot.org/ librarybook/random.htm) # File: random-example-3.py import random histogram = [0] * 20 # calculate histogram for gaussian # noise, using average=5, stddev=1 for i in range(1000): i = int(random.gauss(5, 1) * 2) histogram[i] = histogram[i] + 1 # print the histogram m = max(histogram) for v in histogram: print "*" * (v * 50 / m) fine this works and works well... one problem with this... if you are using this to create an index to a list you might be in trouble as each time you run it you get a slightly different min and max value. so... how does one safely pick from a list of say 15 elements with a large bias towards the center values without over or under-running the bounds of your list? cheers, kevin ps. what would be the opposite of the Gaussian distro the scoop like one, the one where the outer elements are favored. Is that in the python standard lib? (or numpy?) From raymond.hettinger at verizon.net Wed Feb 8 09:08:25 2006 From: raymond.hettinger at verizon.net (Raymond Hettinger) Date: Wed, 08 Feb 2006 03:08:25 -0500 Subject: [Tutor] [Python-Dev] small floating point number problem References: <006d01c62c7d$d7bab730$1f2c4fca@csmith> Message-ID: <001c01c62c86$d694beb0$b83efea9@RaymondLaptop1> [Smith] >I just ran into a curious behavior with small floating points, trying to >find the limits of them on my machine (XP). Does anyone know why the '0.0' >is showing up for one case below but not for the other? According to my >tests, the smallest representable float on my machine is much smaller than >1e-308: it is > > 2.470328229206234e-325 > > but I can only create it as a product of two numbers, not directly. Here > is an attempt to create the much larger 1e-308: > >>>> a=1e-308 >>>> a > 0.0 The clue is in that the two differ by 17 orders of magnitude (325-308) which is about 52 bits. The interpreter builds 1-e308 by using the underlying C library string-to-float function and it isn't constructing numbers outside the normal range for floats. When you enter a value outside that range, the function underflows it to zero. In contrast, your computed floats (such as 1*1e-307) return a denormal result (where the significand is stored with fewer bits than normal because the exponent is already at its outer limit). That denormal result is not zero and the C library float-to-string conversion successfully generates a decimal string representation. The asymmetric handling of denormals by the atof() and ftoa() functions is why you see a difference. A consequence of that asymmetry is the breakdown of the expected eval(repr(f))==f invariant: >>> f = f = .1*1e-307 >>> eval(repr(f)) == f False Raymond From kent37 at tds.net Wed Feb 8 12:08:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 06:08:16 -0500 Subject: [Tutor] I would like to learn python ASAP In-Reply-To: References: Message-ID: <43E9D120.60100@tds.net> guy wrote: > I would like to understand how one can right unit test cases using python > and how to utilize them on a giving application. There are several Python packages that help to automate Windows GUI applications. These could be used to write tests. winguiauto has the basics http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html These two are based on winguiauto: http://www.tizmoi.net/watsup/intro.html http://sourceforge.net/projects/pywinauto Kent From klappnase at freenet.de Wed Feb 8 12:17:33 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 8 Feb 2006 12:17:33 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <20060207233106.6f4bd867.klappnase@freenet.de> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> Message-ID: <20060208121733.22395416.klappnase@freenet.de> On Tue, 7 Feb 2006 23:31:06 +0100 Michael Lange wrote: > > So I think I need two Condition objects here; it is most important here that thread 1 does not > block to minimize the risk of recording buffer overruns, but from reading the docs I am > not sure about the correct procedure. So if I change self.rec_locked and self.vu_locked from the > code above to be Condition objects is it correct to do: > Ok, some testing gave me the answer, with the code I posted I got an AssertionError, so obviously the release() call has to be inside the "if self.rec_lock.acquire(blocking=0):" block. So now my functions look like: gui thread (periodically called by Tkinter): def get_peaks(self): if not self.vu_lock.acquire(blocking=0): return None data = [x for x in self.vubuffer] self.vubuffer = [] self.vu_lock.release() if not data: return None left, right = 0, 0 for d in data: left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left) right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right) return left, right child thread 1: vubuffer = [] recbuffer = [] while self.running: data = self._audioobj.read(self._fragsize)# read data from soundcard vubuffer.append(data) if self.vu_lock.acquire(blocking=0): self.vubuffer += vubuffer vubuffer = [] self.vu_lock.release() if self.recording: recbuffer.append(data) if self.rec_lock.acquire(blocking=0): self.recbuffer += recbuffer recbuffer = [] self.rec_lock.release() child thread 2: while self.recording: # wait a moment until there is something in the buffer to be written data = [] time.sleep(0.1) if self.rec_lock.acquire(blocking=0): data = [x for x in self.recbuffer] self.recbuffer = [] self.rec_lock.release() for d in data: self._waveobj.writeframesraw(d)# write data to file This *seems* to work, however it looks like this code does not separate properly the gui from the child threads which everyone says should be avoided in any case. On the other hand, with the technique I used before, with a boolean as "lock", like: if not self.vu_locked: self.vu_locked = 1 self.vubuffer += vubuffer vubuffer = [] self.vu_locked = 0 it seems like the worst case is that both the gui and the child thread pass the test "if not self.vu_locked" at the same time which might cause some data to be lost from the vubuffer list; probably that is something I could live with. So now my question: Does anyone know how a threading.Condition() object is handled internally, so maybe its methods actually can be called safely from the gui thread? Thanks Michael From le.dahut at laposte.net Wed Feb 8 12:15:25 2006 From: le.dahut at laposte.net (le dahut) Date: Wed, 08 Feb 2006 12:15:25 +0100 Subject: [Tutor] distutils and record-rpm not recognized Message-ID: <43E9D2CD.8090309@laposte.net> I've Python 2.4.1 installed and 'setup.py' doesn't recognize the '--record-rpm' option : "error: option --record-rpm not recognized" The patch including this feature is available since a long time so what's happening ? K. From kent37 at tds.net Wed Feb 8 12:16:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 06:16:01 -0500 Subject: [Tutor] Finding bottom level directories, and command-line arguments In-Reply-To: <667ca7b60602071754w6bec5639x@mail.gmail.com> References: <667ca7b60602071521i1b85076dr@mail.gmail.com> <667ca7b60602071754w6bec5639x@mail.gmail.com> Message-ID: <43E9D2F1.2000504@tds.net> Simon Gerber wrote: > I've got this: > > ------- > def isBottomDir(path): > for item in os.listdir(path): > if os.path.isdir(os.path.join(path,item)): > return False > return True > ------- > > Is that an acceptable way of doing this? I've been reading > http://thedailywtf.com for a month or so now - and though I've yet to > see a Python example cross their pages, I'm rather terrified of > becoming the first :) It's fine, relax :-) > > To iterate through the directories, the following works for me: > > ------- > for root, dirs, files in os.walk('~\Test'): > if test_dir.isBottomDir(root) == True: print root > ------- > > Is it worthwhile trying to write my own recursive function for this? > Or can I safely leave this task to to os.walk without inviting > ridicule from the programming community. Use os.walk(), reinventing the wheel is more likely to invite ridicule ;) But note the three values you get from os.walk() - the current dir (root), a list of dirs in root, a list of files in root...hmm, do you really need to call isBottomDir()? > >>There's a module that does this called 'optparse': >> >> http://www.python.org/doc/lib/module-optparse.html >> >>Try reusing that first, because it's been fairly well exercised and tuned >>to what people expect from an option parser. > > > Excellent. That looks like what I was looking for. There is a great cookbook recipe that makes using optparse as easy as writing a "usage" string: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844 Kent From kent37 at tds.net Wed Feb 8 14:37:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 08:37:18 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <20060208121733.22395416.klappnase@freenet.de> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> Message-ID: <43E9F40E.60609@tds.net> Michael Lange wrote: > On Tue, 7 Feb 2006 23:31:06 +0100 > Michael Lange wrote: > > >>So I think I need two Condition objects here; it is most important here that thread 1 does not >>block to minimize the risk of recording buffer overruns, but from reading the docs I am >>not sure about the correct procedure. So if I change self.rec_locked and self.vu_locked from the >>code above to be Condition objects is it correct to do: >> > > > > Ok, some testing gave me the answer, with the code I posted I got an AssertionError, so obviously > the release() call has to be inside the "if self.rec_lock.acquire(blocking=0):" block. > So now my functions look like: > > gui thread (periodically called by Tkinter): > > def get_peaks(self): > if not self.vu_lock.acquire(blocking=0): > return None > data = [x for x in self.vubuffer] > self.vubuffer = [] > self.vu_lock.release() > if not data: > return None > left, right = 0, 0 > for d in data: > left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left) > right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right) > return left, right > > child thread 1: > > vubuffer = [] > recbuffer = [] > while self.running: > data = self._audioobj.read(self._fragsize)# read data from soundcard > vubuffer.append(data) > if self.vu_lock.acquire(blocking=0): > self.vubuffer += vubuffer > vubuffer = [] > self.vu_lock.release() > if self.recording: > recbuffer.append(data) > if self.rec_lock.acquire(blocking=0): > self.recbuffer += recbuffer > recbuffer = [] > self.rec_lock.release() > > child thread 2: > > while self.recording: > # wait a moment until there is something in the buffer to be written > data = [] > time.sleep(0.1) > if self.rec_lock.acquire(blocking=0): > data = [x for x in self.recbuffer] > self.recbuffer = [] > self.rec_lock.release() > for d in data: > self._waveobj.writeframesraw(d)# write data to file > This is much better than your original. Another architecture you might consider is to have thread 1 put the actual acquired buffers into two Queues that are read by the two consumer threads. This would save you a lot of copying and give you a cleaner implementation. It may block on the producer thread but the Queue is locked only while something is actually being put in or taken out so the blocks should be short. For example (not tested!): def get_peaks(self): try: data = self.vu_queue.get_nowait() except Queue.Empty: return None left, right = 0, 0 for d in data: left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left) right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right) return left, right child thread 1: while self.running: data = self._audioobj.read(self._fragsize)# read data from soundcard self.vu_queue.put(data) self.rec_queue.put(data) child thread 2: while self.recording: data = self.rec_queue.get() for d in data: self._waveobj.writeframesraw(d)# write data to file > This *seems* to work, however it looks like this code does not separate properly the gui from the child > threads which everyone says should be avoided in any case. I don't understand your concern here. > On the other hand, with the technique I used before, with a boolean as "lock", like: > > if not self.vu_locked: > self.vu_locked = 1 > self.vubuffer += vubuffer > vubuffer = [] > self.vu_locked = 0 > > it seems like the worst case is that both the gui and the child thread pass the test "if not self.vu_locked" at > the same time which might cause some data to be lost from the vubuffer list; probably that is something > I could live with. You will be reading and writing the same list from two different threads, which seems like a bad idea. > So now my question: > Does anyone know how a threading.Condition() object is handled internally, so maybe its methods actually > can be called safely from the gui thread? Take a look at the source, threading is in Python. Kent From natmenon at yahoo.com Wed Feb 8 18:19:12 2006 From: natmenon at yahoo.com (Natasha Menon) Date: Wed, 8 Feb 2006 09:19:12 -0800 (PST) Subject: [Tutor] python help Message-ID: <20060208171913.15423.qmail@web52105.mail.yahoo.com> Hi, I have a few doubts in python programming. C if any of u can help me out. 1. In a file called string_stuff.py i have to write a function called frequencies that takes a string as a parameter and returns a dictionary where the keys are the characters from the string and each value is an integer indicating the number of times the key appeared in the string. 2. Similary in the same file string_stuff.py, have to write a function called locations that takes a string as a parameter and returns a dictionary where the keys are the characters from the string and each value is a list indicating the indices in the string at which the key appears, sorted in increasing order. 3. In the same file string_stuff.py, write a function called concordance that takes an open file as a parameter and returns a dictionary where the keys are the strings from the file and each value is a list of line numbers of the lines in which the key appeared, sorted in increasing order. Start counting at 0. Each line number should appear at most once in a list, even if a word appears twice on a line. You may assume that the input consists only of alphabetic letters (a-z, A-Z) and whitespace. Id really appreciate if you could help me on these small question. I am tryin to learn to program in python. Thanks, Natasha --------------------------------- Brings words and photos together (easily) with PhotoMail - it's free and works with Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060208/c5190e23/attachment.htm From m_webber_sydney at yahoo.com.au Wed Feb 8 18:58:18 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Wed, 8 Feb 2006 17:58:18 -0000 Subject: [Tutor] python help In-Reply-To: <20060208171913.15423.qmail@web52105.mail.yahoo.com> Message-ID: <000d01c62cd9$3e4ac250$0200a8c0@kookaburra> These sound like homework questions, in which case it would not be right for us to just give you the answer (and it would not be right for you to ask for it). If you can show us what you have tried so far, maybe we can give you some hints ... ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Natasha Menon Sent: 08 February 2006 17:19 To: tutor at python.org Subject: [Tutor] python help Hi, I have a few doubts in python programming. C if any of u can help me out. 1. In a file called string_stuff.py i have to write a function called frequencies that takes a string as a parameter and returns a dictionary where the keys are the characters from the string and each value is an integer indicating the number of times the key appeared in the string. 2. Similary in the same file string_stuff.py, have to write a function called locations that takes a string as a parameter and returns a dictionary where the keys are the characters from the string and each value is a list indicating the indices in the string at which the key appears, sorted in increasing order. 3. In the same file string_stuff.py, write a function called concordance that takes an open file as a parameter and returns a dictionary where the keys are the strings from the file and each value is a list of line numbers of the lines in which the key appeared, sorted in increasing order. Start counting at 0. Each line number should appear at most once in a list, even if a word appears twice on a line. You may assume that the input consists only of alphabetic letters (a-z, A-Z) and whitespace. Id really appreciate if you could help me on these small question. I am tryin to learn to program in python. Thanks, Natasha From klappnase at freenet.de Wed Feb 8 19:11:25 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 8 Feb 2006 19:11:25 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43E9F40E.60609@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> <43E9F40E.60609@tds.net> Message-ID: <20060208191125.5cd23f5c.klappnase@freenet.de> On Wed, 08 Feb 2006 08:37:18 -0500 Kent Johnson wrote: > Another architecture you might consider is to have thread 1 put the > actual acquired buffers into two Queues that are read by the two > consumer threads. This would save you a lot of copying and give you a > cleaner implementation. It may block on the producer thread but the > Queue is locked only while something is actually being put in or taken > out so the blocks should be short. > > For example (not tested!): > def get_peaks(self): > try: > data = self.vu_queue.get_nowait() > except Queue.Empty: > return None > left, right = 0, 0 > for d in data: > left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left) > right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right) > return left, right > > child thread 1: > > while self.running: > data = self._audioobj.read(self._fragsize)# read data from > soundcard > self.vu_queue.put(data) > self.rec_queue.put(data) > > child thread 2: > > while self.recording: > data = self.rec_queue.get() > for d in data: > self._waveobj.writeframesraw(d)# write data to file > Thanks Kent, the problem with Queues is that Queue.get() returns only one item at a time, but I found that depending on cpu load and disk usage hundreds of data fragments may accumulate into the recording buffer, so in the "writer" thread I would have to use something like (and similar in the get_peaks() method): while self.recording: data = [] while not self.rec_queue.empty(): try: data.append(self.rec_queue.get(block=0)) except Queue.Empty: break for d in data: self._waveobj.writeframesraw(d) I am not sure if this approach is more robust than the one that uses Condition() objects, however I don't think the code looks cleaner. > > > This *seems* to work, however it looks like this code does not separate properly the gui from the child > > threads which everyone says should be avoided in any case. > > I don't understand your concern here. > Maybe it is just because I have not fully understood how the Condition objects work; what I had in mind are warnings like this one (from http://www.astro.washington.edu/owen/TkinterSummary.html): All Tkinter access must be from the main thread (or, more precisely, the thread that called mainloop). Violating this is likely to cause nasty and mysterious symptoms such as freezes or core dumps. Yes this makes combining multi-threading and Tkinter very difficult. The only fully safe technique I have found is polling (e.g. use after from the main loop to poll a threading Queue that your thread writes). I have seen it suggested that a thread can safely use event_create to communicate with the main thread, but have found this is not safe. I guess I have to spend a second thought at this. Thanks again Michael From kent37 at tds.net Wed Feb 8 19:47:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 13:47:39 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <20060208191125.5cd23f5c.klappnase@freenet.de> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> <43E9F40E.60609@tds.net> <20060208191125.5cd23f5c.klappnase@freenet.de> Message-ID: <43EA3CCB.9040304@tds.net> Michael Lange wrote: > On Wed, 08 Feb 2006 08:37:18 -0500 > Kent Johnson wrote: >>child thread 2: >> >> while self.recording: >> data = self.rec_queue.get() >> for d in data: >> self._waveobj.writeframesraw(d)# write data to file >> > > Thanks Kent, > > the problem with Queues is that Queue.get() returns only one item at a time, but I found that depending > on cpu load and disk usage hundreds of data fragments may accumulate into the recording buffer, so in the "writer" > thread I would have to use something like (and similar in the get_peaks() method): > > while self.recording: > data = [] > while not self.rec_queue.empty(): > try: > data.append(self.rec_queue.get(block=0)) > except Queue.Empty: > break > for d in data: > self._waveobj.writeframesraw(d) > > I am not sure if this approach is more robust than the one that uses Condition() objects, > however I don't think the code looks cleaner. I don't understand why this is better than my code. It's a little different - you get all the data, then write all the data; I get a little, write a little - but since you are writing one datum at a time in both cases, I don't know why it would make much difference. You should be able to take the try/except out of your version, since this code is the only consumer from the Queue, if queue.empty() is false, queue.get() should succeed. In the vu meter thread I can see you might want to consume a minimum length of data but again that doesn't seem so hard. OTOH your latest code looks OK too, this was just a suggestion. >>>This *seems* to work, however it looks like this code does not separate properly the gui from the child >>>threads which everyone says should be avoided in any case. >> >>I don't understand your concern here. >> > Maybe it is just because I have not fully understood how the Condition objects work; what I had in mind are > warnings like this one (from http://www.astro.washington.edu/owen/TkinterSummary.html): > > All Tkinter access must be from the main thread (or, more precisely, the thread that called mainloop). OK, yes. What this means is that any code that changes the state of the GUI should be called from the main thread. In your case, that means that the thread that updates the vu meter must be the main thread. If you are calling get_peaks() from a scheduled Tkinter task (scheduled with after() or after_idle()) you will be fine. One way this problem comes up is if you have started a thread to run a long-running task and you want to update a status bar in the GUI. You can't update the GUI directly from the worker thread, you have to pass the status info back into the main thread somehow. Kent From tim.peters at gmail.com Wed Feb 8 20:07:58 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 8 Feb 2006 14:07:58 -0500 Subject: [Tutor] [Python-Dev] small floating point number problem In-Reply-To: <001c01c62c86$d694beb0$b83efea9@RaymondLaptop1> References: <006d01c62c7d$d7bab730$1f2c4fca@csmith> <001c01c62c86$d694beb0$b83efea9@RaymondLaptop1> Message-ID: <1f7befae0602081107h621e299i2f2269386b41e656@mail.gmail.com> [Raymond Hettinger] > ... > The asymmetric handling of denormals by the atof() and ftoa() functions is > why you see a difference. A consequence of that asymmetry is the breakdown > of the expected eval(repr(f))==f invariant: Just noting that such behavior is a violation of the 754 standard for string->double conversion. But Microsoft's libraries don't _claim_ to support the 754 standard, so good luck suing them ;-). Python doesn't promise anything here either. From dyoo at hkn.eecs.berkeley.edu Wed Feb 8 21:30:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 12:30:39 -0800 (PST) Subject: [Tutor] distutils and record-rpm not recognized In-Reply-To: <43E9D2CD.8090309@laposte.net> Message-ID: On Wed, 8 Feb 2006, le dahut wrote: > I've Python 2.4.1 installed and 'setup.py' doesn't recognize the > '--record-rpm' option : > "error: option --record-rpm not recognized" > > The patch including this feature is available since a long time so > what's happening ? Hi Le Dahut, You may be better off asking this on comp.lang.python --- I'm not sure anyone here on Tutor can really help with your question. I'm assuming that you're talking about patch 755286? https://sourceforge.net/tracker/?func=detail&atid=305470&aid=755286&group_id=5470 According to the discussion on this patch, this has not made it into trunk yet --- it's still an "open" issue. The early discussion there mentioned that the quality of the patch wasn't up to standard. In any case, this is something we at Tutor have no control over. Bring it up on comp.lang.python, and maybe you can attract attention to this again. From rshepard at appl-ecosys.com Wed Feb 8 21:35:20 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Wed, 8 Feb 2006 12:35:20 -0800 (PST) Subject: [Tutor] Syntax Question Message-ID: I'm trying to understand how to write SQL statements using pysqlite. The problem is that if I use newlines to format the SQL statements as I would with straight SQLite or PostgreSQL, python complains because it sees the newline before the end of the quoted string. So, I make the CREATE TABLE command one long string, since the column names are separated by commas. But, I'm stuck trying to write a trigger since there are no commas separating phrases and python doesn't like it run together as a single string. There must be something that I'm missing here. TIA, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From dyoo at hkn.eecs.berkeley.edu Wed Feb 8 21:36:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 12:36:36 -0800 (PST) Subject: [Tutor] python help In-Reply-To: <000d01c62cd9$3e4ac250$0200a8c0@kookaburra> Message-ID: > These sound like homework questions, in which case it would not be right > for us to just give you the answer (and it would not be right for you to > ask for it). Agreed; these are not small questions at all. Natasha, if you're having trouble, please be more specific about what you're getting stuck on. Don't just give us homework questions to work on, because that gives us very little information on what in particular you're having problems with. As it is, it looks like each question assumes that you're familiar with loops, dictionaries, strings, and File I/O. That's a tall order; we can't just explain all of that, because we'd end up just regurgitating whatever book or tutorial you're already using, and that's no good to you! So try to show us more of what you've tried; that'll help us see where you need help, and we can be more targetted in what we try to explain. By the way, you may find the tutorials at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers helpful in learning Python. From dyoo at hkn.eecs.berkeley.edu Wed Feb 8 21:41:10 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 12:41:10 -0800 (PST) Subject: [Tutor] Syntax Question In-Reply-To: Message-ID: On Wed, 8 Feb 2006, Rich Shepard wrote: > I'm trying to understand how to write SQL statements using pysqlite. > The problem is that if I use newlines to format the SQL statements as I > would with straight SQLite or PostgreSQL, python complains because it > sees the newline before the end of the quoted string. Hi Rich, Odd. Can you show us that complaint? Show us the error string. There are several possibilities here, but I hate guessing. *grin* Show us the exact error message you're getting, and that'll hint at what's really going on. Normal string literals can't span lines, but triple-quoted string literals can: ###### >>> "hello world File "", line 1 "hello world ^ SyntaxError: EOL while scanning single-quoted string >>> """hello world ... this is a test. ... """ 'hello world\nthis is a test.\n' ###### The idea is that it's all to easy to leave off the terminating quote on single quoted strings, so the SyntaxError tries to be good about giving an early warning. But if we do want to make a string literal that spans across lines, we can deliberately do so by using triple-quoted strings. From rshepard at appl-ecosys.com Wed Feb 8 22:02:46 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Wed, 8 Feb 2006 13:02:46 -0800 (PST) Subject: [Tutor] Syntax Question In-Reply-To: References: Message-ID: On Wed, 8 Feb 2006, Danny Yoo wrote: > Odd. Can you show us that complaint? Show us the error string. There are > several possibilities here, but I hate guessing. *grin* Show us the exact > error message you're getting, and that'll hint at what's really going on. > > Normal string literals can't span lines, but triple-quoted string literals > can: Danny, True. I thought that triple-quoted strings were valid only as docstring comments. [rshepard at salmo /data1/eikos]$ python eikos.py File "eikos.py", line 545 self.cur.execute("CREATE TRIGGER fki_comp_cat BEFORE INSERT ON component FOR EACH ROW BEGIN SELECT RAISE(ROLLBACK, 'insert on table "category" violates foreign key constraint "fk_comp_cat"') WHERE NEW.comp_cat IS NOT NULL AND (SELECT cat_name FROM category WHERE cat_name = NEW.comp_cat) IS NULL END") ^ SyntaxError: invalid syntax I will try it with triple quotes because it's so much easier to read that way. Thanks, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From klappnase at freenet.de Wed Feb 8 22:33:55 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 8 Feb 2006 22:33:55 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43EA3CCB.9040304@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> <43E9F40E.60609@tds.net> <20060208191125.5cd23f5c.klappnase@freenet.de> <43EA3CCB.9040304@tds.net> Message-ID: <20060208223355.24c25496.klappnase@freenet.de> On Wed, 08 Feb 2006 13:47:39 -0500 Kent Johnson wrote: > > while self.recording: > > data = [] > > while not self.rec_queue.empty(): > > try: > > data.append(self.rec_queue.get(block=0)) > > except Queue.Empty: > > break > > for d in data: > > self._waveobj.writeframesraw(d) > I don't understand why this is better than my code. It's a little > different - you get all the data, then write all the data; I get a > little, write a little - but since you are writing one datum at a time > in both cases, I don't know why it would make much difference. > Sorry, I missed to insert the time.sleep(0.1) I used in my original while loop into the example above. The reason for using time.sleep() is that I need to avoid lots of loops over an empty buffer. The amount of time until the producer thread reads a new data fragment into the buffer may be significant, depending on the fragment size requested by the driver (e.g my fm801 card wants fragments of 16384 bytes which is about 0.09 audio seconds). On the other hand the buffer may contain hundreds of kB of data if other processes cause a lot of disk I/O. > You should be able to take the try/except out of your version, since > this code is the only consumer from the Queue, if queue.empty() is > false, queue.get() should succeed. > Not if I call it with block=0; if I understand the docs correctly the queue will raise a Queue.Empty exception if the queue is currently locked by another thread. > In the vu meter thread I can see you might want to consume a minimum > length of data but again that doesn't seem so hard. > > OTOH your latest code looks OK too, this was just a suggestion. > It was a good suggestion, I never looked at the Queue class before, and it's definitely good to know about it. In my special case here, your other suggestion of using Condition() seems to allow me easier handling of my buffers, though. Another part of my code I did not post here that is executed when the recording is stopped (i.e. self.recording is set to 0) also seems to be easier to implement with the Condition technique. > > All Tkinter access must be from the main thread (or, more precisely, > the thread that called mainloop). > > OK, yes. What this means is that any code that changes the state of the > GUI should be called from the main thread. In your case, that means that > the thread that updates the vu meter must be the main thread. If you are > calling get_peaks() from a scheduled Tkinter task (scheduled with > after() or after_idle()) you will be fine. > Yes, that's what I am doing. I think I just was confused because I did not understand what the Condition class does. Now I think I see clearer, thanks for all your help. Michael From john at fouhy.net Wed Feb 8 22:34:00 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 9 Feb 2006 10:34:00 +1300 Subject: [Tutor] Syntax Question In-Reply-To: References: Message-ID: <5e58f2e40602081334s4a4a72c5s@mail.gmail.com> On 09/02/06, Rich Shepard wrote: > self.cur.execute("CREATE TRIGGER fki_comp_cat BEFORE INSERT ON component > FOR EACH ROW BEGIN SELECT RAISE(ROLLBACK, 'insert on table "category" > violates foreign key constraint "fk_comp_cat"') WHERE NEW.comp_cat IS NOT > NULL AND (SELECT cat_name FROM category WHERE cat_name = NEW.comp_cat) IS > NULL END") > ^ > SyntaxError: invalid syntax At a guess, the error here is that the double-quote before CREATE is matching the double quote before 'category', finishing the string there. A triple-quoted string should work for you because lone single or double quotes in a triple-quoted string are passed literally. Otherwise, you need to escape them --- ie: 'insert on table \"category\" ...'. HTH! -- John. From magoldfish at gmail.com Wed Feb 8 23:07:38 2006 From: magoldfish at gmail.com (Marcus Goldfish) Date: Wed, 8 Feb 2006 17:07:38 -0500 Subject: [Tutor] quirky multiple inheritance example!? Message-ID: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com> Hi, I ran across a strange problem using mulitple inheritance that I hope someone can explain. Basically, I am implementing a Publisher pattern, and when I try to add threading, the order I list Base classes matters! Here is the short sample code-- all help explaining this is appreciated! Thanks, Marcus --- import threading class Publisher(object): def __init__(self): self.listeners = {} def register(self, id, object): self.listeners[id] = self.listeners.get(id, object) # This *FAILS* with AttributeError: 'FancyPublisher' # object has no attribute 'listeners' class FancyPublisher(threading.Thread, Publisher): def __init__(self): super(FancyPublisher, self).__init__() F = FancyPublisher() F.register('me', None) # However, this succeeds!? class FancyPublisher(Publisher, threading.Thread): def __init__(self): super(FancyPublisher, self).__init__() F = FancyPublisher() F.register('me', None) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060208/ebc298bb/attachment-0001.html From alan.gauld at freenet.co.uk Wed Feb 8 23:06:57 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Feb 2006 22:06:57 -0000 Subject: [Tutor] python help References: <20060208171913.15423.qmail@web52105.mail.yahoo.com> Message-ID: <00c001c62cfb$fa8a2a10$0b01a8c0@xp> > I have a few doubts in python programming. C if any of u can help me out. Have no doubts - Python can do all of this. > In a file called string_stuff.py i have to write a function called > frequencies > that takes a string as a parameter and returns a dictionary where the keys > are the characters from the string and each value is an integer indicating > the > number of times the key appeared in the string. What is your doubt here? Can you create a function called frequencies that has a string parameter and returns a dictionary? Can you read a string character by character into said dictionary? Can you increment the count for each character as you do so? Where is the problem that you need help with? > Similary in the same file string_stuff.py, have to write a function > called locations > that takes a string as a parameter and returns a dictionary where the keys > are > the characters from the string and each value is a list indicating the > indices in > the string at which the key appears, sorted in increasing order. Similarly this is a pretty clear description of how to solve the problem What bit are you having trouble with? Show us your code and we might be able to help. > In the same file string_stuff.py, write a function called concordance > that > takes an open file as a parameter and returns a dictionary where the > keys are the strings from the file and each value is a list of line > numbers > of the lines in which the key appeared, sorted in increasing order. > Start counting at 0. Each line number should appear at most once in > a list, even if a word appears twice on a line. You may assume that the > input consists only of alphabetic letters (a-z, A-Z) and whitespace. Slightly trickier but not much if you've already done the first two problems. Hint: Remember that you can store lists in dictionaries too. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rshepard at appl-ecosys.com Wed Feb 8 23:52:18 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Wed, 8 Feb 2006 14:52:18 -0800 (PST) Subject: [Tutor] Time to Use a Global Variable? Message-ID: In my wxPython application the UI is run out of class MyFrame. The method associated with File->Quit is called OnFileQuit. All the code for pysqlite is in another class called DBinterface, and that has a method closeDB(): def closeDb(self): """ Closes the database connection explicitly. """ self.cur.close() self.con.close() OnFileQuit looks like this: def OnFileQuit(self, event): closeDb() fn.close() self.Close() When I test the application and try to close it, python complains File "eikos.py", line 315, in OnFileQuit closeDb() NameError: global name 'closeDb' is not defined I've tried changing OnFileQuit to call DBinterface.closeDB(), but that doesn't work. Obviously I still haven't completely grokked how to refer in one class to a method defined in another class. Of course, I've not explicitly created an instance of DBinterface within MyFrame, so that may be the problem. A clue stick is welcome. Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From dyoo at hkn.eecs.berkeley.edu Wed Feb 8 23:56:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 14:56:46 -0800 (PST) Subject: [Tutor] Finding bottom level directories, and command-line arguments In-Reply-To: <667ca7b60602071754w6bec5639x@mail.gmail.com> Message-ID: > I've got this: > > ------- > def isBottomDir(path): > for item in os.listdir(path): > if os.path.isdir(os.path.join(path,item)): > return False > return True > ------- > > Is that an acceptable way of doing this? Hi Simon, Your code looks good to me! > I've been reading http://thedailywtf.com for a month or so now - and > though I've yet to see a Python example cross their pages, I'm rather > terrified of becoming the first :) That web site (http://thedailywtf.com) is amusing in its way, but my problem with it is that so many of the people there enjoy mocking others in a mean-spirited and immature way. Programming well is a hard thing. The adolescent posturing I see there isn't admirable to me. It's also very sad to see that, for any given bad code, there's a lot more really bad responses. So my feelings are mixed about it, in the same sort of way that I have misgivings toward Slashdot. *grin* > To iterate through the directories, the following works for me: > > ------- > for root, dirs, files in os.walk('~\Test'): > if test_dir.isBottomDir(root) == True: print root > ------- > > Is it worthwhile trying to write my own recursive function for this? It's perfectly ok to take advantage of os.walk(); I like this code. Good luck to you! From kent37 at tds.net Thu Feb 9 00:14:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 18:14:14 -0500 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <20060208223355.24c25496.klappnase@freenet.de> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> <43E9F40E.60609@tds.net> <20060208191125.5cd23f5c.klappnase@freenet.de> <43EA3CCB.9040304@tds.net> <20060208223355.24c25496.klappnase@freenet.de> Message-ID: <43EA7B46.6010104@tds.net> Michael Lange wrote: > Sorry, I missed to insert the time.sleep(0.1) I used in my original while loop into the example above. > The reason for using time.sleep() is that I need to avoid lots of loops over an empty buffer. > The amount of time until the producer thread reads a new data fragment into the buffer may > be significant, depending on the fragment size requested by the driver (e.g my fm801 card > wants fragments of 16384 bytes which is about 0.09 audio seconds). On the other hand the > buffer may contain hundreds of kB of data if other processes cause a lot of disk I/O. Using Queue.get() will do this for you automatically. If there is no data it will block until something is added to the queue and you avoid a polling loop. If there is data it will return it quickly. > >>You should be able to take the try/except out of your version, since >>this code is the only consumer from the Queue, if queue.empty() is >>false, queue.get() should succeed. >> > Not if I call it with block=0; if I understand the docs correctly the queue will raise a Queue.Empty exception > if the queue is currently locked by another thread. No, the block flag controls whether the call will wait until something is in the queue or return immediately. The call to Queue.get() will always block waiting for the lock that controls access to the Queue; it can't even tell if the Queue is empty until it gets this lock. Kent From alan.gauld at freenet.co.uk Thu Feb 9 00:20:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Feb 2006 23:20:25 -0000 Subject: [Tutor] Syntax Question References: Message-ID: <00d201c62d06$3e27fea0$0b01a8c0@xp> > There must be something that I'm missing here. Triuple quoted strings :-) Take a look at my Databases topic for examples using SqlLite and triple quotes for the queries. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld . From kp8 at mac.com Thu Feb 9 00:29:49 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 8 Feb 2006 18:29:49 -0500 Subject: [Tutor] soundfile picker & rating system In-Reply-To: References: Message-ID: <99cac8583fc0c17b744d24d088cbb46a@mac.com> I am a little bit stuck .... I want to play a bunch of soundfiles randomly, but i want to give each soundfile a rating (say 0-100) and have the likelihood that the file be chosen be tied to its rating so that the higher the rating the more likely a file is to be chosen. Then i need some additional flags for repetition, and some other business. I am guessing a dictionary would be a great way to do this, with the key being the soundfile name and the values being my ratings and other flags & associated data. #soundfile name : [rating, %chance it will repeat/loop] sfiles = { ("sf001") : [85, 15], ("sf002") : [25, 75], ("sf003") : [95, 45], ("sf004") : [35, 95] } But i am stuck on how to do a random chooser that works according to my idea of choosing according to rating system. It seems to me to be a bit different that just choosing a weighted choice like so: def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item And i am not sure i want to have to go through what will be hundreds of sound files and scale their ratings by hand so that they all add up to 100%. I just want to have a long list that i can add too whenever i want, and assign it a grade/rating according to my whims! cheers, kevin From john at fouhy.net Thu Feb 9 00:44:39 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 9 Feb 2006 12:44:39 +1300 Subject: [Tutor] soundfile picker & rating system In-Reply-To: <99cac8583fc0c17b744d24d088cbb46a@mac.com> References: <99cac8583fc0c17b744d24d088cbb46a@mac.com> Message-ID: <5e58f2e40602081544qa35ae56j@mail.gmail.com> On 09/02/06, kevin parks wrote: > And i am not sure i want to have to go through what will be hundreds of > sound files and scale their ratings by hand so that they all add up to > 100%. I just want to have a long list that i can add too whenever i > want, and assign it a grade/rating according to my whims! Maybe something like this: songs = [('sf001', 43), ('sf002', 81), ('sf003', 79), ...] def pick(): total = sum(x[1] for x in songs) choice = random.randrange(total) # Find the song we want. current = 0 for song, rating in songs: if choice < current + rating: return song current += rating (the basic idea of this algorithm is to replace a list [(a, 5), (b, 3), (c, 6)] by [a,a,a,a,a,b,b,b,c,c,c,c,c,c] and then pick at random from that) There's a lot of scope for making this more efficient --- for example, if the list doesn't change much, you might precompute the cutoffs (eg: make a list [('sf001', 0, 43), ('sf002', 44, 125), ...]) and then do some kind of binary search to find the song you want. Also, this will mean that a song ranked 50 will be fifty times more likely to be chosen than a song ranked 1, while a song ranked 80 will be only 1.6 times more likely to be chosen than a song ranked 50. Maybe some kind of logarithmic transform might smooth things out a bit..? -- John. From kent37 at tds.net Thu Feb 9 00:50:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 18:50:49 -0500 Subject: [Tutor] quirky multiple inheritance example!? In-Reply-To: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com> References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com> Message-ID: <43EA83D9.1080509@tds.net> Marcus Goldfish wrote: > Hi, > > I ran across a strange problem using mulitple inheritance that I hope > someone can explain. Basically, I am implementing a Publisher pattern, > and when I try to add threading, the order I list Base classes matters! > Here is the short sample code-- all help explaining this is appreciated! > > Thanks, > Marcus > > --- > import threading > > class Publisher(object): > def __init__(self): self.listeners = {} > def register(self, id, object): > self.listeners[id] = self.listeners.get(id, object) > > > # This *FAILS* with AttributeError: 'FancyPublisher' > # object has no attribute 'listeners' > class FancyPublisher(threading.Thread, Publisher): > def __init__(self): > super(FancyPublisher, self).__init__() > > F = FancyPublisher() > F.register('me', None) > > > # However, this succeeds!? > class FancyPublisher(Publisher, threading.Thread): > def __init__(self): > super(FancyPublisher, self).__init__() > > F = FancyPublisher() > F.register('me', None) Wow, the third (sort of) threading question in a week! The problem is that neither Publisher nor threading.Thread calls super(...).__init__() in *its* __init__() method, so you are only initializing one of your base classes. I don't think your second FancyPublisher would work when you actually tried to run it as a thread. One solution is to just call both base class __init__() methods directly: class FancyPublisher(Publisher, threading.Thread): def __init__(self): FancyPublisher.__init__(self) threading.Thread.__init__(self) I think it would also work if Publisher.__init__ called super(Publisher, self).__init__() and Publisher is the first base class. This essay highlights some pitfalls with super() including the one you found: http://fuhm.net/super-harmful/ though it provoked a strong response on python-dev: http://mail.python.org/pipermail/python-dev/2005-January/050656.html Kent From kent37 at tds.net Thu Feb 9 00:56:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 18:56:02 -0500 Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: References: Message-ID: <43EA8512.9000805@tds.net> Rich Shepard wrote: > In my wxPython application the UI is run out of class MyFrame. The method > associated with File->Quit is called OnFileQuit. All the code for pysqlite is > in another class called DBinterface, and that has a method closeDB(): > > def closeDb(self): > """ > Closes the database connection explicitly. > """ > self.cur.close() > self.con.close() > > OnFileQuit looks like this: > > def OnFileQuit(self, event): > closeDb() > fn.close() > self.Close() > > When I test the application and try to close it, python complains > File "eikos.py", line 315, in OnFileQuit > closeDb() > NameError: global name 'closeDb' is not defined > > I've tried changing OnFileQuit to call DBinterface.closeDB(), but that > doesn't work. Obviously I still haven't completely grokked how to refer in > one class to a method defined in another class. Of course, I've not > explicitly created an instance of DBinterface within MyFrame, so that may be > the problem. Evidently closeDb is an instance method of some class you don't show here. Does DBinterface create and maintain a single instance of this class? or some other code creates an instance? You need to call closeDb on the DBinterface instance, it is not a module-level function. You haven't shown enough code for me to know how the OnFileQuit method might gain access to the DBinterface instance; how do you access other methods for working with the database? Kent From alan.gauld at freenet.co.uk Thu Feb 9 00:59:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Feb 2006 23:59:35 -0000 Subject: [Tutor] quirky multiple inheritance example!? References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com> Message-ID: <00e601c62d0b$b6dee930$0b01a8c0@xp> # This *FAILS* with AttributeError: 'FancyPublisher' # object has no attribute 'listeners' class FancyPublisher(threading.Thread, Publisher): def __init__(self): super(FancyPublisher, self).__init__() F = FancyPublisher() F.register('me', None) ------------------- The problem is that super appears to only work with single inheritance. There may be a way to makle it work for multiple inheritance by changing the second parameter but the documentration is a bit thin!! For that reason I tend not to use super but instead prefer the classical method of explicit call: class FancyPublisher(threading.Thread, Publisher): def __init__(self): Publisher.__init__(self) That way its clear which superclass is being called and I can call all of the superclasses in whichever order I want. Hopefully someone can explain how to use super properly to do this, but it beats me! (This is why super() doesn't appear in the OOP topic in my tutor, I found it more confusing than helpful for a beginner - and even for me!) Alan G From rshepard at appl-ecosys.com Thu Feb 9 01:20:04 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Wed, 8 Feb 2006 16:20:04 -0800 (PST) Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: <43EA8512.9000805@tds.net> References: <43EA8512.9000805@tds.net> Message-ID: On Wed, 8 Feb 2006, Kent Johnson wrote: > Evidently closeDb is an instance method of some class you don't show here. > Does DBinterface create and maintain a single instance of this class? or > some other code creates an instance? Kent, closeDB() is defined in the class DBinterface. That's the only instance for the database connection. > You need to call closeDb on the DBinterface instance, it is not a > module-level function. You haven't shown enough code for me to know how > the OnFileQuit method might gain access to the DBinterface instance; how > do you access other methods for working with the database? I tried calling DBinterface.closeDB(), but python tells me that DBinterface is not defined. And here I thought that I understood scoping and the use of classes. What shall I provide to help clarify the situation? The class DBinterface is about 300 lines long. The method closeDB() is defined in the class DBinterface. What I'm trying to do is to ensure that the database cursor and connection are closed when the user exits from the application. Class DBinterface has a __del__ method to clean up if the user forgets to close the open database, so I'm trying to learn how to explicitly close it. Thanks, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From benvinger at yahoo.co.uk Thu Feb 9 01:24:15 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 9 Feb 2006 00:24:15 +0000 (GMT) Subject: [Tutor] python help In-Reply-To: <20060208171913.15423.qmail@web52105.mail.yahoo.com> Message-ID: <20060209002415.37003.qmail@web25810.mail.ukl.yahoo.com> Why are these homework programming challenges so recognisable? It boils down to: Write a function that that uses X and Y techniques. The function may be hard and challenging to write but doesn't ever do anything interesting or anything that is useful and complete on its own. I realise teachers have to test mastery of certain techniques, but they seem to lack the imagination. Especially with modern languagues like Python, where you can write a whole program that actually does something usefull using only a few lines of code it should not be necessary to ask these kinds of dull questions. Just stick at it Natasha, it is far more interesting when you the programming challenge has to accomplish a real result. Ben --- Natasha Menon wrote: > Hi, > > I have a few doubts in python programming. C if > any of u can help me out. > > 1. > In a file called string_stuff.py i have to write a > function called frequencies that takes a string as a > parameter and returns a dictionary where the keys > are the characters from the string and each value is > an integer indicating the number of times the key > appeared in the string. > > 2. > Similary in the same file string_stuff.py, have to > write a function called locations that takes a > string as a parameter and returns a dictionary where > the keys are the characters from the string and each > value is a list indicating the indices in the string > at which the key appears, sorted in increasing > order. > > 3. > In the same file string_stuff.py, write a function > called concordance that takes an open file as a > parameter and returns a dictionary where the keys > are the strings from the file and each value is a > list of line numbers of the lines in which the key > appeared, sorted in increasing order. Start counting > at 0. Each line number should appear at most once in > a list, even if a word appears twice on a line. You > may assume that the input consists only of > alphabetic letters (a-z, A-Z) and whitespace. > > > Id really appreciate if you could help me on these > small question. I am tryin to learn to program in > python. > > Thanks, > Natasha > > > --------------------------------- > Brings words and photos together (easily) with > PhotoMail - it's free and works with Yahoo! Mail.> _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From nequeo at gmail.com Thu Feb 9 02:35:49 2006 From: nequeo at gmail.com (Simon Gerber) Date: Thu, 9 Feb 2006 12:35:49 +1100 Subject: [Tutor] Finding bottom level directories, and command-line arguments In-Reply-To: References: <667ca7b60602071754w6bec5639x@mail.gmail.com> Message-ID: <667ca7b60602081735l49016473h@mail.gmail.com> Hi Danny, > That web site (http://thedailywtf.com) is amusing in its way, but my > problem with it is that so many of the people there enjoy mocking others > in a mean-spirited and immature way. Programming well is a hard thing. > The adolescent posturing I see there isn't admirable to me. It's also very > sad to see that, for any given bad code, there's a lot more really bad > responses. So my feelings are mixed about it, in the same sort of way > that I have misgivings toward Slashdot. *grin* Yes... Slashdot. *shudder*. I've had two of my articles Slashdotted, and both times it left quite a bruise. If it happens again, I have resolved to simply not read the comments. Like Othello said, there are some things we are better off not knowing :) > It's perfectly ok to take advantage of os.walk(); I like this code. Excellent. But based on Kent's comment, I have discovered that ------ for root, dirs, files in os.walk(prog_variables['vid_path']): if dirs == []: print root ------ does the same thing. Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From dyoo at hkn.eecs.berkeley.edu Thu Feb 9 02:41:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 17:41:25 -0800 (PST) Subject: [Tutor] python help In-Reply-To: <20060209002415.37003.qmail@web25810.mail.ukl.yahoo.com> Message-ID: > I realise teachers have to test mastery of certain techniques, but they > seem to lack the imagination. I agree; the problem here, I think, is that these homework questions often focus WAY too much on Python-specific features, rather than on fundamental issues, and so the questions end up feeling very artificial. So the first question that says: > > In a file called string_stuff.py i have to write a function called > > frequencies that takes a string as a parameter and returns a > > dictionary where the keys are the characters from the string and each > > value is an integer indicating the number of times the key appeared in > > the string. has no human context whatsoever, so of course it's a useless homework problem. Why would someone want to take a useless histogram of a bunch of letters? What would be more interesting is putting it in context, say like: "We're writing a book report, but we notice that we use certain words a lot more than other words. It would be useful to get an idea of what words are being overused so we can get out our thesaurus out on those particular words. We need to know which words we're using, and how frequently we're using them..." The context has to be there for the problem to make sense: otherwise what often ends up happening is disattachment and disillusionment. And the result should be relevant and feel like a "real" thing to them, even if it is a simplification. And it doesn't have to be immediately useful for the student, just as long as that student sees that it might be useful to someone. And in this case, if we don't mention dictionaries initially, that's fine, because we can solve the problem with or without dictionaries. If we did want to force the use of dictionaries: 1. We can motivate it later by mentioning that we want to use the program on a term paper, and it's taking forever. 2. Or we can talk about how our friends have some other program that can plot histograms, but it expects to see a dictionary mapping items and their occurrence. Either way, there needs to be a reason, a "why" to these things. Unfortunately, it takes effort on a teacher's end to do this, but that's what they should be paid for! *grin* From victor at grupocdm.com Thu Feb 9 02:46:26 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 08 Feb 2006 19:46:26 -0600 Subject: [Tutor] Splitting long string into same len parts Message-ID: <1139449587.21137.14.camel@elrond> Hi to all, I'd like to split a long string into equally long strings (len(str) = 3). I did the following using regexes: >>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' >>> o = re.split(r'(...)', n) >>> print o ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', '', 'w0s', '', 'dq3', '', 'zjf', ''] Which gives me empty strings between each value. So to actually have this working I ended up filtering through a list comprehension: >>> o = [ x for x in re.split(r'(...)', n) if x ] >>> print o ['xb1', 'jyz', 'qnd', '1ee', 'nko', 'kqn', 'hep', '6vp', '692', 'qi9', 'tma', 'g3o', 'wzq', 'w0s', 'dq3', 'zjf'] This is what I needed. Is there an easier or more straightforward way to do this? Thanks. Victor From john at fouhy.net Thu Feb 9 03:01:13 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 9 Feb 2006 15:01:13 +1300 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: <1139449587.21137.14.camel@elrond> References: <1139449587.21137.14.camel@elrond> Message-ID: <5e58f2e40602081801u4332a3d7l@mail.gmail.com> On 09/02/06, Victor Bouffier wrote: > I'd like to split a long string into equally long strings (len(str) = > 3). I did the following using regexes: Remember that a string is just like a list (except that you can't modify it). So, for instance: >>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' >>> n[0:3], n[3:6] ('xb1', 'jyz') Can you see how to generate the slice boundaries for the length you need? -- John. From kent37 at tds.net Thu Feb 9 03:43:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 21:43:09 -0500 Subject: [Tutor] quirky multiple inheritance example!? In-Reply-To: <00e601c62d0b$b6dee930$0b01a8c0@xp> References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com> <00e601c62d0b$b6dee930$0b01a8c0@xp> Message-ID: <43EAAC3D.2060903@tds.net> Alan Gauld wrote: > The problem is that super appears to only work with single inheritance. > There may be a way to makle it work for multiple inheritance by changing > the second parameter but the documentration is a bit thin!! That's ironic - super() is intended to ease some of the problems with multiple inheritance especially diamond patterns. Some docs are here: http://www.python.org/2.2.3/descrintro.html#cooperation The problem with the OP is that not all the classes involved use super(). Kent From kent37 at tds.net Thu Feb 9 03:51:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Feb 2006 21:51:03 -0500 Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: References: <43EA8512.9000805@tds.net> Message-ID: <43EAAE17.4000300@tds.net> Rich Shepard wrote: > On Wed, 8 Feb 2006, Kent Johnson wrote: > >> Evidently closeDb is an instance method of some class you don't show >> here. >> Does DBinterface create and maintain a single instance of this class? or >> some other code creates an instance? > > > Kent, > > closeDB() is defined in the class DBinterface. That's the only > instance for > the database connection. > >> You need to call closeDb on the DBinterface instance, it is not a >> module-level function. You haven't shown enough code for me to know how >> the OnFileQuit method might gain access to the DBinterface instance; how >> do you access other methods for working with the database? > > > I tried calling DBinterface.closeDB(), but python tells me that > DBinterface > is not defined. And here I thought that I understood scoping and the use of > classes. > > What shall I provide to help clarify the situation? The class DBinterface > is about 300 lines long. OK. Suppose I have class DB(object): def __init__(self): self.conn = getDatabaseConnection() def closeDb(self): self.conn.close() def doSomethingInteresting(self): self.conn.execute(...) To use this class, I have to instantiate it: myDb = DB() Now I can say myDb.doSomethingInteresting() To close the connection, I have to call closeDb() on the *instance* - myDb - not on the class itself - DB: myDb.closeDb() Does this help? If not...where is your code that calls DBinterface to create an instance of DBinterface? Where do you store the value (the DBinterface instance)? How do you access it to do something interesting? Kent > > The method closeDB() is defined in the class DBinterface. What I'm trying > to do is to ensure that the database cursor and connection are closed when > the user exits from the application. Class DBinterface has a __del__ method > to clean up if the user forgets to close the open database, so I'm > trying to > learn how to explicitly close it. > > Thanks, > > Rich > From dyoo at hkn.eecs.berkeley.edu Thu Feb 9 03:55:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Feb 2006 18:55:48 -0800 (PST) Subject: [Tutor] Splitting long string into same len parts In-Reply-To: <1139449587.21137.14.camel@elrond> Message-ID: On Wed, 8 Feb 2006, Victor Bouffier wrote: > Hi to all, > > I'd like to split a long string into equally long strings (len(str) = > 3). I did the following using regexes: > > >>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' > >>> o = re.split(r'(...)', n) > >>> print o > ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', > 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', > '', 'w0s', '', 'dq3', '', 'zjf', ''] > > Which gives me empty strings between each value. Hi Victor, Try using re.findall() instead of re.split(). The behavior you're seeing with split is perfectly logical: each pair of empty strings is being split by that three-character sequence. Best of wishes! From andre.roberge at gmail.com Thu Feb 9 04:05:34 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 8 Feb 2006 23:05:34 -0400 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: References: <1139449587.21137.14.camel@elrond> Message-ID: <7528bcdd0602081905l4f439c7cxffa8b6ef3f00bda3@mail.gmail.com> On 2/8/06, Danny Yoo wrote: > > > On Wed, 8 Feb 2006, Victor Bouffier wrote: > > > Hi to all, > > > > I'd like to split a long string into equally long strings (len(str) = > > 3). I did the following using regexes: > > > > >>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' > > >>> o = re.split(r'(...)', n) > > >>> print o > > ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', > > 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', > > '', 'w0s', '', 'dq3', '', 'zjf', ''] > > > > Which gives me empty strings between each value. > > Hi Victor, > > Try using re.findall() instead of re.split(). The behavior you're seeing > with split is perfectly logical: each pair of empty strings is being split > by that three-character sequence. There's a tongue-in-cheek quote that I really like: "Sometimes you have a programming problem and it seems like the best solution is to use regular expressions; now you have two problems." Given that you are thinking of using "re", and that you seem to have a working solution, I doubt this is a homework problem... so, how about the untested: n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' length = len(n) o = [] for i in range(0, length, 3): o.append(n[i:i+3]) Andr? From rshepard at appl-ecosys.com Thu Feb 9 05:06:02 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Wed, 8 Feb 2006 20:06:02 -0800 (PST) Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: <43EAAE17.4000300@tds.net> References: <43EA8512.9000805@tds.net> <43EAAE17.4000300@tds.net> Message-ID: On Wed, 8 Feb 2006, Kent Johnson wrote: > OK. Suppose I have Sigh. I was going too fast and, of course, I got ahead of myself. > To use this class, I have to instantiate it: > myDb = DB() Yes, that's all in the example's __main__ and I didn't put it in my application. Will do so right away. Thank you for using a soft clue stick. RIch -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From emile at fenx.com Thu Feb 9 07:36:33 2006 From: emile at fenx.com (Emile van Sebille) Date: Wed, 8 Feb 2006 22:36:33 -0800 Subject: [Tutor] Splitting long string into same len parts References: <1139449587.21137.14.camel@elrond> <7528bcdd0602081905l4f439c7cxffa8b6ef3f00bda3@mail.gmail.com> Message-ID: "Andre Roberge" wrote in message > There's a tongue-in-cheek quote that I really like: > "Sometimes you have a programming problem and it seems like the best > solution is to use regular expressions; now you have two problems." +1 -- There are some things re is good for, but mainly it's good motivation to just do it in python... > n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' > length = len(n) > o = [] > for i in range(0, length, 3): > o.append(n[i:i+3]) > Or as a one-liner... o = [ n[ii:ii+3] for ii in range(0,len(n),3) ] Emile From victor at grupocdm.com Thu Feb 9 08:43:22 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Thu, 09 Feb 2006 01:43:22 -0600 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: References: <1139449587.21137.14.camel@elrond> <7528bcdd0602081905l4f439c7cxffa8b6ef3f00bda3@mail.gmail.com> Message-ID: <1139471002.21137.18.camel@elrond> Hi Emile and John, Thanks a lot for your insight. There is always a better way, or at least a more pythonic one. Take care. Victor. On Wed, 2006-02-08 at 22:36 -0800, Emile van Sebille wrote: > "Andre Roberge" wrote in message > > > There's a tongue-in-cheek quote that I really like: > > "Sometimes you have a programming problem and it seems like the best > > solution is to use regular expressions; now you have two problems." > > +1 -- There are some things re is good for, but mainly it's good > motivation to just do it in python... > > > n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' > > length = len(n) > > o = [] > > for i in range(0, length, 3): > > o.append(n[i:i+3]) > > > > Or as a one-liner... > > o = [ n[ii:ii+3] for ii in range(0,len(n),3) ] > > Emile > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Feb 9 10:16:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:16:55 -0000 Subject: [Tutor] Time to Use a Global Variable? References: Message-ID: <00fb01c62d59$92539bd0$0b01a8c0@xp> Rich, I love the way you post problems and also post a possible solution - usually the correct one! :-) > I've tried changing OnFileQuit to call DBinterface.closeDB(), but that > doesn't work. Obviously I still haven't completely grokked how to refer in > one class to a method defined in another class. Of course, I've not > explicitly created an instance of DBinterface within MyFrame, so that may > be > the problem. Yes that's the problem. Classes are templates for creating objects, so you don't call methods on the classes themselves(*). You have to create an instance and work on that. In your case you would create the instance as part of the initialisation of the application. You could create the instance outside the UI and pass it in as an argument to the constructor but either way the app object has a reference to the database object. (*)You can define "class methods" which do belong to the class and can be called directly without an instance but those are rather esoteric items which we can safely ignore here. Dipping briefly into analogy mode, this is all quite logical. When Toyota create a car they do so from a set of designs. You can't drive the design you have to create an instance of a car from the design first. The class is like the design and the instance is the car. HTH, Alan G. From alan.gauld at freenet.co.uk Thu Feb 9 10:25:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:25:20 -0000 Subject: [Tutor] Finding bottom level directories, and command-line arguments References: Message-ID: <00ff01c62d5a$bf835680$0b01a8c0@xp> I've been away so missed this thead earlier but one wee thing I just noticed: >> ------- >> def isBottomDir(path): >> for item in os.listdir(path): >> if os.path.isdir(os.path.join(path,item)): >> return False >> return True >> ------- >> for root, dirs, files in os.walk('~\Test'): >> if test_dir.isBottomDir(root) == True: print root >> ------- Can be done more simply with: for root,dirs,files in os.walk('~/Test'): if not dirs: print root At a bottom node the dirs list from os.walk will be empty. And you can get the list of all bottom dirs with: leaves = [ root for (root,dirs,files) in os.walk(start) if not dirs] 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 Thu Feb 9 10:38:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:38:20 -0000 Subject: [Tutor] python help References: Message-ID: <011f01c62d5c$9078b9f0$0b01a8c0@xp> > has no human context whatsoever, so of course it's a useless homework > problem. Why would someone want to take a useless histogram of a bunch of > letters? Erm me! Communications analysts and cryptographers do that all the time! :-) The problem is fine, it's the context that would give it a purpose that is missing. If the problem were introduced with a little background rationale it might seem more relevant. Alan G. From alan.gauld at freenet.co.uk Thu Feb 9 10:34:57 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:34:57 -0000 Subject: [Tutor] python help References: <20060209002415.37003.qmail@web25810.mail.ukl.yahoo.com> Message-ID: <011b01c62d5c$17b64460$0b01a8c0@xp> Ben, > Write a function that that uses X and Y techniques. > I realise teachers have to test mastery of certain > techniques, but they seem to lack the imagination. To be fair to teachers, its often the students who lack imagination. If you pose the problem as write an application to count the numbers of each letter in a paragraph of text or whatever many students will not make the connection to the technique that they are supposed to be using. Or they get so involved in the sub problem of creating/reading the paragraph of text that they don't spend time on the counting problem. A an example I have seen a solution to the above problem that used multiple loops to create a list of unique words. It then iterated over that list counting the occurences of each unique word. This solution required 2 loops overv the text for every unique word. Iyt worked but was horribly slow and the student made no use of the dictionaries that we had just spent a lecture learning about (this was in an awk class not Python...). > Especially with modern languagues like Python, where > you can write a whole program that actually does > something usefull using only a few lines of code it OTOH I do agree that the tasks could be at least a bit more interesting. Even if the technique to be used was prescribed or mandated. Alan G. From alan.gauld at freenet.co.uk Thu Feb 9 10:45:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:45:52 -0000 Subject: [Tutor] Splitting long string into same len parts References: <1139449587.21137.14.camel@elrond> Message-ID: <012301c62d5d$9ddf66b0$0b01a8c0@xp> Hi Victor, > I'd like to split a long string into equally long strings (len(str) = > 3). I did the following using regexes: > This is what I needed. Is there an easier or more straightforward way to > do this? Define easier :-) You could just use string slicing and a stepsize of 3 in range: lst = [] for index in range(0,len(mystring),3): lst.append(mystring[index : index+3]) Or tutrning that into a comprehension lst = [mystring[index : index+3] for index in range(0,len(mystring),3)] is that easier? I'm, not sure... and you still have problems where the string is not exactly divisible by 3, should you add padding? 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 Thu Feb 9 10:48:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 09:48:35 -0000 Subject: [Tutor] quirky multiple inheritance example!? References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp> <43EAAC3D.2060903@tds.net> Message-ID: <012901c62d5d$ff3d6560$0b01a8c0@xp> >> The problem is that super appears to only work with single inheritance. > That's ironic - super() is intended to ease some of the problems with > multiple inheritance especially diamond patterns. Some docs are here: > http://www.python.org/2.2.3/descrintro.html#cooperation > > The problem with the OP is that not all the classes involved use super(). I tried that. Before posting I went back and reread the super docs and tried building an MI lattice but, whatever I did, super only ever called the first listed superclass. If it had a super it called its superclass but the second superclasss never got initialised so far as I could tell! Alan G. From kent37 at tds.net Thu Feb 9 11:56:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Feb 2006 05:56:21 -0500 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: <1139449587.21137.14.camel@elrond> References: <1139449587.21137.14.camel@elrond> Message-ID: <43EB1FD5.6010005@tds.net> Victor Bouffier wrote: > Hi to all, > > I'd like to split a long string into equally long strings (len(str) = > 3). This is a very popular topic in the Python Cookbook. See for example http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095 and the links in the comments for the first recipe above. Kent From nickyncy at yahoo.com.hk Thu Feb 9 11:33:42 2006 From: nickyncy at yahoo.com.hk (Nicky Ng) Date: Thu, 9 Feb 2006 18:33:42 +0800 Subject: [Tutor] Breadth first search Message-ID: <01d201c62d64$4f919bc0$034b0893@nsct01> Hi, I would like to implement a breadth first serach with Python and read data from a text file with following file format File structure description First line contains number of node Second line contains node id(s) and distance between node id Last line is -1 Each node or distance is separated by space -1 For the example below, first line represent number of node is 10, second line contains first node id 0, second node id 1, distance between node id 0 and node id 1 is 2 0 is the root (starting node), the aim of the searching program is to find out the shortest path from 0 to a leaf node and print out the node path and value the path distance Could you give me any idea how to implement this search program with Python? Example: 10 0 1 2 0 5 3 1 2 2 1 3 4 2 1 3 2 3 1 5 6 3 5 7 1 6 8 1 7 8 1 7 9 2 9 5 3 -1 Outcome: Possible solution: Path=0,1,2,3 length=5 Path=0,5,6,8 length=5 Path=0,5,7,8 length=5 Thank you for your help. Nicky. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060209/4ec0041d/attachment.html From kent37 at tds.net Thu Feb 9 12:01:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Feb 2006 06:01:54 -0500 Subject: [Tutor] quirky multiple inheritance example!? In-Reply-To: <012901c62d5d$ff3d6560$0b01a8c0@xp> References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp> <43EAAC3D.2060903@tds.net> <012901c62d5d$ff3d6560$0b01a8c0@xp> Message-ID: <43EB2122.4000305@tds.net> Alan Gauld wrote: >>> The problem is that super appears to only work with single inheritance. > > >> That's ironic - super() is intended to ease some of the problems with >> multiple inheritance especially diamond patterns. Some docs are here: >> http://www.python.org/2.2.3/descrintro.html#cooperation >> >> The problem with the OP is that not all the classes involved use super(). > > I tried that. Before posting I went back and reread the super docs and > tried building an MI lattice but, whatever I did, super only ever called > the > first listed superclass. If it had a super it called its superclass but the > second superclasss never got initialised so far as I could tell! Works for me. Each class must call super(...).__init__(). The first arg to super() must be the class in which the call appears. One mistake is to call super(self.__class__, self) - this is not correct. Here is an example: >>> class A(object): ... def __init__(self): ... print 'A.__init__()' ... super(A, self).__init__() ... >>> class B(object): ... def __init__(self): ... print 'B.__init__()' ... super(B, self).__init__() ... >>> class C(A, B): ... def __init__(self): ... print 'C.__init__()' ... super(C, self).__init__() ... >>> C() C.__init__() A.__init__() B.__init__() <__main__.C object at 0x00A32BB0> Kent From kent37 at tds.net Thu Feb 9 14:07:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Feb 2006 08:07:50 -0500 Subject: [Tutor] Breadth first search In-Reply-To: <01d201c62d64$4f919bc0$034b0893@nsct01> References: <01d201c62d64$4f919bc0$034b0893@nsct01> Message-ID: <43EB3EA6.10203@tds.net> Nicky Ng wrote: > Hi, > > I would like to implement a breadth first serach with Python and read > data from a text file with following file format > > Could you give me any idea how to implement this search program with Python? Hmm, sounds like homework to me. The first thing I would do is pick a representation for the graph. One way is to use a dictionary where the keys are the name of the start vertex and the values are lists of ending vertices. In your case you also need to find a way to store the weight of the edge. Next you need to read the data file and create the chosen graph representation for the data. Finally you can implement the breadth-first search. A classic breadth-first search uses a queue; you can use a list for this - list.append() adds a new element, list.pop() removes an element from teh other end. Wikipedia calls breadth-first search on a weighted graph a uniform-cost search and recommends using a priority queue instead of a FIFO. Python's heapq module can help here. Kent From rshepard at appl-ecosys.com Thu Feb 9 15:19:44 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Thu, 9 Feb 2006 06:19:44 -0800 (PST) Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: <00fb01c62d59$92539bd0$0b01a8c0@xp> References: <00fb01c62d59$92539bd0$0b01a8c0@xp> Message-ID: On Thu, 9 Feb 2006, Alan Gauld wrote: > I love the way you post problems and also post a possible > solution - usually the correct one! :-) Alan, Well, I try to be helpful. > Yes that's the problem. And so I fixed that last evening. As my software engineering colleague so tactfully and sensitively put it, it's very difficult for someone who's spent decades writing procedural code as a non-professional to stop thinking procedurally when working with an object-oriented language. From the time C++ first came out I understood all the concepts but I stayed with C because it met all my needs. As my friend wrote, there's as much to unlearn as there is to learn to make the transition. Anyway, I got the UI for the model framework done, and he's finished with the core C shared libraries, so now he'll take over writing the middle-ware while I focus on those things I do best. That's why there's more than just me in this effort. :-) Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From alan.gauld at freenet.co.uk Thu Feb 9 16:06:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Feb 2006 15:06:02 -0000 Subject: [Tutor] Time to Use a Global Variable? References: <00fb01c62d59$92539bd0$0b01a8c0@xp> Message-ID: <016101c62d8a$57faf880$0b01a8c0@xp> > As my software engineering colleague so tactfully and sensitively put > it, > it's very difficult for someone who's spent decades writing procedural > code > as a non-professional to stop thinking procedurally when working with an > object-oriented language. Actually its just as hard for professional software engineers. There were some studies done when OO started to become really popular in the early 90's. They reckoned you could teach OOP to a new programmer in 3-6 months but for a long term procedural programmer they would learn the syntax in a week but it would take 6 months to 2 years to learn to really think in OO terms. > wrote, there's as much to unlearn as there is to learn to make the > transition. Absolutely. It is a new way of approaching problems. Its very hard to change your whole approach to problem analysis - especially if you have a strong math background because math fits the procedural/functional style much better than it does OO. Those who come from a life sciences background or a traditional engineering background can usually transition much more easily because they are used to thinking in terms of systems of linked objects and their interactions. Alan G. From rshepard at appl-ecosys.com Thu Feb 9 16:21:08 2006 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Thu, 9 Feb 2006 07:21:08 -0800 (PST) Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: <016101c62d8a$57faf880$0b01a8c0@xp> References: <00fb01c62d59$92539bd0$0b01a8c0@xp> <016101c62d8a$57faf880$0b01a8c0@xp> Message-ID: On Thu, 9 Feb 2006, Alan Gauld wrote: > Those who come from a life sciences background or a traditional engineering > background can usually transition much more easily because they are used to > thinking in terms of systems of linked objects and their interactions. Alan, I suppose, then, that I'm the exception that proves the rule. My strength as a systems ecologist is synthesis; seeing how it all fits together and works given all the pieces. But, I also have a very strong quantitative ability and have applied statistics (including spatial) and modeling (including fuzzy sets and fuzzy logic) to natural resource concerns. It's still the correct expression of the linked objects and their interactions where I'm stalled. Of course, I recognize where and why I have problems, but those are very difficult to effectively resolve via long-distance e-mail. Unfortunately, there's a lack of enthusiasm among the local python experts to sitting down and providing a tutorial on specific, real-life code. That works much better for me in learning a new language. Although, I have picked up LaTeX quite well from books and the mail lists. Thanks, Rich -- Richard B. Shepard, Ph.D. | Author of "Quantifying Environmental Applied Ecosystem Services, Inc. (TM) | Impact Assessments Using Fuzzy Logic" Voice: 503-667-4517 Fax: 503-667-8863 From dyoo at hkn.eecs.berkeley.edu Thu Feb 9 20:52:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Feb 2006 11:52:31 -0800 (PST) Subject: [Tutor] Breadth first search In-Reply-To: <01d201c62d64$4f919bc0$034b0893@nsct01> Message-ID: On Thu, 9 Feb 2006, Nicky Ng wrote: > I would like to implement a breadth first serach with Python and read > data from a text file with following file format [cut] Hi Nicky, We've seen the problems from Programming Challenges: http://www.programming-challenges.com/pg.php?page=index and I recognize this as one of their class of problems. This is a homework assignment, and as such, we are restricted in what we can say. But can you be more specific about why you're having trouble with this? As it is, you haven't mentioned anything except the homework problem statement, so we have no idea why you're having trouble with it. What exactly have you done or tried so far? Have you written programs that do things similar to what is being asked here? We're not going to give you an "answer", but depending on what more you can tell us, we will do what we can to point you in some direction that should help. But the work has to be your own. You may find a tutorial like: http://www.ibiblio.org/obp/thinkCSpy/ useful. From klappnase at freenet.de Thu Feb 9 22:22:00 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 9 Feb 2006 22:22:00 +0100 Subject: [Tutor] Changing instance attributes in different threads In-Reply-To: <43EA7B46.6010104@tds.net> References: <61d0e2b40602061241y270a58efu24fe0368acaf7619@mail.gmail.com> <43E7CA17.1030808@tds.net> <61d0e2b40602061429n3ea0dfc0w636961acc50e46f5@mail.gmail.com> <43E7DCFA.6070905@tds.net> <20060207111725.51f07b9c.klappnase@freenet.de> <43E87E55.5090401@tds.net> <20060207233106.6f4bd867.klappnase@freenet.de> <20060208121733.22395416.klappnase@freenet.de> <43E9F40E.60609@tds.net> <20060208191125.5cd23f5c.klappnase@freenet.de> <43EA3CCB.9040304@tds.net> <20060208223355.24c25496.klappnase@freenet.de> <43EA7B46.6010104@tds.net> Message-ID: <20060209222200.3ad617fd.klappnase@freenet.de> On Wed, 08 Feb 2006 18:14:14 -0500 Kent Johnson wrote: > > Sorry, I missed to insert the time.sleep(0.1) I used in my original while loop into the example above. > > The reason for using time.sleep() is that I need to avoid lots of loops over an empty buffer. > > The amount of time until the producer thread reads a new data fragment into the buffer may > > be significant, depending on the fragment size requested by the driver (e.g my fm801 card > > wants fragments of 16384 bytes which is about 0.09 audio seconds). On the other hand the > > buffer may contain hundreds of kB of data if other processes cause a lot of disk I/O. > > Using Queue.get() will do this for you automatically. If there is no > data it will block until something is added to the queue and you avoid a > polling loop. If there is data it will return it quickly. > > > > Not if I call it with block=0; if I understand the docs correctly the queue will raise a Queue.Empty exception > > if the queue is currently locked by another thread. > > No, the block flag controls whether the call will wait until something > is in the queue or return immediately. The call to Queue.get() will > always block waiting for the lock that controls access to the Queue; it > can't even tell if the Queue is empty until it gets this lock. > Ah , then I misunderstood what the docs meant with "return an item if one is immediately available, else raise the Empty exception". I thought "immediately available" means the Queue is currently not locked by another thread. Thanks again Michael From dyoo at hkn.eecs.berkeley.edu Fri Feb 10 01:30:47 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Feb 2006 16:30:47 -0800 (PST) Subject: [Tutor] Breadth first search (fwd) Message-ID: [Forwarding the question on breadth first search to tutor] ---------- Forwarded message ---------- Date: Fri, 10 Feb 2006 07:25:05 +0800 From: Nicky Ng To: Danny Yoo Subject: Re: [Tutor] Breadth first search Dear Danny, I did not read the book u mentinoed and just feel interesting because my friend asked me about this problem. I am new in Python so not sure how to do with Python to solve this problem. I did part of my program but not work properly. From dyoo at hkn.eecs.berkeley.edu Fri Feb 10 02:03:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Feb 2006 17:03:44 -0800 (PST) Subject: [Tutor] Breadth first search (fwd) In-Reply-To: Message-ID: > I am new in Python so not sure how to do with Python to solve this > problem. Hi Nicky, Would you know how to do this problem in a different programming language? I'm not getting any sense at all at what experience or level you have. The question is just hard enough that asking it to a total beginner would be very mean indeed. But it's also easy enough that if you have previous experience with programming, then the problem really shouldn't have much to do with Python at all, but with the overall algorithm to solve the problem. > I did part of my program but not work properly. What do you mean by "not work properly?" It would be unreasonable for a driver to get a flat tire, call up their mechanic, say "The car's broken!", and leave it at that. The same thing goes with computer programs. The question you are asking has mulitple pieces: it would be very useful to know what pieces are working and what parts aren't. Tell us more. You have to keep in mind that none of us here are psychic. If you don't tell us anything, what kind of help can we give you? From nephish at xit.net Fri Feb 10 03:18:20 2006 From: nephish at xit.net (nephish) Date: Fri, 10 Feb 2006 02:18:20 +0000 Subject: [Tutor] nutshell review Message-ID: <1139537900.20224.2.camel@bitsbam> lo there, i know this comes up from time to time. i am considering buying 'python in a nutshell'. All the reviews i have read for it are very good. But it only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at home. As good a reference as it is, is it too dated to be that good still ? i have 'Learning Python' and 'Programming Python'. Learning is awesome for me, Programming is a bit over my head. any suggestions? From andre.roberge at gmail.com Fri Feb 10 03:22:15 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 9 Feb 2006 22:22:15 -0400 Subject: [Tutor] nutshell review In-Reply-To: <1139537900.20224.2.camel@bitsbam> References: <1139537900.20224.2.camel@bitsbam> Message-ID: <7528bcdd0602091822l2a2d0500y296da6deb7be0a8d@mail.gmail.com> On 2/9/06, nephish wrote: > lo there, > i know this comes up from time to time. i am considering buying 'python > in a nutshell'. All the reviews i have read for it are very good. But it > only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at > home. As good a reference as it is, is it too dated to be that good > still ? i have 'Learning Python' and 'Programming Python'. Learning is > awesome for me, Programming is a bit over my head. > any suggestions? > I own about 10 Python books including Learning Python, Programming Python and Python in a Nutshell. Of these three, Python in a Nutshell is the one I find the most useful. The Python Cookbook (2nd ed) is my other favourite. Your mileage may vary... Andr? From nephish at xit.net Fri Feb 10 03:24:46 2006 From: nephish at xit.net (nephish) Date: Thu, 09 Feb 2006 20:24:46 -0600 Subject: [Tutor] nutshell review In-Reply-To: <7528bcdd0602091822l2a2d0500y296da6deb7be0a8d@mail.gmail.com> References: <1139537900.20224.2.camel@bitsbam> <7528bcdd0602091822l2a2d0500y296da6deb7be0a8d@mail.gmail.com> Message-ID: <1139538286.20622.6.camel@bitsbam> thanks man, ill check out cookbook & see what its all about, too. sk On Thu, 2006-02-09 at 22:22 -0400, Andre Roberge wrote: > On 2/9/06, nephish wrote: > > lo there, > > i know this comes up from time to time. i am considering buying 'python > > in a nutshell'. All the reviews i have read for it are very good. But it > > only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at > > home. As good a reference as it is, is it too dated to be that good > > still ? i have 'Learning Python' and 'Programming Python'. Learning is > > awesome for me, Programming is a bit over my head. > > any suggestions? > > > I own about 10 Python books including Learning Python, Programming > Python and Python in a Nutshell. Of these three, Python in a Nutshell > is the one I find the most useful. The Python Cookbook (2nd ed) is my > other favourite. Your mileage may vary... > > Andr? From carroll at tjc.com Fri Feb 10 04:02:55 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 9 Feb 2006 19:02:55 -0800 (PST) Subject: [Tutor] nutshell review In-Reply-To: <1139537900.20224.2.camel@bitsbam> Message-ID: On Fri, 10 Feb 2006, nephish wrote: > i know this comes up from time to time. i am considering buying 'python > in a nutshell'. All the reviews i have read for it are very good. But it > only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at > home. As good a reference as it is, is it too dated to be that good > still ? No, it's not too dated. I still use it constantly as my main reference. When I know a facility is post-2.2, I use the online docs instead. But my preference is definitely for the Nutshell. Alex explains things extraordinarily well, in my opinion. The book is well-organized and well-indexed, so you can find things pretty easily. Two thumbs up, from here. > i have 'Learning Python' and 'Programming Python'. Learning is > awesome for me, Programming is a bit over my head. That tracks my feelings. I don't find "Programming Python" to be very useful. It's not the sort of reference book that, say, "Programming Perl" occupies on the Perl world. My own take on PP is that you can't open it up to a discussion of a particular feature and understand that feature without understanding a lot of other things having nothing to do with the feature, but that are implicit in the explanations and examples. (But I hasten to add, I've seen enough people swear how much they love that book, that this may just be idiosyncratic to me.) I think a good Python *reference* book is invaluable to any Python programmer. And to me, that book is Python in a Nutshell. There are a couple others that are good, too: The Python 2.1 Bible - 2.1, obviously; I don't know if there's a later version; The Complete Python Reference - published 2001, so bound to be a bit dated) Python Essential Reference - When I first started playing with Python, a library copy of this was my reference. I liked it, but I like the Nutshell just a little better, but that may be a matter of familiarity. If you're going for this one, I'd suggest waiting another couple of weeks. The Third Edition is coming out February 24, which means it will be the most current Python reference book, when published. I would be surprised if it didn't cover through 2.4. From carroll at tjc.com Fri Feb 10 04:07:37 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 9 Feb 2006 19:07:37 -0800 (PST) Subject: [Tutor] nutshell review In-Reply-To: <7528bcdd0602091822l2a2d0500y296da6deb7be0a8d@mail.gmail.com> Message-ID: On Thu, 9 Feb 2006, Andre Roberge wrote: > I own about 10 Python books including Learning Python, Programming > Python and Python in a Nutshell. Of these three, Python in a Nutshell > is the one I find the most useful. The Python Cookbook (2nd ed) is my > other favourite. Your mileage may vary... I love the Cookbook, but it's not a reference and it does not do a very good job if you try to force it into that role. As I read through it, I see recipes that use some feature -- usually a library call -- I don't know, and I can't find out what the thing does from the context. I have to go look it up in another book, like the Nutshell. That's not a bad thing. If the Cookbook explained every little part of every recipe, it would be way too long, and the editors would have had to cut out half the recipes to make it a reaonsble size. My only point is that, great as it is, it's not a reference book, and shouldn't be expected to be one. Man, I probably have about 10 Python books, too (including both editions of the Cookbook), and I only program for fun. From nephish at xit.net Fri Feb 10 04:29:26 2006 From: nephish at xit.net (nephish) Date: Thu, 09 Feb 2006 21:29:26 -0600 Subject: [Tutor] nutshell review In-Reply-To: References: Message-ID: <1139542166.27274.0.camel@bitsbam> Sounds like its worth the wait. thanks all. shawn On Thu, 2006-02-09 at 19:02 -0800, Terry Carroll wrote: > On Fri, 10 Feb 2006, nephish wrote: > > > i know this comes up from time to time. i am considering buying 'python > > in a nutshell'. All the reviews i have read for it are very good. But it > > only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at > > home. As good a reference as it is, is it too dated to be that good > > still ? > > No, it's not too dated. I still use it constantly as my main reference. > When I know a facility is post-2.2, I use the online docs instead. But my > preference is definitely for the Nutshell. Alex explains things > extraordinarily well, in my opinion. The book is well-organized > and well-indexed, so you can find things pretty easily. > > Two thumbs up, from here. > > > i have 'Learning Python' and 'Programming Python'. Learning is > > awesome for me, Programming is a bit over my head. > > That tracks my feelings. I don't find "Programming Python" to be very > useful. It's not the sort of reference book that, say, "Programming Perl" > occupies on the Perl world. My own take on PP is that you can't open it > up to a discussion of a particular feature and understand that feature > without understanding a lot of other things having nothing to do with the > feature, but that are implicit in the explanations and examples. (But I > hasten to add, I've seen enough people swear how much they love that book, > that this may just be idiosyncratic to me.) > > I think a good Python *reference* book is invaluable to any Python > programmer. And to me, that book is Python in a Nutshell. > > There are a couple others that are good, too: > > The Python 2.1 Bible - 2.1, obviously; I don't know if there's a later > version; > > > The Complete Python Reference - published 2001, so bound to be a bit > dated) > > Python Essential Reference - When I first started playing with Python, a > library copy of this was my reference. I liked it, but I like the > Nutshell just a little better, but that may be a matter of familiarity. > If you're going for this one, I'd suggest waiting another couple of weeks. > The Third Edition is coming out February 24, which means it will be the > most current Python reference book, when published. I would be surprised > if it didn't cover through 2.4. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hugonz-lists at h-lab.net Fri Feb 10 05:20:45 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 09 Feb 2006 22:20:45 -0600 Subject: [Tutor] Time to Use a Global Variable? In-Reply-To: References: Message-ID: <43EC149D.3060408@h-lab.net> Hi Rich I guess passing a reference to the database handler instance that contains closeDB to your app's __init__ is less dirty that having a global variable, what do you think? Hugo > > When I test the application and try to close it, python complains > File "eikos.py", line 315, in OnFileQuit > closeDb() > NameError: global name 'closeDb' is not defined > > I've tried changing OnFileQuit to call DBinterface.closeDB(), but that > doesn't work. Obviously I still haven't completely grokked how to refer in > one class to a method defined in another class. Of course, I've not > explicitly created an instance of DBinterface within MyFrame, so that may be > the problem. > > A clue stick is welcome. > > Rich > From hugonz-lists at h-lab.net Fri Feb 10 06:24:07 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 09 Feb 2006 23:24:07 -0600 Subject: [Tutor] Tkinter, widgets not displaying... Message-ID: <43EC2377.1030704@h-lab.net> Hi All, I wrote a small turn delivering graphical app that is supposed to display turns in a queue. If I instantiate the class and call its methods, thus displaying strings in several canvases, from the interactive prompt, everything works fine. If I do it when running the script as a programs, nothing gets displayed. If I call mainloop() at the end of my program, everything gets displayed, but then I cannot use my own function classes. This program will never respond to events, but just get called from a "queue manager" script for display... Here's the code: #!/usr/bin/env python from __future__ import division import Tkinter import tkFont from Tkconstants import * from time import sleep class TurnQueue(Tkinter.Frame): def __init__(self, master=None, pw=60, ph=60, panels=4): self.ph = ph self.pw = pw self.panels = panels Tkinter.Frame.__init__(self, master) self.createWidgets() self.pack() def createWidgets(self): """Create four canvases and a warning window.""" self.canvases = [Tkinter.Canvas(height=self.ph, width=self.pw, borderwidth=1, background = '#FFFFFF') for i in range(self.panels)] self.textbox_ids = [] # display them all, initialized for i in self.canvases: id = i.create_text(self.pw//2, self.ph//2, text='', font=('bitstream charter', self.ph, 'bold'), fill='red') self.textbox_ids.append(id) i.pack() def write_panel(self, panel_no, newtext): """writepanel(self, panel, newtext) Set panel to text """ self.canvases[panel_no].itemconfigure(self.textbox_ids[panel_no], text=newtext) def read_panel(self, panel_no): """textcontents <- read_panel(self, panel_no) Read panel text contents""" return(self.canvases[panel_no].itemcget(self.textbox_ids[panel_no], 'text')) def insert(self, turn_string): """Insert a new turn into the queue, move the rest upwards, delete oldest.""" current_values = [self.read_panel(i) for i in range(len(self.canvases))] next_values = current_values[:] next_values[:-1] = current_values[1:] next_values[-1] = turn_string # update all panel values for i in range(len(self.canvases)): self.write_panel(i, next_values[i]) if __name__ == "__main__": myturns = TurnQueue(pw=200, ph=100, panels=4) for i in range(100): myturns.insert(str(i)) sleep(0.2) From hugonz-lists at h-lab.net Fri Feb 10 06:57:22 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 09 Feb 2006 23:57:22 -0600 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <7528bcdd0602061059t112f4e46l901e16c14c350a6f@mail.gmail.com> References: <200602060946.42913.pkraus@pelsupply.com> <20060206171618.GD1767@johnsons-web.com> <7528bcdd0602061059t112f4e46l901e16c14c350a6f@mail.gmail.com> Message-ID: <43EC2B42.7070602@h-lab.net> > I'm programming under Windows and I haven't found anything better than > Stani's Python Editor (spe). It should be cross-platform. > I second SPE under Windows, though under linux I keep using vim. The included utilities are great (I love Kiki) The only caveat would be that running wxpython programs could get you into trouble, as SPE itself is written in wxPython. Hugo From hugonz-lists at h-lab.net Fri Feb 10 07:25:57 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 10 Feb 2006 00:25:57 -0600 Subject: [Tutor] Tkinter, widgets not displaying... In-Reply-To: <43EC2377.1030704@h-lab.net> References: <43EC2377.1030704@h-lab.net> Message-ID: <43EC31F5.2060509@h-lab.net> Sorry for replying to myself, but I found a page that says that it can be done without threads... so it hit me: use threads!!! (duh) Ok, for future reference, this is the part where I use the classes I defined: if __name__ == "__main__": top = Tkinter.Tk() myturns = TurnQueue(top, pw=200, ph=100, panels=4) #importing here is ugly, but just for testing. from thread import start_new_thread start_new_thread(Tkinter.Tk.mainloop, (top,)) for i in range(10): myturns.insert(str(i)) sleep(0.2) So now I see my line of canvases displaying numbers going upwards.. Hugo From john at fouhy.net Fri Feb 10 08:32:53 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 10 Feb 2006 20:32:53 +1300 Subject: [Tutor] Tkinter, widgets not displaying... In-Reply-To: <43EC31F5.2060509@h-lab.net> References: <43EC2377.1030704@h-lab.net> <43EC31F5.2060509@h-lab.net> Message-ID: <5e58f2e40602092332k34c19f46w@mail.gmail.com> On 10/02/06, Hugo Gonz?lez Monteverde wrote: > Sorry for replying to myself, but I found a page that says that it can > be done without threads... so it hit me: use threads!!! (duh) Yes, this will be what you need. Your GUI won't do anything until you run mainloop, and mainloop won't exit until you close your GUI. So if you want to programmatically feed data in, you need to do it from a different thread. One caveat, though --- > if __name__ == "__main__": > start_new_thread(Tkinter.Tk.mainloop, (top,)) > for i in range(10): > myturns.insert(str(i)) > sleep(0.2) By doing this, you are changing the GUI from a different thread from the one running mainloop. This is a BAD IDEA. It can easily lead to weird bugs that you will struggle to understand. If you want to do multithreaded programming with a GUI, one good way is to use .after_idle. ie, instead of myturns.insert(str(i)), do top.after_idle(myturns.insert, str(i)) (I think this is the right syntax). This will cause the mainloop thread to run the code instead. HTH! -- John. From alan.gauld at freenet.co.uk Fri Feb 10 09:52:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Feb 2006 08:52:23 -0000 Subject: [Tutor] quirky multiple inheritance example!? References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp><43EAAC3D.2060903@tds.net> <012901c62d5d$ff3d6560$0b01a8c0@xp> <43EB2122.4000305@tds.net> Message-ID: <01a601c62e1f$4f9f4660$0b01a8c0@xp> > Works for me. Each class must call super(...).__init__(). The first arg > >>> class A(object): > ... def __init__(self): > ... print 'A.__init__()' > ... super(A, self).__init__() > ... > >>> class B(object): > ... def __init__(self): > ... print 'B.__init__()' > ... super(B, self).__init__() > ... > >>> class C(A, B): > ... def __init__(self): > ... print 'C.__init__()' > ... super(C, self).__init__() > ... > >>> C() > C.__init__() > A.__init__() > B.__init__() > <__main__.C object at 0x00A32BB0> Thats almost exactly what I did but with several extra MI classes to test things like diamond lattice etc. BUT I say almost because the one thing I didn't do is call super() at the highest level. 'A' and 'B' in your case. DUH! Its obvious when I look at it now but in my mind I was thinking they didn't have a superclass, but of course they do - object! Having said that I still don't like that mechanism since it makes the behaviour of the subclass depend on the implementation of the superclass. That is, if I choose to create a sub class of someone elses class then a call to super will only work if the other person has written their class with a call to super... not good. Whereas if I call the class init explicitly it works regardless of how the superclass is written. Thanks for a 'super' explanation Kent :-) Alan G From alan.gauld at freenet.co.uk Fri Feb 10 10:03:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Feb 2006 09:03:42 -0000 Subject: [Tutor] nutshell review References: Message-ID: <01d801c62e20$e3fede00$0b01a8c0@xp> > That tracks my feelings. I don't find "Programming Python" to be very > useful. It's not the sort of reference book that, say, "Programming Perl" > .... > hasten to add, I've seen enough people swear how much they love that book, > that this may just be idiosyncratic to me.) One thing to note about PP is that it is really two very different books. It was originally the second book ever published on Python and as such tried to be both tutorial and reference and cookbook. Naturally it failed (although not too badly or Python would probably not have taken off!) on asll counts. By the time the current (2nd edition) came out there were lots of Python tutorials so this version aims at being an advanced topic guide. It looks at lots of areas that were not very well covbered in other tutorials. It is not a tutorial and not really a reference guide either, its probably closest to the cookbook in spirit but less specific. There is a 3rd edition coming out that is allegedly going to target even more advanced topics and I have my name down with Amazon for that one... :-) > I think a good Python *reference* book is invaluable to any Python > programmer. And to me, that book is Python in a Nutshell. Me too. > Python Essential Reference - When I first started playing with Python, > ... > The Third Edition is coming out February 24, which means it will be the > most current Python reference book, when published. I would be surprised > if it didn't cover through 2.4. According to Amazon it does... But despite opwning both of the prevbious editions I don't think I'll be buying this one. The Nutshell is still current enough for me - all the really big changes in Puython happened in 2.2! Alan G. From danielle at davout.org Fri Feb 10 11:30:53 2006 From: danielle at davout.org (danielle at davout.org) Date: Fri, 10 Feb 2006 11:30:53 +0100 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <43EC2B42.7070602@h-lab.net> References: <200602060946.42913.pkraus@pelsupply.com> <20060206171618.GD1767@johnsons-web.com> <7528bcdd0602061059t112f4e46l901e16c14c350a6f@mail.gmail.com> <43EC2B42.7070602@h-lab.net> Message-ID: <43EC6B5D.2020604@davout.org> What about It's an Editor based on wxPython. NewEdit uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So NewEdit is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call "Slot Class". This technique will make the changes centralized and easily managed. What are its features? ================ * Cross platform o based on wxPython, so it can run anywhere that wxPython works, such as: Windows, Linux. o Unicode support.......: http://wiki.woodpecker.org.cn/moin/NewEdit?action=AttachFile&do=get&target=newedit_3.2.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/NewEdit?action=AttachFile&do=get&target=NewEdit3.2.exe wiki: http://wiki.woodpecker.org.cn/moin/NewEdit svn: http://cvs.woodpecker.org.cn/svn/woodpecker/newedit maillist: http://groups.google.com/group/NewEdit Hugo Gonz?lez Monteverde a ?crit : >> I'm programming under Windows and I haven't found anything better than >> Stani's Python Editor (spe). It should be cross-platform. >> >> > > I second SPE under Windows, though under linux I keep using vim. The > included utilities are great (I love Kiki) > > The only caveat would be that running wxpython programs could get you > into trouble, as SPE itself is written in wxPython. > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From thomas.coopman at gmail.com Fri Feb 10 11:11:05 2006 From: thomas.coopman at gmail.com (thomas) Date: Fri, 10 Feb 2006 11:11:05 +0100 Subject: [Tutor] pyGtk using combobox Message-ID: <20060210111105.74388200@localhost> Hi, I would like to make a combobox with a list of strings, but I have many problems with it. I know how to make the combobox and how to add strings, but is it possible to get a list of strings from the combobox and also is it possible to update the combobox with a list of strings? (something like combo.set_popdown_strings(list)) From kent37 at tds.net Fri Feb 10 11:53:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Feb 2006 05:53:22 -0500 Subject: [Tutor] quirky multiple inheritance example!? In-Reply-To: <01a601c62e1f$4f9f4660$0b01a8c0@xp> References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp><43EAAC3D.2060903@tds.net> <012901c62d5d$ff3d6560$0b01a8c0@xp> <43EB2122.4000305@tds.net> <01a601c62e1f$4f9f4660$0b01a8c0@xp> Message-ID: <43EC70A2.30106@tds.net> Alan Gauld wrote: > Having said that I still don't like that mechanism since it makes the > behaviour of the subclass depend on the implementation of the > superclass. That is, if I choose to create a sub class of someone elses > class then a call to super will only work if the other person has > written their class with a call to super... not good. Whereas if I call > the class init explicitly it works regardless of how the superclass is > written. It's worse than that - with MI if you call __init__() explicitly and the base classes call super().__init__(), one of the base class __init__() methods will be called twice. See http://fuhm.net/super-harmful/ for an example. super() only works correctly when all the classes involved use it. My conclusion is that it is best reserved for the times it is actually needed (with diamond MI), and direct calling of the base class method should be used everywhere else. Kent From alan.gauld at freenet.co.uk Fri Feb 10 12:29:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Feb 2006 11:29:31 -0000 Subject: [Tutor] quirky multiple inheritance example!? References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp><43EAAC3D.2060903@tds.net><012901c62d5d$ff3d6560$0b01a8c0@xp> <43EB2122.4000305@tds.net><01a601c62e1f$4f9f4660$0b01a8c0@xp> <43EC70A2.30106@tds.net> Message-ID: <01eb01c62e35$43457e50$0b01a8c0@xp> > It's worse than that - with MI if you call __init__() explicitly and the > base classes call super().__init__(), one of the base class __init__() > methods will be called twice. See http://fuhm.net/super-harmful/ for an > example. > Excellent link Kent. This just highlights how woefully inadequate the official documentation for super() is! It has also confirmed my belief that I'm better off sticking to explicit calls and worrying about diamond lattice situations only when I need to (which is very rarely indeed!). Its also confirmed that I did the right thing by ignoring super in my tutor! Alan G From kent37 at tds.net Fri Feb 10 14:01:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Feb 2006 08:01:51 -0500 Subject: [Tutor] quirky multiple inheritance example!? In-Reply-To: <01eb01c62e35$43457e50$0b01a8c0@xp> References: <5e183f3d0602081407q274684hc55373a94205aee4@mail.gmail.com><00e601c62d0b$b6dee930$0b01a8c0@xp><43EAAC3D.2060903@tds.net><012901c62d5d$ff3d6560$0b01a8c0@xp> <43EB2122.4000305@tds.net><01a601c62e1f$4f9f4660$0b01a8c0@xp> <43EC70A2.30106@tds.net> <01eb01c62e35$43457e50$0b01a8c0@xp> Message-ID: <43EC8EBF.2050300@tds.net> Alan Gauld wrote: >> It's worse than that - with MI if you call __init__() explicitly and >> the base classes call super().__init__(), one of the base class >> __init__() methods will be called twice. See >> http://fuhm.net/super-harmful/ for an example. >> > > Excellent link Kent. This just highlights how woefully inadequate the > official documentation for super() is! It has also confirmed my belief > that I'm better off sticking to explicit calls and worrying about diamond > lattice situations only when I need to (which is very rarely indeed!). That is my conclusion too. But to balance it out, here is a page that recommends using super() everywhere (in the Chandler project): http://wiki.osafoundation.org/bin/view/Projects/UsingSuper and here is the heated discussion on python-dev sparked by the "Super Considered Harmful" essay: http://mail.python.org/pipermail/python-dev/2005-January/050656.html Kent From kent37 at tds.net Fri Feb 10 14:30:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Feb 2006 08:30:16 -0500 Subject: [Tutor] Tkinter, widgets not displaying... In-Reply-To: <43EC2377.1030704@h-lab.net> References: <43EC2377.1030704@h-lab.net> Message-ID: <43EC9568.9070602@tds.net> Hugo Gonz?lez Monteverde wrote: > Hi All, > > I wrote a small turn delivering graphical app that is supposed to > display turns in a queue. > def insert(self, turn_string): > """Insert a new turn into the queue, move the rest upwards, > delete oldest.""" This is overly complicated: > current_values = [self.read_panel(i) for i in > range(len(self.canvases))] You are going to throw away the first value, there is no need to read it. > next_values = current_values[:] There is no need to copy current_values since it is a brand new list already. > next_values[:-1] = current_values[1:] > next_values[-1] = turn_string This works but you could just copy the part of current_values you want and append turn_string. Taking all this together, you can write just next_values = [self.read_panel(i) for i in range(1, len(self.canvases))] next_values.append(turn_string) But there is a deeper issue here. You seem to be writing some kind of simulation. You might want to consider separating your model - the data and mechanics of the simulation - from the GUI - the visual representation. The way you have it now, the data is stored in the GUI itself. This leads to tight coupling between the model and the GUI. It will be hard to test the model or to put a different front-end on it, and hard to have a clean conceptual model of the simulation. For example, you could have this model class: class QueueModel(object): def __init__(self, length=4): self.data = [None * length ] def insert(self, item): self.data.pop() # remove the first item self.data.append(item) Then in your GUI, your insert() method would become update(self, model). Or maybe instantiate the GUI giving it an instance of the model. Your main program would drive them both. Oversimplifying by leaving out the threading, it would look like model = QueueModel(length=4) gui = TurnQueue(model, pw=200, ph=100) for i in range(100): model.insert(str(i)) gui.update() sleep(0.2) As the model develops, this separation from the GUI will make it much easier to work with. Kent From kent37 at tds.net Fri Feb 10 14:32:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Feb 2006 08:32:18 -0500 Subject: [Tutor] Tkinter, widgets not displaying... In-Reply-To: <5e58f2e40602092332k34c19f46w@mail.gmail.com> References: <43EC2377.1030704@h-lab.net> <43EC31F5.2060509@h-lab.net> <5e58f2e40602092332k34c19f46w@mail.gmail.com> Message-ID: <43EC95E2.1060808@tds.net> John Fouhy wrote: > If you want to do multithreaded programming with a GUI, one good way > is to use .after_idle. > > ie, instead of myturns.insert(str(i)), do > top.after_idle(myturns.insert, str(i)) (I think this is the right > syntax). This will cause the mainloop thread to run the code instead. Another way to do this without a separate thread is to use top.after() to schedule the inserts. Schedule the first one before calling mainloop(), and have each insert schedule the next one. Kent From carl.badgley at gmail.com Fri Feb 10 16:56:53 2006 From: carl.badgley at gmail.com (carl.badgley at gmail.com) Date: Fri, 10 Feb 2006 09:56:53 -0600 Subject: [Tutor] nutshell review In-Reply-To: <01d801c62e20$e3fede00$0b01a8c0@xp> References: <01d801c62e20$e3fede00$0b01a8c0@xp> Message-ID: <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> Isn't there supposed to be a new edition of the Nutshell book coming out? I was kinda hanging back for that one... Carl Badgley -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/5ff60183/attachment.htm From nephish at xit.net Fri Feb 10 17:08:55 2006 From: nephish at xit.net (nephish) Date: Fri, 10 Feb 2006 10:08:55 -0600 Subject: [Tutor] nutshell review In-Reply-To: <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> References: <01d801c62e20$e3fede00$0b01a8c0@xp> <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> Message-ID: <1139587735.25713.1.camel@localhost.localdomain> yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get the cookbook now, and then pick up the new nutshell later. sk On Fri, 2006-02-10 at 09:56 -0600, carl.badgley at gmail.com wrote: > Isn't there supposed to be a new edition of the Nutshell book coming > out? I was kinda hanging back for that one... > Carl Badgley > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From carl.badgley at gmail.com Fri Feb 10 17:18:12 2006 From: carl.badgley at gmail.com (carl.badgley at gmail.com) Date: Fri, 10 Feb 2006 10:18:12 -0600 Subject: [Tutor] nutshell review In-Reply-To: <1139587735.25713.1.camel@localhost.localdomain> References: <01d801c62e20$e3fede00$0b01a8c0@xp> <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> <1139587735.25713.1.camel@localhost.localdomain> Message-ID: <1cbf5cf90602100818v726042fbjcd9074fd96fe7f2a@mail.gmail.com> See I couldn't tell if he was talking about the Nutshell book or the Python Essential Reference book...thanks Carl On 2/10/06, nephish wrote: > > yeah, one of the guys that posted earlier mentioned late feb as a > release of the new one. i think i am going to go ahead and get the > cookbook now, and then pick up the new nutshell later. > sk > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/db0b18d0/attachment.htm From kent37 at tds.net Fri Feb 10 17:23:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Feb 2006 11:23:39 -0500 Subject: [Tutor] nutshell review In-Reply-To: <1139587735.25713.1.camel@localhost.localdomain> References: <01d801c62e20$e3fede00$0b01a8c0@xp> <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> <1139587735.25713.1.camel@localhost.localdomain> Message-ID: <43ECBE0B.2050706@tds.net> nephish wrote: > yeah, one of the guys that posted earlier mentioned late feb as a > release of the new one. i think i am going to go ahead and get the > cookbook now, and then pick up the new nutshell later. It's the third edition of Python Essential Reference that is due Feb 24. Judging from his posts to comp.lang.python, Alex Martelli is working on a second edition of the Nutshell - or at least feeling guilty about *not* working on it - but I haven't seen any dates. Kent From hugonz-lists at h-lab.net Fri Feb 10 17:26:29 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 10 Feb 2006 10:26:29 -0600 Subject: [Tutor] Tkinter, widgets not displaying... In-Reply-To: <43EC9568.9070602@tds.net> References: <43EC2377.1030704@h-lab.net> <43EC9568.9070602@tds.net> Message-ID: <43ECBEB5.4080802@h-lab.net> Hi Kent and John, Thanks a lot for the advice on how to improve my program. I will look into separating the data and model as John suggests here. I didn't know about after_idle() and after(); seems that dir()'ing the classes sometimes gives out a lot more information than you can chew at any given time :) Thanks, Hugo From mlennert at club.worldonline.be Fri Feb 10 17:03:18 2006 From: mlennert at club.worldonline.be (Moritz Lennert) Date: Fri, 10 Feb 2006 17:03:18 +0100 Subject: [Tutor] cgi script: how to continue a process in the background and return from cgi script Message-ID: <43ECB946.50502@club.worldonline.be> Hello, I need some pointers in the right direction for the following problem: I have a cgi script which reads in some form elements, uses them to compose an SQL query, sends that query to the postgresql backend, writes the results into a temporary file and sends a mail to the user with the link to the file. The main block of the program is very simple formulaire = cgi.FieldStorage(keep_blank_values=1) adresse=formulaire["email1"].value if adresse == "": print_error_adresse() else: requete=compose_req(formulaire) #function composing the query print_info_mail(adresse, requete) #function printing a web page telling the user that the query is ongoing and that she will be advised by email when it is done results=req(requete, 91) #function launching the query fname=fichier_resultats(results) #function writing the results to a file if(fname): envoi_res(fname, requete, adresse) #function sending the email to the user The problem I have is that the process obviously remains active throughout the entire program, including the query, and that I, therefore, sometimes get timeout problems with apache. So, what I would like to do is to go through all the steps until the printing of the web page and then somehow fork the process of querying so that the cgi script terminates and the querying, result file writing and email sending are done in the background. I have no experience with either forking or threading, but the way I understand them any child processes die when the parent dies. I have tried the recipe in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 which is supposed to fork a process as daemon, thus decoupling it from the calling terminal, but I don't seem to get it to work (I get one defunct process and the child process, but the timeout problem remains). I am also not sure this is actually what I need (I don't know if what I describe above is "decoupling from the calling terminal"). So, could some give me a pointer to possible solutions ? Do I have to make the last part of my program a seperate program and go through a system call ? Thank you ! Moritz From carl.badgley at gmail.com Fri Feb 10 17:49:33 2006 From: carl.badgley at gmail.com (carl.badgley at gmail.com) Date: Fri, 10 Feb 2006 10:49:33 -0600 Subject: [Tutor] nutshell review In-Reply-To: <43ECBE0B.2050706@tds.net> References: <01d801c62e20$e3fede00$0b01a8c0@xp> <1cbf5cf90602100756t11727108i141f2801f85125ca@mail.gmail.com> <1139587735.25713.1.camel@localhost.localdomain> <43ECBE0B.2050706@tds.net> Message-ID: <1cbf5cf90602100849h6b5980fctc8f8e47e4a8c1df7@mail.gmail.com> Thanks for the info.../sigh well I shall be waiting with bells on Carl On 2/10/06, Kent Johnson wrote: > > nephish wrote: > > yeah, one of the guys that posted earlier mentioned late feb as a > > release of the new one. i think i am going to go ahead and get the > > cookbook now, and then pick up the new nutshell later. > > It's the third edition of Python Essential Reference that is due Feb 24. > Judging from his posts to comp.lang.python, Alex Martelli is working on > a second edition of the Nutshell - or at least feeling guilty about > *not* working on it - but I haven't seen any dates. > > Kent > > _______________________________________________ > 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/20060210/e5841e95/attachment.htm From Barry.Carroll at psc.com Fri Feb 10 17:58:41 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 10 Feb 2006 08:58:41 -0800 Subject: [Tutor] nutshell review Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C35E4@eugsrv400.psc.pscnet.com> Greetings: I have been programming in Python for about a year. We use Python 2.3; we haven't migrated to 2.4 because the Real-time OS we use in our test systems doesn't yet support it. I have the four O'Reilly 'standards' as well ("Nutshell", "Learning", "Cookbook", and "Programming"). I use "Nutshell" and "Learning" the most by far. When I'm looking for a detailed example of some implementation I will look through "Cookbook" or "Programming", but when I need to look up usage or syntax, or remind myself how some feature works, I go to "Nutshell" first and then "Learning" I use them both nearly every day. I find that "Nutshell" supports 2.3 very well. Don't know about 2.4. Another book I have just found that may turn out useful is "Python Programming Patterns" by Thomas W. Christopher, published by Prentice Hall PTR. From the reviews I've read, It isn't really a 'design patterns' book in the usual sense, but it contains good demonstrations of applying Python to solve real problems. I don't know for myself yet, as I just ordered it yesterday. We'll see. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ "Never trust anything that can think for itself if you can't see where it keeps its brain" JK Rowling > -----Original Message----- > ------------------------------ > > Message: 10 > Date: Fri, 10 Feb 2006 02:18:20 +0000 > From: nephish > Subject: [Tutor] nutshell review > To: tutor at python.org > Message-ID: <1139537900.20224.2.camel at bitsbam> > Content-Type: text/plain > > lo there, > i know this comes up from time to time. i am considering buying 'python > in a nutshell'. All the reviews i have read for it are very good. But it > only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at > home. As good a reference as it is, is it too dated to be that good > still ? i have 'Learning Python' and 'Programming Python'. Learning is > awesome for me, Programming is a bit over my head. > any suggestions? From mac at Wireless.Com Fri Feb 10 12:11:53 2006 From: mac at Wireless.Com (Mike Cheponis) Date: Fri, 10 Feb 2006 03:11:53 -0800 (PST) Subject: [Tutor] cannonical matrix representation? Message-ID: What's the best way to represent a matrix M with 4 dimensions, such as M[x][y][z][t] where each element in the sparse matrix could be a simple number, or could be an executable Python function snipped that returns a value when that cell is evaluated? The user of the program will type in Python functions to be inserted into particular cells in the 4-D matrix. I did't see any package that exactly does this; do I write my own Matrix class and base it on lists? Thanks! -Mike p.s. This seems to me like it ought to be built into the base language - multidimensional object arrays. (Indeed, maybe it is, and I'm just too dense to notice!) From bzhang at sangamo.com Fri Feb 10 20:10:28 2006 From: bzhang at sangamo.com (Beilin Zhang) Date: Fri, 10 Feb 2006 11:10:28 -0800 Subject: [Tutor] cgi script: how to continue a process in the backgrou nd and return from cgi script Message-ID: <50FD00D269EBD311956100104B141CA3013A416D@pasteur.sangamo.com> I think you need to close the IO streams before forking the child process. Something like sys.stdout.flush() sys.stdout.close() sys.stdin.close() sys.stderr.close() os.close(0) os.close(1) os.close(2) This is probably not the best way, but it works for me. Beilin Zhang -----Original Message----- From: Moritz Lennert [mailto:mlennert at club.worldonline.be] Sent: Friday, February 10, 2006 8:03 AM To: tutor at python.org Subject: [Tutor] cgi script: how to continue a process in the background and return from cgi script Hello, I need some pointers in the right direction for the following problem: I have a cgi script which reads in some form elements, uses them to compose an SQL query, sends that query to the postgresql backend, writes the results into a temporary file and sends a mail to the user with the link to the file. The main block of the program is very simple formulaire = cgi.FieldStorage(keep_blank_values=1) adresse=formulaire["email1"].value if adresse == "": print_error_adresse() else: requete=compose_req(formulaire) #function composing the query print_info_mail(adresse, requete) #function printing a web page telling the user that the query is ongoing and that she will be advised by email when it is done results=req(requete, 91) #function launching the query fname=fichier_resultats(results) #function writing the results to a file if(fname): envoi_res(fname, requete, adresse) #function sending the email to the user The problem I have is that the process obviously remains active throughout the entire program, including the query, and that I, therefore, sometimes get timeout problems with apache. So, what I would like to do is to go through all the steps until the printing of the web page and then somehow fork the process of querying so that the cgi script terminates and the querying, result file writing and email sending are done in the background. I have no experience with either forking or threading, but the way I understand them any child processes die when the parent dies. I have tried the recipe in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 which is supposed to fork a process as daemon, thus decoupling it from the calling terminal, but I don't seem to get it to work (I get one defunct process and the child process, but the timeout problem remains). I am also not sure this is actually what I need (I don't know if what I describe above is "decoupling from the calling terminal"). So, could some give me a pointer to possible solutions ? Do I have to make the last part of my program a seperate program and go through a system call ? Thank you ! Moritz _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From hugonz-lists at h-lab.net Fri Feb 10 21:03:05 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 10 Feb 2006 14:03:05 -0600 Subject: [Tutor] cgi script: how to continue a process in the background and return from cgi script In-Reply-To: <43ECB946.50502@club.worldonline.be> References: <43ECB946.50502@club.worldonline.be> Message-ID: <43ECF179.4050305@h-lab.net> > So, could some give me a pointer to possible solutions ? Do I have to > make the last part of my program a seperate program and go through a > system call ? Hi, I have had this problem before. The timeout problem with Apache remains because STDOUT of both child and the parent are open. Apache keeps thinking the CGI is still sending data until the filehandle is closed. I have solved it in the pas using this recipe, which is similar to the one you used before: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 Hope that helps, Hugo From Barry.Carroll at psc.com Fri Feb 10 21:42:58 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 10 Feb 2006 12:42:58 -0800 Subject: [Tutor] Iterating over a string: index and value Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> I seem to recall reading somewhere that it is possible to concurrently generate the index and value of a string's characters in a single for statement. Is this true or did imagine it? Here is the scenario: Given an ASCII string of arbitrary length and content, generate a sequence of tuples whose elements are: the index of each character in the string, and data based on the ordinal value of the character in the ASCII collating sequence. The brute force way to do this is >>>>>>>>>> tuplseq = () for idx in mystr: char = mystr[idx] ordval = ord(char) data = process(ordval) tuplseq.append(idx, data) >>>>>>>>>> Is there a way to generate the character (or its ord value) along with the index? E.g.: >>>>>>>>>> tuplseq = () for idx ordval in XXXXXXXXX: tuplseq.append(idx, process(ordval)) >>>>>>>>>> Where XXXXXXXXX is some construct using mystr. BTW, this is for internal software for our test group. Thanks in advance for your help. Barry barry.carroll at psc.com 541-302-1107 ________________________ "Never trust anything that can think for itself if you can't see where it keeps its brain" JK Rowling -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/9a67a808/attachment-0001.htm From edgar.antonio.rv at gmail.com Fri Feb 10 22:04:01 2006 From: edgar.antonio.rv at gmail.com (Edgar Antonio Rodriguez Velazco) Date: Fri, 10 Feb 2006 15:04:01 -0600 Subject: [Tutor] IDE - Editors - Python Message-ID: <9378d12c0602101304k2f1486f8re19883c286a6f779@mail.gmail.com> Try with Python Card. ; ) -- Edgar A. Rodriguez V. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/97edec8c/attachment.html From adam.jtm30 at gmail.com Fri Feb 10 22:42:00 2006 From: adam.jtm30 at gmail.com (Adam) Date: Fri, 10 Feb 2006 21:42:00 +0000 Subject: [Tutor] Iterating over a string: index and value In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> Message-ID: Here's a list comprehension which does it: >>> print [(i, ord(v)) for i, v in enumerate("abcdefg")] [(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] and a for loop: >>> for i, v in enumerate("abcdefg"): ... tuplseq.append((i, ord(v))) ... >>> tuplseq [(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] how's that? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/8be83f82/attachment.htm From davholla2002 at yahoo.co.uk Fri Feb 10 22:51:00 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri, 10 Feb 2006 21:51:00 +0000 (GMT) Subject: [Tutor] Change files Message-ID: <20060210215100.67092.qmail@web25915.mail.ukl.yahoo.com> I wrote a little program that replaces all files called 'abcde' with the file in the directory from which you riun the program. However it does not find them (there is another one). What have I done wrong :- #this program copies the file x to all other places in the directory. #however it does not go to the right places def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for name in dirs: for name in files: if name == file1: shutil.copy(file2,name) print "copied one file" import os import shutil #main top = '/home' a = os.getcwd() filename = 'abcde' file1 = filename file2 = a+'/'+filename getfiles(file1, file2,top) print "finished" --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060210/738ff9e6/attachment.htm From Barry.Carroll at psc.com Fri Feb 10 22:55:41 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 10 Feb 2006 13:55:41 -0800 Subject: [Tutor] Iterating over a string: index and value Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C35E8@eugsrv400.psc.pscnet.com> Adam, That is super! Just what I was looking for. Thanks! And whaddya know? There it is in the Python 2.3 Library reference, section 2.1! Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ "Never trust anything that can think for itself if you can't see where it keeps its brain" JK Rowling ? >________________________________________ >From: Adam [mailto:adam.jtm30 at gmail.com] >Sent: Friday, February 10, 2006 1:42 PM >To: Carroll, Barry >Cc: tutor at python.org >Subject: Re: [Tutor] Iterating over a string: index and value > >Here's a list comprehension which does it: >>>> print [(i, ord(v)) for i, v in enumerate("abcdefg")] >[(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] > >and a for loop: > >>>> for i, v in enumerate("abcdefg"): >...???? tuplseq.append((i, ord(v))) >... >>>> tuplseq >[(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] > >how's that? From tim at johnsons-web.com Fri Feb 10 23:06:46 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 10 Feb 2006 13:06:46 -0900 Subject: [Tutor] Trying a csv error Message-ID: <20060210220646.GW1767@johnsons-web.com> Hello: I'm using the csv module, and resources are imported as in import csv My exception trapping uses etype, value, tb = sys.exc_info() and I'm getting the following value = "newline inside string" type = "_csv.Error" I would like to proceed with the assumption for now that this error should not abort processing. The relevant code snippet is as follows: while(1): try: reader.next() ## csv object method except StopIteration: break I'd like to do the following while(1): try: reader.next() ## csv object method except cvs._csv.Error: ## or something like this print "bad csv record, skipping ...." continue except StopIteration: break The problem is that python does not recognize the error objects and gives me: "'module' object has no attribute '_csv'". Any ideas on how to trap this error? Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From andre.roberge at gmail.com Fri Feb 10 23:05:15 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Fri, 10 Feb 2006 18:05:15 -0400 Subject: [Tutor] cannonical matrix representation? In-Reply-To: References: Message-ID: <7528bcdd0602101405j6f57a3cdpfe295e87d6727bce@mail.gmail.com> On 2/10/06, Mike Cheponis wrote: > What's the best way to represent a matrix M with 4 dimensions, such as M[x][y][z][t] where each element in the sparse matrix could be a simple number, or could be an executable Python function snipped that returns a value when that cell is evaluated? > > The user of the program will type in Python functions to be inserted into particular cells in the 4-D matrix. > > I did't see any package that exactly does this; do I write my own Matrix class and base it on lists? > > Thanks! -Mike If it is a truly sparse matrix, I would use a dictionary with tuples as keys; i.e., m{(x, y, z, t) = "element"} Andr? > > p.s. This seems to me like it ought to be built into the base language - multidimensional object arrays. (Indeed, maybe it is, and I'm just too dense to notice!) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Feb 10 23:36:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Feb 2006 14:36:03 -0800 (PST) Subject: [Tutor] Trying a csv error In-Reply-To: <20060210220646.GW1767@johnsons-web.com> Message-ID: > I'd like to do the following > while(1): > try: > reader.next() ## csv object method > except cvs._csv.Error: ## or something like this > print "bad csv record, skipping ...." > continue > except StopIteration: > break > > The problem is that python does not recognize the > error objects and gives me: > "'module' object has no attribute '_csv'". > > Any ideas on how to trap this error? Hi Tim, According to the bottom of: http://www.python.org/doc/lib/csv-contents.html you should be able to check for csv.Error. """The csv module defines the following exception: exception Error Raised by any of the functions when an error is detected.""" Here's what it looks like: ###### >>> import csv >>> csv.Error ###### So internally, csv.Error is the thing you've been seeing, but from the API, you should try to ignore that particular internal implementation detail, and just use csv.Error instead. Best of wishes! From alan.gauld at freenet.co.uk Fri Feb 10 23:53:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Feb 2006 22:53:52 -0000 Subject: [Tutor] cannonical matrix representation? References: Message-ID: <002101c62e94$dd4b3990$0b01a8c0@xp> > p.s. This seems to me like it ought to be built into the base language > - multidimensional object arrays. The only languages I know that truly support anything like what you want are programmes like Mathematica and arguably MS Excel Basic... There is a pseudo mathematica somewhere in Python but otherwise its roll your own time ... I think... Which usually means its time for somebody to find a ready wrapped solution :-) 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 Feb 10 23:51:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Feb 2006 22:51:43 -0000 Subject: [Tutor] Iterating over a string: index and value References: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> Message-ID: <001d01c62e94$907d8320$0b01a8c0@xp> > generate the index and value of a string's characters in a single for > statement. Is this true or did imagine it? >>> for i,c in enumerate('fred'): print i,c ... 0 f 1 r 2 e 3 d Like that? Alan G. From tim at johnsons-web.com Sat Feb 11 00:25:59 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 10 Feb 2006 14:25:59 -0900 Subject: [Tutor] Trying a csv error In-Reply-To: References: <20060210220646.GW1767@johnsons-web.com> Message-ID: <20060210232559.GY1767@johnsons-web.com> Hi Danny: Thanks! tim (who_should_have_read_the_docs) * Danny Yoo [060210 13:56]: > > I'd like to do the following > > while(1): > > try: > > reader.next() ## csv object method > > except cvs._csv.Error: ## or something like this > > print "bad csv record, skipping ...." > > continue > > except StopIteration: > > break > > > > The problem is that python does not recognize the > > error objects and gives me: > > "'module' object has no attribute '_csv'". > > > > Any ideas on how to trap this error? > > Hi Tim, > > According to the bottom of: > > http://www.python.org/doc/lib/csv-contents.html > > you should be able to check for csv.Error. > > """The csv module defines the following exception: > > exception Error > Raised by any of the functions when an error is detected.""" > > > Here's what it looks like: > > ###### > >>> import csv > >>> csv.Error > > ###### > > So internally, csv.Error is the thing you've been seeing, but from the > API, you should try to ignore that particular internal implementation > detail, and just use csv.Error instead. > > > Best of wishes! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From victor at grupocdm.com Sat Feb 11 02:25:16 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Fri, 10 Feb 2006 19:25:16 -0600 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: <43EB1FD5.6010005@tds.net> References: <1139449587.21137.14.camel@elrond> <43EB1FD5.6010005@tds.net> Message-ID: <1139621116.7878.5.camel@elrond> WOW!! This is really great. Thanks Ken. This first one is definitely going to my personal scripts directory ;-) Victor On Thu, 2006-02-09 at 05:56 -0500, Kent Johnson wrote: > Victor Bouffier wrote: > > Hi to all, > > > > I'd like to split a long string into equally long strings (len(str) = > > 3). > > This is a very popular topic in the Python Cookbook. See for example > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095 > > and the links in the comments for the first recipe above. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From victor at grupocdm.com Sat Feb 11 04:48:57 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Fri, 10 Feb 2006 21:48:57 -0600 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: References: Message-ID: <1139629738.7878.22.camel@elrond> Aha!!! I believe this is what I was looking for in the first place (not that I will use it anyway, given the alternatives provided by others). I guess that coming from a Perl background, which as you know includes regexes as part of the core language, you tend to look to all solutions through this lens. I faced this problem before and solved it using regexes but could not remember how. Your re.findall() suggestion is nice though. Very clean. Thanks Danny. On Wed, 2006-02-08 at 18:55 -0800, Danny Yoo wrote: > > On Wed, 8 Feb 2006, Victor Bouffier wrote: > > > Hi to all, > > > > I'd like to split a long string into equally long strings (len(str) = > > 3). I did the following using regexes: > > > > >>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' > > >>> o = re.split(r'(...)', n) > > >>> print o > > ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', > > 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', > > '', 'w0s', '', 'dq3', '', 'zjf', ''] > > > > Which gives me empty strings between each value. > > Hi Victor, > > Try using re.findall() instead of re.split(). The behavior you're seeing > with split is perfectly logical: each pair of empty strings is being split > by that three-character sequence. > > > Best of wishes! > > From victor at grupocdm.com Sat Feb 11 04:49:10 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Fri, 10 Feb 2006 21:49:10 -0600 Subject: [Tutor] Splitting long string into same len parts In-Reply-To: <012301c62d5d$9ddf66b0$0b01a8c0@xp> References: <1139449587.21137.14.camel@elrond> <012301c62d5d$9ddf66b0$0b01a8c0@xp> Message-ID: <1139629751.7878.23.camel@elrond> On Thu, 2006-02-09 at 09:45 +0000, Alan Gauld wrote: > > Define easier :-) > Right! > You could just use string slicing and a stepsize of 3 in range: > > lst = [mystring[index : index+3] for index in range(0,len(mystring),3)] > Ever since I found them, list comprehensions are my favorites. > ... and you still have problems where the > string is not exactly divisible by 3, should you add padding? > Alan, I understand where you are coming from. However, in this case I don't have a problem since the incoming string will always be divisible by 3, in this particular case. Thanks for pointing it out though. Victor From smiles at worksmail.net Sat Feb 11 05:42:24 2006 From: smiles at worksmail.net (Smith) Date: Fri, 10 Feb 2006 22:42:24 -0600 Subject: [Tutor] cannonical matrix representation? References: Message-ID: <018c01c62ec5$afcf47f0$542c4fca@csmith> | 3. cannonical matrix representation? (Mike Cheponis) | | What's the best way to represent a matrix M with 4 dimensions, such | as M[x][y][z][t] where each element in the sparse matrix could be a | simple number, or could be an executable Python function snipped that | returns a value when that cell is evaluated? | | The user of the program will type in Python functions to be inserted | into particular cells in the 4-D matrix. | | I did't see any package that exactly does this; do I write my own | Matrix class and base it on lists? I don't know how full-blown of a solution that you need, but a little helper function for dictionaries (as was noted as a good way to deal with a sparse pmatric) might suffice, something like this,maybe. ### def setdict(d,v,*k): #args = dictionary, value, key all separated by commas d[tuple(k)]=str(v) def evaldict(d,*k): #return the evaluated entry at key k in dictionary d return eval(d[tuple(k)]) d={} setdict(d,1,1,2) setdict(d,'x+3',2) print d x=3 print evaldict(d,1,2) print evaldict(d,2) ### output {(1, 2): '1', (2,): 'x+3'} 1 6 ### The evaluation will pull its values from the context in which the evaldict is being made. There are ways to get around this, but just ask if you need/want to go this direction. From victor at grupocdm.com Sat Feb 11 06:08:44 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Fri, 10 Feb 2006 23:08:44 -0600 Subject: [Tutor] Iterating over a string: index and value In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C35E5@eugsrv400.psc.pscnet.com> Message-ID: <1139634524.10298.4.camel@elrond> On Fri, 2006-02-10 at 12:42 -0800, Carroll, Barry wrote: > I seem to recall reading somewhere that it is possible to concurrently > generate the index and value of a string?s characters in a single for > statement. Is this true or did imagine it? > > > > Here is the scenario: > > > > Given an ASCII string of arbitrary length and content, generate a > sequence of tuples whose elements are: > > the index of each character in the string, and > > data based on the ordinal value of the character in the ASCII > collating sequence. > Hi Barry, Have a look at enumerate: >>> list(enumerate('abcdefghijk')) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k')] You need to work on each tuple in the iterable, but the function takes you halfway. Hope it helps. Victor From carroll at tjc.com Sat Feb 11 06:30:47 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Feb 2006 21:30:47 -0800 (PST) Subject: [Tutor] nutshell review In-Reply-To: <1cbf5cf90602100818v726042fbjcd9074fd96fe7f2a@mail.gmail.com> Message-ID: It's the Python Essential Reference book, Third Edition due out February 24. I'm not aware of a new Nutshell coming out. On Fri, 10 Feb 2006 carl.badgley at gmail.com wrote: > See I couldn't tell if he was talking about the Nutshell book or the Python > Essential Reference book...thanks > Carl > > On 2/10/06, nephish wrote: > > > > yeah, one of the guys that posted earlier mentioned late feb as a > > release of the new one. i think i am going to go ahead and get the > > cookbook now, and then pick up the new nutshell later. > > sk > > > > > From carroll at tjc.com Sat Feb 11 06:34:22 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Feb 2006 21:34:22 -0800 (PST) Subject: [Tutor] nutshell review In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C35E4@eugsrv400.psc.pscnet.com> Message-ID: On Fri, 10 Feb 2006, Carroll, Barry wrote: > Another book I have just found that may turn out useful is "Python > Programming Patterns" by Thomas W. Christopher, published by Prentice > Hall PTR. I got that from the library about a year ago. I found it interesting, but not too helpful. One problem is that it explains a Python feature in terms of other python features only, and you don't really get the flavor of what the heck the feature being described actually can do for you; although I'm sure the description of the feature is technically correct. I recently happened across a cheap copy used, and bought it; it was worth the money for the used copy, but I wouldn't have bought it new. (Unfortunately, the copy is at my office, and I'm at home, so unable to provide a good concrete example.) From jhe13586 at bigpond.net.au Sat Feb 11 07:19:55 2006 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Sat, 11 Feb 2006 16:19:55 +1000 Subject: [Tutor] Postgresql+Python -tutorial? In-Reply-To: <018101c5686d$7eff9450$26ba8651@xp> References: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: 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? Yes and no. Postgresql offers more features and is IMO more flexible than most SQL servers out there. Example: postgresql enables you to set up editable sql views. This means that you can concatenate several tables into a view (A stored SQL query), and use this as if it was an ordinary table by adding, deleting and editing data within it. Very handy if you want to set up "infinite keyword" systems. E.g. MemoTable with an integer "memoid" field and a text field for a "memo" KeywordTable with an integer "keyid" field and a text "keyword" field. MemoKeyTable with an integer "memokeyid" field, an integer "memoid" field, and an integer "keyid" field - with a UNIQUE index/constraint across the "memoid" and "keyid" fields. To get the keywords for each memo, use a view that contains something like the following SQL query. (Warning, the syntax is probably incorrect.) FROM MemoTable, KeywordTable, MemoKeyTable GET MemoTable.memoid, MemoTable.memo, KeywordTable.keyword WHERE (MemoTable.memoid == MemoKeyTable.memoid) AND (KeywordTable.keyid == MemoKeyTable.keyid) SORT BY MemoTable.memoid; In MySQL, this would let you retrieve the data from the tables, but Postgresql will let you add entirely new memos, add a new keyword to a memo, remove a memo cleanly, remove a keyword from a memo, etc. all from the view. However, MySQL is used a lot in web pages because it can return queries much faster than any other database - the catch is that it can only do this with transaction-less tables. (I don't know your level of SQL experience, so please forgive me if I explain things you already know.) Transactions enable you to have a whole series of SQL commands fail if one fails. Useful if you want to add interconnected data across a series of tables. E.g. a finance company moving money from one account to another. You definitely don't want the money to be removed from the first account unless you can add it to the second account. (MySQL can use transactions, however, you immediately lose the speed advantage.) Finally, Postgresql does some things differently from other databases (Calling a function to fill a default value for autoincrementing, rather than a dedicated SERIAL field type.) If you're planing to access the database directly from python, this is no hassle, but if you want to use it through something like OpenOffice.org or ODBC drivers, some things don't work to well. Hope that helped? Joal Heagney From jhe13586 at bigpond.net.au Sat Feb 11 07:34:31 2006 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Sat, 11 Feb 2006 16:34:31 +1000 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <200602060946.42913.pkraus@pelsupply.com> References: <200602060946.42913.pkraus@pelsupply.com> Message-ID: Paul Kraus wrote: > Which editors does everyone use and why. Please keep the discussion to IDE's > rather then any editors. I am well versed on Emacs and VI so anything beyond > them would be appreciative. Why you like the editor and how it helps reduce > your development time would be productive and helpfull. > > TIA, Idle. Purely because I don't do much programming and all I need is a text editor with a built in command line to test ideas and check completed modules. The types of things I use python for are: - semi-quick scripts for one-off automation problems that bash scripting can't solve, - small programs to explore computer or math's based problems. e.g. sorting algorithms, genetic algorithms, Fourier transforms of waves to analyze frequency distributions (Trying to make a white/pink noise generator and ran it's output into the computer's soundcard) - as a handy-dandy scientific calculator when I can't be bothered hunting down my RL scientific calculator :). Most of these have console-argument, interactive console (raw_input) or file-based input methods, with a text console output. Joal Heagney From bokr at oz.net Wed Feb 8 16:54:38 2006 From: bokr at oz.net (Bengt Richter) Date: Wed, 08 Feb 2006 15:54:38 GMT Subject: [Tutor] small floating point number problem References: <006d01c62c7d$d7bab730$1f2c4fca@csmith> <001c01c62c86$d694beb0$b83efea9@RaymondLaptop1> Message-ID: <43ea0d7e.264446924@news.gmane.org> On Wed, 08 Feb 2006 03:08:25 -0500, "Raymond Hettinger" wrote: >[Smith] >>I just ran into a curious behavior with small floating points, trying to >>find the limits of them on my machine (XP). Does anyone know why the '0.0' >>is showing up for one case below but not for the other? According to my >>tests, the smallest representable float on my machine is much smaller than >>1e-308: it is >> >> 2.470328229206234e-325 >> >> but I can only create it as a product of two numbers, not directly. Here >> is an attempt to create the much larger 1e-308: >> >>>>> a=1e-308 >>>>> a >> 0.0 > >The clue is in that the two differ by 17 orders of magnitude (325-308) which >is about 52 bits. > >The interpreter builds 1-e308 by using the underlying C library >string-to-float function and it isn't constructing numbers outside the >normal range for floats. When you enter a value outside that range, the >function underflows it to zero. > >In contrast, your computed floats (such as 1*1e-307) return a denormal >result (where the significand is stored with fewer bits than normal because >the exponent is already at its outer limit). That denormal result is not >zero and the C library float-to-string conversion successfully generates a >decimal string representation. > >The asymmetric handling of denormals by the atof() and ftoa() functions is >why you see a difference. A consequence of that asymmetry is the breakdown >of the expected eval(repr(f))==f invariant: > >>>> f = f = .1*1e-307 >>>> eval(repr(f)) == f >False > BTW, for the OP, chasing minimum float values is probably best done with powers of 2 >>> math.ldexp(1, -1074) 4.9406564584124654e-324 >>> math.ldexp(1, -1075) 0.0 >>> .5**1074 4.9406564584124654e-324 >>> .5**1075 0.0 >>> math.frexp(.5**1074) (0.5, -1073) >>> math.frexp(.5**1075) (0.0, 0) Regards, Bengt Richter From bill at celestial.net Sat Feb 11 07:52:42 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 10 Feb 2006 22:52:42 -0800 Subject: [Tutor] Postgresql+Python -tutorial? In-Reply-To: References: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: <20060211065242.GB49090@alexis.mi.celestial.com> On Sat, Feb 11, 2006, Joal Heagney wrote: >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? > >Yes and no. Postgresql offers more features and is IMO more flexible >than most SQL servers out there. > ... >However, MySQL is used a lot in web pages because it can return queries >much faster than any other database - the catch is that it can only do >this with transaction-less tables. ... >(MySQL can use transactions, however, you immediately lose the speed >advantage.) Postgresql is a far more mature product than mysql when it comes to the critical ACID features, transactions, stored procedures, and triggers. Postgresql is also far more compliant with SQL standards. As I understand it, mysql's transaction capabilities are only available when it's built with the innodb back end storage. Mysql and innodb licensing isn't GPL, and the company that provides innodb has recently been purchased by a commercial databae vendor (I don't remeber which one offhand). The licensing issues with mysql make me very leary of doing anything commercial with it. There is also the python sqlobject system which provides a very object oriented wrapper on top of relational databases. Using sqlobject can make many database functions very easy, and largely independent of the underlying database. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``I don't make jokes, I just watch the Government and report the facts...'' Will Rogers From alan.gauld at freenet.co.uk Sat Feb 11 10:06:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Feb 2006 09:06:07 -0000 Subject: [Tutor] Postgresql+Python -tutorial? References: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: <006501c62eea$64ec98d0$0b01a8c0@xp> > Alan G wrote: >> Is there some advantage to Postgres over MySql? > > Yes and no. Postgresql offers more features and is IMO more flexible > than most SQL servers out there. Thanks for the list, several things I didn't know. > Example: postgresql enables you to set up editable sql views. Most databases I've used (Oracle, DB2, Interbase) can do this, I wasn't aware MySql couldn't. > However, MySQL is used a lot in web pages because it can return queries > much faster than any other database - the catch is that it can only do > this with transaction-less tables. And I didn't know about Transactionless tables. > Hope that helped? > > Joal Heagney Yes thanks. My interest comes from the fact that I am in the process of reconfiguring my home network and in particular wanted a popular opensource database to replace my ancient copy of Oracle for Linux. The choices are Firebird, MySql and Postgres. I am familiar with the first but the others are more popular (think job experience...) Thanks again, Alan G. From python at venix.com Sat Feb 11 15:48:25 2006 From: python at venix.com (Python) Date: Sat, 11 Feb 2006 09:48:25 -0500 Subject: [Tutor] Postgresql+Python -tutorial? In-Reply-To: References: <018101c5686d$7eff9450$26ba8651@xp> Message-ID: <1139669305.1978.196.camel@www.venix.com> On Sat, 2006-02-11 at 16:19 +1000, Joal Heagney wrote: > > I'm curious. Why? > > Is there some advantage to Postgres over MySql? > > Yes and no. Postgresql offers more features and is IMO more flexible > than most SQL servers out there. A friend described MySQL as the RDBMS for people who do not really need an RDBMS. This is a little unfair, but has just enough truth to bear repeating. MyISAM tables offer good performance at the cost of transactions, views, row locking, etc. The MySQL documentation suggests some work-arounds. I use MySQL for these benefits: replication - (off-site near real time backups; simple distributed processing) enum and set datatypes - easy to use integer to text mapping fields. enums == radio buttons (single-select), sets == check boxes (multi- select) very easy administration good performance Obviously, the lack of transactions is a nuisance. If you are converting software from another RDBMS, the MySQL limitations will be especially painful. When replication and/or easy administration trump other concerns, MySQL can be a good choice. -- Lloyd Kvam Venix Corp From davholla2002 at yahoo.co.uk Sat Feb 11 23:09:38 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat, 11 Feb 2006 22:09:38 +0000 (GMT) Subject: [Tutor] Change files In-Reply-To: Message-ID: <20060211220938.56582.qmail@web25905.mail.ukl.yahoo.com> Bruce, Thanks but is was not the solution. It goes through all the directories but does not seem to work. Here is the modified code :- def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for name in dirs: print name for name in files: if name == file1: name = os.getcwd()+'/'+name print "the name is" + name shutil.copy(file2,name) print "copied one file" print os.getcwd() import os import shutil #main top = '/home' a = os.getcwd() filename = 'abcde' file1 = filename file2 = a+'/'+filename print file2 getfiles(filename, file2,top) print "finished" David Bruce wrote: I guess that you need to fix two things: 1 the indentaion error after for name in files: 2 specify full path for the destination arg in shutil.copy On 2/10/06, David Holland wrote: > I wrote a little program that replaces all files called 'abcde' with the > file in the directory from which you riun the program. However it does not > find them (there is another one). > What have I done wrong :- > #this program copies the file x to all other places in the directory. > #however it does not go to the right places > def getfiles(file1,file2,top): > for root, dirs, files in os.walk(top): > for name in dirs: > for name in files: > if name == file1: > shutil.copy(file2,name) > print "copied one file" > > import os > import shutil > #main > top = '/home' > a = os.getcwd() > filename = 'abcde' > file1 = filename > file2 = a+'/'+filename > getfiles(file1, file2,top) > print "finished" > > > > > ________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! > Security Centre. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > --------------------------------- Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060211/105894d9/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Feb 12 06:08:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Feb 2006 21:08:57 -0800 (PST) Subject: [Tutor] Change files In-Reply-To: <20060211220938.56582.qmail@web25905.mail.ukl.yahoo.com> Message-ID: > for root, dirs, files in os.walk(top): > for name in dirs: > print name > for name in files: This code looks suspicious. At this point, when we say "name", what do we expect to get here? Do you mean the directory name, or the file name? It can't be both! *grin* From Senthil_OR at Dell.com Sun Feb 12 13:41:47 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Sun, 12 Feb 2006 06:41:47 -0600 Subject: [Tutor] Change files Message-ID: David, in getfiles, the os.getcwd() points the main programs cwd only and so shutil.copy() fails. so changing to name = os.path.join(root,name) helps us get the file in the directory we checked against. def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for dirname in dirs: print dirname for name in files: if name == file1: name = os.path.join(root,name) print "the name is" + name shutil.copy(file2,name) print "copied one file" print os.getcwd() import os import shutil #main top = r'c:\temp' a = os.getcwd() filename = 'some.txt' file1 = filename file2 = a+ os.sep +filename print file2 getfiles(filename, file2,top) print "finished" thanks! -- Senthil _____ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of David Holland Sent: Sunday, February 12, 2006 3:40 AM To: Bruce Cc: tutor python Subject: Re: [Tutor] Change files Bruce, Thanks but is was not the solution. It goes through all the directories but does not seem to work. Here is the modified code :- def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for name in dirs: print name for name in files: if name == file1: name = os.getcwd()+'/'+name print "the name is" + name shutil.copy(file2,name) print "copied one file" print os.getcwd() import os import shutil #main top = '/home' a = os.getcwd() filename = 'abcde' file1 = filename file2 = a+'/'+filename print file2 getfiles(filename, file2,top) print "finished" David Bruce wrote: I guess that you need to fix two things: 1 the indentaion error after for name in files: 2 specify full path for the destination arg in shutil.copy On 2/10/06, David Holland wrote: > I wrote a little program that replaces all files called 'abcde' with the > file in the directory from which you riun the program. However it does not > find them (there is another one). > What have I done wrong :- > #this program copies the file x to all other places in the directory. > #however it does not go to the right places > def getfiles(file1,file2,top): > for root, dirs, files in os.walk(top): > for name in dirs: > for name in files: > if name == file1: > shutil.copy(file2,name) > print "copied one file" > > import os > import shutil > #main > top = '/home' > a = os.getcwd() > filename = 'abcde' > file1 = filename > file2 = a+'/'+filename > getfiles(file1, file2,top) > print "finished" > > > > > ________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! > Security Centre. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _____ Yahoo! Photos - NEW, now offering a quality print service from just 8p a photo. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060212/e5b45817/attachment.htm From davholla2002 at yahoo.co.uk Sun Feb 12 16:20:22 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sun, 12 Feb 2006 15:20:22 +0000 (GMT) Subject: [Tutor] Change files In-Reply-To: Message-ID: <20060212152022.59061.qmail@web25901.mail.ukl.yahoo.com> Thanks, now I understand and that works perfectly. Senthil_OR at Dell.com wrote: David, in getfiles, the os.getcwd() points the main programs cwd only and so shutil.copy() fails. so changing to name = os.path.join(root,name) helps us get the file in the directory we checked against. def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for dirname in dirs: print dirname for name in files: if name == file1: name = os.path.join(root,name) print "the name is" + name shutil.copy(file2,name) print "copied one file" print os.getcwd() import os import shutil #main top = r'c:\temp' a = os.getcwd() filename = 'some.txt' file1 = filename file2 = a+ os.sep +filename print file2 getfiles(filename, file2,top) print "finished" thanks! -- Senthil --------------------------------- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of David Holland Sent: Sunday, February 12, 2006 3:40 AM To: Bruce Cc: tutor python Subject: Re: [Tutor] Change files Bruce, Thanks but is was not the solution. It goes through all the directories but does not seem to work. Here is the modified code :- def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for name in dirs: print name for name in files: if name == file1: name = os.getcwd()+'/'+name print "the name is" + name shutil.copy(file2,name) print "copied one file" print os.getcwd() import os import shutil #main top = '/home' a = os.getcwd() filename = 'abcde' file1 = filename file2 = a+'/'+filename print file2 getfiles(filename, file2,top) print "finished" David Bruce wrote: I guess that you need to fix two things: 1 the indentaion error after for name in files: 2 specify full path for the destination arg in shutil.copy On 2/10/06, David Holland wrote: > I wrote a little program that replaces all files called 'abcde' with the > file in the directory from which you riun the program. However it does not > find them (there is another one). > What have I done wrong :- > #this program copies the file x to all other places in the directory. > #however it does not go to the right places > def getfiles(file1,file2,top): > for root, dirs, files in os.walk(top): > for name in dirs: > for name in files: > if name == file1: > shutil.copy(file2,name) > print "copied one file" > > import os > import shutil > #main > top = '/home' > a = os.getcwd() > filename = 'abcde' > file1 = filename > file2 = a+'/'+filename > getfiles(file1, file2,top) > print "finished" > > > > > ________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! > Security Centre. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > --------------------------------- Yahoo! Photos ? NEW, now offering a quality print service from just 8p a photo. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060212/0eace3c4/attachment.htm From smiles at worksmail.net Sun Feb 12 19:44:51 2006 From: smiles at worksmail.net (Smith) Date: Sun, 12 Feb 2006 12:44:51 -0600 Subject: [Tutor] nice() Message-ID: <038701c63004$733603c0$132c4fca@csmith> I've been thinking about a function that was recently proposed at python-dev named 'areclose'. It is a function that is meant to tell whether two (or possible more) numbers are close to each other. It is a function similar to one that exists in Numeric. One such implementation is def areclose(x,y,abs_tol=1e-8,rel_tol=1e-5): diff = abs(x-y) return diff <= ans_tol or diff <= rel_tol*max(abs(x),abs(y)) (This is the form given by Scott Daniels on python-dev.) Anyway, one of the rationales for including such a function was: When teaching some programming to total newbies, a common frustration is how to explain why a==b is False when a and b are floats computed by different routes which ``should'' give the same results (if arithmetic had infinite precision). Decimals can help, but another approach I've found useful is embodied in Numeric.allclose(a,b) -- which returns True if all items of the arrays are ``close'' (equal to within certain absolute and relative tolerances) The problem with the above function, however, is that it *itself* has a comparison between floats and it will give undesired result for something like the following test: ### >>> print areclose(2, 2.1, .1, 0) #see if 2 and 2.1 are within 0.1 of each other False >>> ### Here is an alternative that might be a nice companion to the repr() and round() functions: nice(). It is a combination of Tim Peter's delightful 'case closed' presentation in the thread, "Rounding to n significant digits?" [1] and the hidden magic of "prints" simplification of floating point numbers when being asked to show them. It's default behavior is to return a number in the form that the number would have when being printed. An optional argument, however, allows the user to specify the number of digits to round the number to as counted from the most significant digit. (An alternative name, then, could be 'lround' but I think there is less baggage for the new user to think about if the name is something like nice()--a function that makes the floating point numbers "play nice." And I also think the name...sounds nice.) Here it is in action: ### >>> 3*1.1==3.3 False >>> nice(3*1.1)==nice(3.3) True >>> x=3.21/0.65; print x 4.93846153846 >>> print nice(x,2) 4.9 >>> x=x*1e5; print nice(x,2) 490000.0 ### Here's the function: ### def nice(x,leadingDigits=0): """Return x either as 'print' would show it (the default) or rounded to the specified digit as counted from the leftmost non-zero digit of the number, e.g. nice(0.00326,2) --> 0.0033""" assert leadingDigits>=0 if leadingDigits==0: return float(str(x)) #just give it back like 'print' would give it leadingDigits=int(leadingDigits) return float('%.*e' % (leadingDigits,x)) #give it back as rounded by the %e format ### Might something like this be useful? For new users, no arguments are needed other than x and floating points suddenly seem to behave in tests made using nice() values. It's also useful for those computing who want to show a physically meaningful value that has been rounded to the appropriate digit as counted from the most significant digit rather than from the decimal point. Some time back I had worked on the significant digit problem and had several math calls to figure out what the exponent was. The beauty of Tim's solution is that you just use built in string formatting to do the work. Nice. /c [1] http://mail.python.org/pipermail/tutor/2004-July/030324.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060212/1792bf6b/attachment-0001.html From mlennert at club.worldonline.be Sun Feb 12 21:36:00 2006 From: mlennert at club.worldonline.be (Moritz Lennert) Date: Sun, 12 Feb 2006 21:36:00 +0100 (CET) Subject: [Tutor] SOLVED: Re: cgi script: how to continue a process in the background and return from cgi script In-Reply-To: <43ECF179.4050305@h-lab.net> References: <43ECB946.50502@club.worldonline.be> <43ECF179.4050305@h-lab.net> Message-ID: <60693.85.10.64.177.1139776560.squirrel@geog-pc40.ulb.ac.be> On Fri, February 10, 2006 21:03, Hugo Gonz?lez Monteverde wrote: > >> So, could some give me a pointer to possible solutions ? Do I have to >> make the last part of my program a seperate program and go through a >> system call ? > > Hi, > > I have had this problem before. The timeout problem with Apache remains > because STDOUT of both child and the parent are open. Apache keeps > thinking the CGI is still sending data until the filehandle is closed. > > I have solved it in the pas using this recipe, which is similar to the > one you used before: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 I got it to work with this recipe, thanks a lot ! (also to Beilin Zhang who said the same about IO streams) Moritz From alan.gauld at freenet.co.uk Mon Feb 13 00:24:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Feb 2006 23:24:45 -0000 Subject: [Tutor] nice() References: <038701c63004$733603c0$132c4fca@csmith> Message-ID: <00a001c6302b$82d51f10$0b01a8c0@xp> I have no particularly strong view on the concept (except that I usually see the "problem" as a valuable opportunity to introduce a concept that has far wider reaching consequences than floating point numbers!). However I do dislike the name nice() - there is already a nice() in the os module with a fairly well understood function. But I'm sure some time with a thesaurus can overcome that single mild objection. :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Smith" To: Cc: ; Sent: Sunday, February 12, 2006 6:44 PM Subject: [Tutor] nice() I've been thinking about a function that was recently proposed at python-dev named 'areclose'. It is a function that is meant to tell whether two (or possible more) numbers are close to each other. It is a function similar to one that exists in Numeric. One such implementation is def areclose(x,y,abs_tol=1e-8,rel_tol=1e-5): diff = abs(x-y) return diff <= ans_tol or diff <= rel_tol*max(abs(x),abs(y)) (This is the form given by Scott Daniels on python-dev.) Anyway, one of the rationales for including such a function was: When teaching some programming to total newbies, a common frustration is how to explain why a==b is False when a and b are floats computed by different routes which ``should'' give the same results (if arithmetic had infinite precision). Decimals can help, but another approach I've found useful is embodied in Numeric.allclose(a,b) -- which returns True if all items of the arrays are ``close'' (equal to within certain absolute and relative tolerances) The problem with the above function, however, is that it *itself* has a comparison between floats and it will give undesired result for something like the following test: ### >>> print areclose(2, 2.1, .1, 0) #see if 2 and 2.1 are within 0.1 of each >>> other False >>> ### Here is an alternative that might be a nice companion to the repr() and round() functions: nice(). It is a combination of Tim Peter's delightful 'case closed' presentation in the thread, "Rounding to n significant digits?" [1] and the hidden magic of "prints" simplification of floating point numbers when being asked to show them. It's default behavior is to return a number in the form that the number would have when being printed. An optional argument, however, allows the user to specify the number of digits to round the number to as counted from the most significant digit. (An alternative name, then, could be 'lround' but I think there is less baggage for the new user to think about if the name is something like nice()--a function that makes the floating point numbers "play nice." And I also think the name...sounds nice.) Here it is in action: ### >>> 3*1.1==3.3 False >>> nice(3*1.1)==nice(3.3) True >>> x=3.21/0.65; print x 4.93846153846 >>> print nice(x,2) 4.9 >>> x=x*1e5; print nice(x,2) 490000.0 ### Here's the function: ### def nice(x,leadingDigits=0): """Return x either as 'print' would show it (the default) or rounded to the specified digit as counted from the leftmost non-zero digit of the number, e.g. nice(0.00326,2) --> 0.0033""" assert leadingDigits>=0 if leadingDigits==0: return float(str(x)) #just give it back like 'print' would give it leadingDigits=int(leadingDigits) return float('%.*e' % (leadingDigits,x)) #give it back as rounded by the %e format ### Might something like this be useful? For new users, no arguments are needed other than x and floating points suddenly seem to behave in tests made using nice() values. It's also useful for those computing who want to show a physically meaningful value that has been rounded to the appropriate digit as counted from the most significant digit rather than from the decimal point. Some time back I had worked on the significant digit problem and had several math calls to figure out what the exponent was. The beauty of Tim's solution is that you just use built in string formatting to do the work. Nice. /c [1] http://mail.python.org/pipermail/tutor/2004-July/030324.html From shuying at gmail.com Mon Feb 13 01:59:54 2006 From: shuying at gmail.com (Shuying Wang) Date: Mon, 13 Feb 2006 11:59:54 +1100 Subject: [Tutor] self Message-ID: <75fa0c3a0602121659w99093fdhf83e45c8f4f48c@mail.gmail.com> Hi, I'm having problems understanding some code I came across: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single Singleton.__single = self What does passing self to Singleton.__single do? --Shuying From carroll at tjc.com Mon Feb 13 04:35:55 2006 From: carroll at tjc.com (Terry Carroll) Date: Sun, 12 Feb 2006 19:35:55 -0800 (PST) Subject: [Tutor] nice() In-Reply-To: <038701c63004$733603c0$132c4fca@csmith> Message-ID: On Sun, 12 Feb 2006, Smith wrote: > ... I think there is less baggage for the new user to think > about if the name is something like nice()--a function that makes the > floating point numbers "play nice." And I also think the name...sounds > nice.) For "number is close enough"? From amonroe at columbus.rr.com Mon Feb 13 04:40:23 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 12 Feb 2006 22:40:23 -0500 Subject: [Tutor] nice() In-Reply-To: References: Message-ID: <153128694993.20060212224023@columbus.rr.com> > On Sun, 12 Feb 2006, Smith wrote: >> ... I think there is less baggage for the new user to think >> about if the name is something like nice()--a function that makes the >> floating point numbers "play nice." And I also think the name...sounds >> nice.) > For "number is close enough"? How about near()... Numbers Equal Adjusted (or Approximated) for Rounding :^) Alan From ismaelgf at adinet.com.uy Mon Feb 13 05:09:33 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Mon, 13 Feb 2006 02:09:33 -0200 Subject: [Tutor] nice() In-Reply-To: <038701c63004$733603c0$132c4fca@csmith> References: <038701c63004$733603c0$132c4fca@csmith> Message-ID: <43F0067D.6080606@adinet.com.uy> Smith wrote: > I've been thinking about a function that was recently proposed at > python-dev named 'areclose'. It is a function that is meant to tell > whether two (or possible more) numbers are close to each other. It > is a function similar to one that exists in Numeric. One such > implementation is > [Snip] How about overloading Float comparison? I'd say that'd "nicer". BTW: Nice is not an... em.. nice name for a function that does what you describe. If I have understood correctly, float to float comparison must be done comparing relative errors, so that when dealing with small but rightly represented numbers it won't tell "True" just because they're "close". I think your/their solution only covers the case when dealing with "big" numbers. Ismael From kenny.li at gmail.com Mon Feb 13 08:38:10 2006 From: kenny.li at gmail.com (Kenny Li) Date: Sun, 12 Feb 2006 23:38:10 -0800 Subject: [Tutor] Instantiate a subClass using an instance of its baseClass Message-ID: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> *Hi Tutor:* ** *My question is "how to instantiate a subClass using an instance of its baseClass?"* *Details below:* *=============* ** *class B(object): * * ''' the baseClass '''* * def __init__(self, arg1, arg2):* * self.a1=arg1* * self.a2=arg2* * * *class C(B): * * ''' C is subClass of B '''* * def __init__(self, arg1, arg2):* * B.__init__(self, arg1, arg2)* * self.extra="blah blah blah"* ** *if __name__ == '__main__':* * c=C("spam", "ham") #<<<< Normal instantiation, No Problem Here.* * * * # Now, I ran into a situation, where I don't have the values of "arg1 and arg2", * * # but I do have an instance of baseClass (B), called b. * ** * # How do I write the class C [for example, its __new__(cls...) static method] to enable me to do the following?* * c=C(b) # <<< This is what I want.* *# Note: I already know I can embed the B in my C class (aka "has-a"), then I can avoid the trouble, * * # but ... doing c=C(b) is more fun and elegant.* ** *Thanks,* ** *Kenny* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060212/93be71a1/attachment.html From ewald.ertl at hartter.com Mon Feb 13 10:20:52 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 13 Feb 2006 10:20:52 +0100 Subject: [Tutor] self In-Reply-To: <75fa0c3a0602121659w99093fdhf83e45c8f4f48c@mail.gmail.com> References: <75fa0c3a0602121659w99093fdhf83e45c8f4f48c@mail.gmail.com> Message-ID: <43F04F74.1000906@hartter.com> Hi Shuying! Shuying Wang wrote: > Hi, > > I'm having problems understanding some code I came across: > > class Singleton: > __single = None > def __init__( self ): > if Singleton.__single: > raise Singleton.__single > Singleton.__single = self > > What does passing self to Singleton.__single do? I would say, this just sets the Singleton.__single to true and stores the reference to the only one allowed instance of the class. When the next time an instance of the class Singleton is requested an exception with the first instance of Singleton is thrown. Hope my explanation is clearly understandable in English Ewald From kent37 at tds.net Mon Feb 13 11:59:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Feb 2006 05:59:15 -0500 Subject: [Tutor] Instantiate a subClass using an instance of its baseClass In-Reply-To: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> Message-ID: <43F06683.2060102@tds.net> Kenny Li wrote: > *class B(object): * > * ''' the baseClass '''* > * def __init__(self, arg1, arg2):* > * self.a1=arg1* > * self.a2=arg2* > * * > *class C(B): * > * ''' C is subClass of B '''* > * def __init__(self, arg1, arg2):* > * B.__init__(self, arg1, arg2)* > * self.extra="blah blah blah"* > ** > *if __name__ == '__main__':* > * # Now, I ran into a situation, where I don't have the values > of "arg1 and arg2", * > * # but I do have an instance of baseClass (B), called b. * > ** > * # How do I write the class C [for example, its > __new__(cls...) static method] to enable me to do the following?* > * c=C(b) # <<< This is what I want.* Two options: 1. Just pass b.a1 and b.a2 to the C constructor: c = C(b.a1, b.a2) A little clumsy but it works. 2. Write C.__init__() to accept either form: def __init__(self, arg1, arg2=None): if isinstance(arg1, B): arg1, arg2 = arg1.a1, arg1.a2 # the rest as before Kent From janos.juhasz at VELUX.com Mon Feb 13 15:57:58 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 13 Feb 2006 15:57:58 +0100 Subject: [Tutor] sys.argv In-Reply-To: Message-ID: Hi, I want to pass args to my python script on XP. This code print 'argv[0] %s' % sys.argv[0] print 'argv[1] %s' % sys.argv[1] print 'argv[2] %s' % sys.argv[2] shows this: argv[0] D:\devel\home\devel\python\db\xlsxml.py argv[1] "K:\IT\admin\test\Flat argv[2] Files\2006\06.02.2006-293753-gy" but I would see this: argv[0] D:\devel\home\devel\python\db\xlsxml.py argv[1] "K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy" argv[2] '' Yours sincerely, ______________________________ J?nos Juh?sz From andre.roberge at gmail.com Mon Feb 13 16:02:39 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 13 Feb 2006 11:02:39 -0400 Subject: [Tutor] sys.argv In-Reply-To: References: Message-ID: <7528bcdd0602130702w19ef1fe9nf1e9cbee1e3b0712@mail.gmail.com> On 2/13/06, J?nos Juh?sz wrote: > Hi, > > I want to pass args to my python script on XP. > This code > print 'argv[0] %s' % sys.argv[0] > print 'argv[1] %s' % sys.argv[1] > print 'argv[2] %s' % sys.argv[2] > > shows this: > argv[0] D:\devel\home\devel\python\db\xlsxml.py > argv[1] "K:\IT\admin\test\Flat > argv[2] Files\2006\06.02.2006-293753-gy" Your path has a space in it (between Flat and Files). This is probably why it is broken as two different arguments. Andr? > > but I would see this: > argv[0] D:\devel\home\devel\python\db\xlsxml.py > argv[1] "K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy" > argv[2] '' > > > Yours sincerely, > ______________________________ > J?nos Juh?sz > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 13 16:10:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Feb 2006 10:10:15 -0500 Subject: [Tutor] sys.argv In-Reply-To: References: Message-ID: <43F0A157.6040903@tds.net> J?nos Juh?sz wrote: > Hi, > > I want to pass args to my python script on XP. > This code > print 'argv[0] %s' % sys.argv[0] > print 'argv[1] %s' % sys.argv[1] > print 'argv[2] %s' % sys.argv[2] > > shows this: > argv[0] D:\devel\home\devel\python\db\xlsxml.py > argv[1] "K:\IT\admin\test\Flat > argv[2] Files\2006\06.02.2006-293753-gy" > > but I would see this: > argv[0] D:\devel\home\devel\python\db\xlsxml.py > argv[1] "K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy" > argv[2] '' Since the file name includes a space you must quote it on the command line, otherwise the system inteprets the space as an argument separator. E.g. > python xlsxml.py "K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy" Kent From janos.juhasz at VELUX.com Mon Feb 13 17:41:23 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 13 Feb 2006 17:41:23 +0100 Subject: [Tutor] sys.argv In-Reply-To: <7528bcdd0602130702w19ef1fe9nf1e9cbee1e3b0712@mail.gmail.com> Message-ID: Thanks Andre, The problem came from my wrong script calling. Python is just fine :) I corrected it, and I can call it now with """ Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\Shell\Flat2Xls\Command] @="python \"D:\\devel\\xlsxml.py\" \"%1\"" """ In this case there is a new menu item for the right click popup for any file that can call my script with the filename as argument. It works well on my machine with sort and long filenames. But it uses the old format dos filename on some other PCs. Is it any way to translate the sort DOS filename to the long NTSF one with python ? But it would be fine to set up XP to call my script with the long filename. Yours sincerely, ______________________________ J?nos Juh?sz VELUX Magyarorsz?g Fert?di ?p?t?komponens Kft. IT Department Malom K?z 1, H-9431 Fert?d Telephone direct: +36 99 537 939 Telephone office: +36 99 537 920 Office fax: +36 99 537 921 Telephone mobile: +36 30 682 6331 @ janos.juhasz at VELUX.com www www.VELUX.com Andre Roberge wrote on 2006.02.13 16:02:39: > On 2/13/06, J?nos Juh?sz wrote: > > Hi, > > > > I want to pass args to my python script on XP. > > This code > > print 'argv[0] %s' % sys.argv[0] > > print 'argv[1] %s' % sys.argv[1] > > print 'argv[2] %s' % sys.argv[2] > > > > shows this: > > argv[0] D:\devel\home\devel\python\db\xlsxml.py > > argv[1] "K:\IT\admin\test\Flat > > argv[2] Files\2006\06.02.2006-293753-gy" > Your path has a space in it (between Flat and Files). This is > probably why it is > broken as two different arguments. > Andr? > > > > > but I would see this: > > argv[0] D:\devel\home\devel\python\db\xlsxml.py > > argv[1] "K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy" > > argv[2] '' > > > > > > Yours sincerely, > > ______________________________ > > J?nos Juh?sz > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > From kenny.li at gmail.com Mon Feb 13 18:04:29 2006 From: kenny.li at gmail.com (Kenny Li) Date: Mon, 13 Feb 2006 09:04:29 -0800 Subject: [Tutor] Fwd: Instantiate a subClass using an instance of its baseClass In-Reply-To: <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> <43F06683.2060102@tds.net> <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> Message-ID: <2c48519d0602130904i44352903uf69e759f866a4708@mail.gmail.com> Kent: I forgot to mention that no coping is allowed. Your two options essentially are doing copying of the b. Furthermore, let's say, I don't even know the inside details of B, for example, I subclass the socket.socket, and I got a client socket after it accepting an incoming connection, and I want to use the newly gotten client socket to create an instance of the subClass. Following is the way normally I would do, but I don't know the abnormal case---gotten an client socket (instance of socket.socket) and trying to use it to create an instance of MySocket (subclass of socket.socket). import socket class MySocket(socket.socket): ''' my special socket ''' def __init__(self, family, sock_type): socket.socket.__init__(self, family, socket_type) self.extra="blah blah blah" Hope this help clarifying my intent. On 2/13/06, Kent Johnson wrote: > > Kenny Li wrote: > > *class B(object): * > > * ''' the baseClass '''* > > * def __init__(self, arg1, arg2):* > > * self.a1=arg1* > > * self.a2=arg2* > > * * > > *class C(B): * > > * ''' C is subClass of B '''* > > * def __init__(self, arg1, arg2):* > > * B.__init__(self, arg1, arg2)* > > * self.extra="blah blah blah"* > > ** > > *if __name__ == '__main__':* > > * # Now, I ran into a situation, where I don't have the values > > of "arg1 and arg2", * > > * # but I do have an instance of baseClass (B), called b. * > > ** > > * # How do I write the class C [for example, its > > __new__(cls...) static method] to enable me to do the following?* > > * c=C(b) # <<< This is what I want.* > > Two options: > > 1. Just pass b.a1 and b.a2 to the C constructor: > c = C(b.a1, b.a2) > > A little clumsy but it works. > > 2. Write C.__init__() to accept either form: > def __init__(self, arg1, arg2=None): > if isinstance(arg1, B): > arg1, arg2 = arg1.a1, arg1.a2 > # the rest as before > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060213/85b175be/attachment.html From smiles at worksmail.net Mon Feb 13 18:10:28 2006 From: smiles at worksmail.net (Smith) Date: Mon, 13 Feb 2006 11:10:28 -0600 Subject: [Tutor] nice() References: Message-ID: <004f01c630c0$f051e1f0$5f2c4fca@csmith> | From: Josiah Carlson | "Alan Gauld" wrote: || However I do dislike the name nice() - there is already a nice() in || the || os module with a fairly well understood function. perhaps trim(), nearly(), about(), defer_the_pain_of() :-) I've waited to think of names until after writing this. The reason for the last name option may become apparent after reading the rest of this post. || But I'm sure some || time with a thesaurus can overcome that single mild objection. :-) | | Presumably it would be located somewhere like the math module. I would like to see it as accessible as round, int, float, and repr. I really think a round-from-the-left is a nice tool to have. It's obviously very easy to build your own if you know what tools to use. Not everyone is going to be reading the python-dev or similar lists, however, and so having it handy would be nice. | From: Greg Ewing | Smith wrote: | || When teaching some programming to total newbies, a common || frustration is how to explain why a==b is False when a and b are || floats computed by different routes which ``should'' give the || same results (if arithmetic had infinite precision). | | This is just a special case of the problems inherent | in the use of floating point. As with all of these, | papering over this particular one isn't going to help | in the long run -- another one will pop up in due | course. | | Seems to me it's better to educate said newbies not | to use algorithms that require comparing floats for | equality at all. I think that having a helper function like nice() is a middle ground solution to the problem, falling short of using only decimal or rational values for numbers and doing better than requiring a test of error between floating values that should be equal but aren't because of alternate methods of computation. Just like the argument for having true division being the default behavior for the computational environment, it seems a little unfriendly to expect the more casual user to have to worry that 3*0.1 is not the same as 3/10.0. I know--they really are different, and one should (eventually) understand why, but does anyone really want the warts of floating point representation to be popping up in their work if they could be avoided, or at least easily circumvented? I know you know why the following numbers show up as not equal, but this would be an example of the pain in working with a reasonably simple exercise of, say, computing the bin boundaries for a histogram where bins are a width of 0.1: ### >>> for i in range(20): ... if (i*.1==i/10.)<>(nice(i*.1)==nice(i/10.)): ... print i,repr(i*.1),repr(i/10.),i*.1,i/10. ... 3 0.30000000000000004 0.29999999999999999 0.3 0.3 6 0.60000000000000009 0.59999999999999998 0.6 0.6 7 0.70000000000000007 0.69999999999999996 0.7 0.7 12 1.2000000000000002 1.2 1.2 1.2 14 1.4000000000000001 1.3999999999999999 1.4 1.4 17 1.7000000000000002 1.7 1.7 1.7 19 1.9000000000000001 1.8999999999999999 1.9 1.9 ### For, say, garden variety numbers that aren't full of garbage digits resulting from fp computation, the boundaries computed as 0.1*i are not going to agree with such simple numbers as 1.4 and 0.7. Would anyone (and I truly don't know the answer) really mind if all floating point values were filtered through whatever lies behind the str() manipulation of floats before the computation was made? I'm not saying that strings would be compared, but that float(str(x)) would be compared to float(str(y)) if x were being compared to y as in x<=y. If this could be done, wouldn't a lot of grief just go away and not require the use of decimal or rational types for many users? I understand that the above really is just a patch over the problem, but I'm wondering if it moves the problem far enough away that most users wouldn't have to worry about it. Here, for example, are the first values where the running sum doesn't equal the straight multiple of some step size: ### >>> def go(x,n=1000): ... s=0;i=0 ... while snice(i*x): ... return i,s,i*x,`s`,`i*x` ... >>> for i in range(1,100): ... print i, go(i/1000.) ... print ... 1 (60372 60.3719999999 60.372 60.371999999949999 60.372) 2 (49645 99.2899999999 99.29 99.289999999949998 99.290000000000006) ### The soonest the breakdown occurs is at the 22496th multiple of 0.041 for the range given above. By the time someone starts getting into needs of iterating so many times, they will be ready to use the more sophisticated option of nice()--the one which makes it more versatile and less of a patch--the option to round the answers to a given number of leading digits rather than a given decimal precision like round. nice() gives a simple way to think about making a comparison of floats. You just have to ask yourself at what "part per X" do you no longer care whether the numbers are different or not. e.g., for approximately 1 part in 100, use nice(x,2) and nice(y,2) to make the comparison between x and y. Replacing nice(*) with nice(*,6) in the go() defined above produces no discrepancy in values computed the two different ways. Since the cost of str() and '%.*e' is nearly the same, perhaps a default value of leadingDigits=9 would be a good default value, and the float(str()) option could be eliminated from nice. Isn't nice() sort of a poor-man's decimal-type without all the extra baggage? | In my opinion, if you ever find | yourself trying to do this, you're not thinking about | the problem correctly, and your algorithm is simply | wrong, even if you had infinitely precise floats. | As for real world examples of when this would be nice I will have to rely on others to justify this more heavily. Some quick examples that come to mind are: * Creating histograms of physical measurements with limited significant digits (i.e., not lots of digits from computation) * Collecting sets of points within a certain range of a given value (all points within 10% of a given value) * Stopping iterations when computed errors have fallen below a certain threshold. (For this, getting the stopping condition "right" is not so critical because doing one more iteration usually isn't a problem if an error happens to be a tiny bit larger than the required tolerance. However, the leadingDigits option on nice() allows one to even get this stopping condition right to a limited precision, something like ### tol = 1e-5 while 1: #do something and compute err if nice(err,3)<=nice(tol,3): break ### By specifying the leadingDigits value of 3, the user is saying that it's fine to quit when the err >= 0.9995. Since there is no additional cost in specifying more digits, a value of 9 could be used as well. | Ismael at tutor wrote: | How about overloading Float comparison? I'm not so adept at such things--how easy is this to do for all comparisions in a script? in an interactive session? For the latter, if it were easy, perhaps it could be part of a "newbie" mode that could be loaded. I think that some (one above has said so) would rather not have an issue pushed away, they would want to leave things as they are and just learn to work around it, not be given a hand-holding device that is eventually going to let them down anyway. I'm wondering if just having to use the function to make a comparison will be like putting your helmet on before you cycle--a reminder that there may be hazards ahead, proceed with caution. If so, then overloading the Float comparision would be better not done, requiring the "buckling" of the floats within nice(). | | If I have understood correctly, float to float comparison must be done | comparing relative errors, so that when dealing with small but rightly | represented numbers it won't tell "True" just because they're | "close". I | think your/their solution only covers the case when dealing with "big" | numbers. Think of two small numbers that you think might fail the nice test and then use the leadingDigits option (set at something like 6) and see if the problem doesn't disappear. If I understand you correctly, is this such a case: x and y defined below are truly close and nice()'s default comparison would say they are different, but nice(*,6) would say they are the same--the same to the first 6 digits of the exponential representation: ### >>> x=1.234567e-7 >>> y=1.234568e-7 >>> nice(x)==nice(y) False >>> nice(x,6)==nice(y,6) True ### | Chuck Allison wrote on edu-sig: | There is a reliable way to compute the exact number of floating-point | "intervals" (one less than the number of FP numbers) between any two | FP numbers. It is a long-ago solved problem. I have attached a C++ | version. You can't define closeness by a "distance" in a FP system - | you should use this measure instead (called "ulps" - units in the | last place). The distance between large FP numbers may always be | greater than the tolerance you prescribe. The spacing between | adjacent FP numbers at the top of the scale for IEEE double precision | numbers is 2^(972) (approx. 10^(293))! I doubt you're going to make | your tolerance this big. I don't believe newbies can grasp this, but | they can be taught to get a "feel" for floating-point number systems. | You can't write reliable FP code without this understanding. See | http://uvsc.freshsources.com/decimals.pdf. A very readable 13 page introduction to some floating point issues. Thanks for the reference. The author concludes with, "Computer science students don't need to be numerical analysts, but they may be called upon to write mathematical software. Indeed, scientists and engineers use tools like Matlab and Mathematica, but who implements these systems? It takes the expertise that only CS graduates have to write such sophisticated software. Without knowledge of the intricacies of floating-point computation, they will make a mess of things. In this paper I have surveyed the basics that every CS graduate should have mastered before they can be trusted in a workplace that does any kind of computing with real numbers." So perhaps this brings us back to the original comment that "fp issues are a learning opportunity." They are. The question I have is "how soon do they need to run into them?" Is decreasing the likelihood that they will see the problem (but not eliminate it) a good thing for the python community or not? /c From kent37 at tds.net Mon Feb 13 18:34:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Feb 2006 12:34:13 -0500 Subject: [Tutor] Instantiate a subClass using an instance of its baseClass In-Reply-To: <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> <43F06683.2060102@tds.net> <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> Message-ID: <43F0C315.4080903@tds.net> Kenny Li wrote: > Kent: > > I forgot to mention that no coping is allowed. Your two options > essentially are doing copying of the b. Not really. I make new references to the attributes of b. It sounds like you want c = C(b) to actually convert b to be an instance of C, instead of creating a new object. Is that right? You can do that it C.__new__ but I wonder why you want to? Here is some code that might do what you want: ''' Construction of a derived class from a base class returns the base class converted to an instance of the derived class ''' class B(object): ''' the baseClass ''' def __init__(self, arg1, arg2): self.a1=arg1 self.a2=arg2 def __repr__(self): return 'B(%r, %r)' % (self.a1, self.a2) class C(B): ''' C is subClass of B ''' def __new__(cls, arg1, arg2=None): if isinstance(arg1, B): # If given a B instance, convert it to a C and return it arg1.__class__ = C return arg1 return B.__new__(cls, arg1, arg2) def __init__(self, arg1, arg2=None): if not isinstance(arg1, B): B.__init__(self, arg1, arg2) self.extra="blah blah blah" def __repr__(self): return 'C(%r, %r, %r)' % (self.a1, self.a2, self.extra) b=B(1, 2) print b c=C(2, 3) print c c=C(b) print c, (c is b) print b # b is now a C - it's the same object as c Kent From carroll at tjc.com Mon Feb 13 19:40:43 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 13 Feb 2006 10:40:43 -0800 (PST) Subject: [Tutor] sys.argv In-Reply-To: Message-ID: On Mon, 13 Feb 2006, [ISO-8859-1] János Juhász wrote: > Is it any way to translate the sort DOS filename to the long NTSF one with > python ? You'll have to expand on this to handle files other than current directory, but basically: >>> win32api.FindFiles("FILEWI~1.TXT")[0][8] 'FileWithALongFileName.txt' From darinlh at gmail.com Mon Feb 13 19:42:31 2006 From: darinlh at gmail.com (Darin William Lawson Hosking) Date: Mon, 13 Feb 2006 11:42:31 -0700 Subject: [Tutor] IDE - Editors - Python In-Reply-To: <43EC6B5D.2020604@davout.org> References: <200602060946.42913.pkraus@pelsupply.com> <20060206171618.GD1767@johnsons-web.com> <7528bcdd0602061059t112f4e46l901e16c14c350a6f@mail.gmail.com> <43EC2B42.7070602@h-lab.net> <43EC6B5D.2020604@davout.org> Message-ID: <1139856152.8331.9.camel@localhost.localdomain> I have looked at several "ide's" but still haven't found a true newbie python editor mainly need code completion and maybe drop in code like a wisiwig html editor would give me. I am looking at python for basically network admin scripts. If anyone knows of one I would really appreciate a link. By the way I only use linux. Thanx in advanced Darin On Fri, 2006-02-10 at 11:30 +0100, danielle at davout.org wrote: > What about It's an Editor based on wxPython. NewEdit uses Mixin and > Plugin technique as its architecture. Most of its classes can be > extended via mixin and plugin components, and finally become an > integrity class at creating the instance. So NewEdit is very dynamic. > You can write the new features in new files, and hardly need to modify > the existing code. And if you want to extend the existing classes, you > could write mixins and plugins, and this will be bound to the target > class that I call "Slot Class". This technique will make the changes > centralized and easily managed. What are its features? ================ > * Cross platform o based on wxPython, so it can run anywhere that > wxPython works, such as: Windows, Linux. o Unicode support.......: > http://wiki.woodpecker.org.cn/moin/NewEdit?action=AttachFile&do=get&target=newedit_3.2.zip > also have windows installer: > http://wiki.woodpecker.org.cn/moin/NewEdit?action=AttachFile&do=get&target=NewEdit3.2.exe > wiki: http://wiki.woodpecker.org.cn/moin/NewEdit svn: > http://cvs.woodpecker.org.cn/svn/woodpecker/newedit maillist: > http://groups.google.com/group/NewEdit > Hugo Gonz?lez Monteverde a ?crit : > >> I'm programming under Windows and I haven't found anything better than > >> Stani's Python Editor (spe). It should be cross-platform. > >> > >> > > > > I second SPE under Windows, though under linux I keep using vim. The > > included utilities are great (I love Kiki) > > > > The only caveat would be that running wxpython programs could get you > > into trouble, as SPE itself is written in wxPython. > > > > Hugo > > _______________________________________________ > > 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 -- With A $2 Donation to Feed the Children you can now get started with Success University. all of the details are available to you immediately by visiting http://darinlh.successuniversity.com/new.asp From kenny.li at gmail.com Mon Feb 13 20:02:17 2006 From: kenny.li at gmail.com (Kenny Li) Date: Mon, 13 Feb 2006 11:02:17 -0800 Subject: [Tutor] Fwd: Instantiate a subClass using an instance of its baseClass In-Reply-To: <2c48519d0602131100r5a2fa82aj8d0dddee1a08d39f@mail.gmail.com> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> <43F06683.2060102@tds.net> <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> <43F0C315.4080903@tds.net> <2c48519d0602131100r5a2fa82aj8d0dddee1a08d39f@mail.gmail.com> Message-ID: <2c48519d0602131102m4dfa79abx71dcb8a2c2777766@mail.gmail.com> Sorry, keep forgetting "reply-all" ---------- Forwarded message ---------- From: Kenny Li Date: Feb 13, 2006 11:00 AM Subject: Re: [Tutor] Instantiate a subClass using an instance of its baseClass To: Kent Johnson Yep! I think that is what I want. I did not know enough to do (inside C.__init__() ): arg1.__class__=C As to my intent, I want to subclass socket.socket. By doing so, I may get a socket (instance of my baseClass) after it (my subclass) accepts an incoming connection, and I want to use the subclass instance (the client socket) to get an instance of my subclass. Do you think your solution would work in my socket.socket subclassing case? (I will give it a try to verify, just asking before I even try) Again, Thanks a lot, Kent! PS: there is information about __new__(), but there seems not a lot about __class__, could you point me to some web sources about __class__? On 2/13/06, Kent Johnson wrote: > > Kenny Li wrote: > > Kent: > > > > I forgot to mention that no coping is allowed. Your two options > > essentially are doing copying of the b. > > Not really. I make new references to the attributes of b. > > It sounds like you want > c = C(b) > to actually convert b to be an instance of C, instead of creating a new > object. Is that right? You can do that it C.__new__ but I wonder why you > want to? > > Here is some code that might do what you want: > > ''' Construction of a derived class from a base class returns the base > class > converted to an instance of the derived class ''' > > class B(object): > ''' the baseClass ''' > def __init__(self, arg1, arg2): > self.a1=arg1 > self.a2=arg2 > > def __repr__(self): > return 'B(%r, %r)' % (self.a1, self.a2) > > class C(B): > ''' C is subClass of B ''' > def __new__(cls, arg1, arg2=None): > if isinstance(arg1, B): > # If given a B instance, convert it to a C and return it > arg1.__class__ = C > return arg1 > > return B.__new__(cls, arg1, arg2) > > def __init__(self, arg1, arg2=None): > if not isinstance(arg1, B): > B.__init__(self, arg1, arg2) > self.extra="blah blah blah" > > def __repr__(self): > return 'C(%r, %r, %r)' % (self.a1, self.a2, self.extra) > > > b=B(1, 2) > print b > > c=C(2, 3) > print c > > c=C(b) > print c, (c is b) > print b # b is now a C - it's the same object as c > > > Kent > > _______________________________________________ > 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/20060213/ac4816f1/attachment.html From kent37 at tds.net Mon Feb 13 20:17:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Feb 2006 14:17:15 -0500 Subject: [Tutor] Instantiate a subClass using an instance of its baseClass In-Reply-To: <2c48519d0602131100r5a2fa82aj8d0dddee1a08d39f@mail.gmail.com> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> <43F06683.2060102@tds.net> <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> <43F0C315.4080903@tds.net> <2c48519d0602131100r5a2fa82aj8d0dddee1a08d39f@mail.gmail.com> Message-ID: <43F0DB3B.7040702@tds.net> Kenny Li wrote: > Yep! I think that is what I want. I did not know enough to do (inside > C.__init__() ): > arg1.__class__=C > > As to my intent, I want to subclass socket.socket. By doing so, I may > get a socket (instance of my baseClass) after it (my subclass) accepts > an incoming connection, and I want to use the subclass instance (the > client socket) to get an instance of my subclass. > > Do you think your solution would work in my socket.socket subclassing > case? (I will give it a try to verify, just asking before I even try) I think so :-) unless some socket code is looking at the actual class of the socket. But why not just override socket.accept() to do what you want? Here is the full def of socket.accept(): def accept(self): sock, addr = self._sock.accept() return _socketobject(_sock=sock), addr Just change it to def accept(self): sock, addr = self._sock.accept() return MySocket(_sock=sock), addr > Again, Thanks a lot, Kent! > > PS: there is information about __new__(), but there seems not a lot > about __class__, could you point me to some web sources about __class__? Google "site:docs.python.org __class__" and especially http://docs.python.org/dev/lib/specialattrs.html Kent From kenny.li at gmail.com Mon Feb 13 21:02:35 2006 From: kenny.li at gmail.com (Kenny Li) Date: Mon, 13 Feb 2006 12:02:35 -0800 Subject: [Tutor] Instantiate a subClass using an instance of its baseClass In-Reply-To: <43F0DB3B.7040702@tds.net> References: <2c48519d0602122338o7c15e570xfc116120fa46c886@mail.gmail.com> <43F06683.2060102@tds.net> <2c48519d0602130903h45417a50m7e06fbc956f79d6d@mail.gmail.com> <43F0C315.4080903@tds.net> <2c48519d0602131100r5a2fa82aj8d0dddee1a08d39f@mail.gmail.com> <43F0DB3B.7040702@tds.net> Message-ID: <2c48519d0602131202u978a114hb217b4fc6de45d73@mail.gmail.com> Kent: Overriding the accept() is an excellent idea. It looks more elegant than my original thinking of "total" subclassing. Thanks a lot; I have learned a great deal from you. Kenny On 2/13/06, Kent Johnson wrote: > > Kenny Li wrote: > > Yep! I think that is what I want. I did not know enough to do (inside > > C.__init__() ): > > arg1.__class__=C > > > > As to my intent, I want to subclass socket.socket. By doing so, I may > > get a socket (instance of my baseClass) after it (my subclass) accepts > > an incoming connection, and I want to use the subclass instance (the > > client socket) to get an instance of my subclass. > > > > Do you think your solution would work in my socket.socket subclassing > > case? (I will give it a try to verify, just asking before I even try) > > I think so :-) unless some socket code is looking at the actual class of > the socket. > > But why not just override socket.accept() to do what you want? Here is > the full def of socket.accept(): > > def accept(self): > sock, addr = self._sock.accept() > return _socketobject(_sock=sock), addr > > Just change it to > > def accept(self): > sock, addr = self._sock.accept() > return MySocket(_sock=sock), addr > > > Again, Thanks a lot, Kent! > > > > PS: there is information about __new__(), but there seems not a lot > > about __class__, could you point me to some web sources about __class__? > > Google "site:docs.python.org __class__" and especially > http://docs.python.org/dev/lib/specialattrs.html > > Kent > > _______________________________________________ > 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/20060213/61e69c2e/attachment.html From chuck at freshsources.com Mon Feb 13 05:20:17 2006 From: chuck at freshsources.com (Chuck Allison) Date: Sun, 12 Feb 2006 21:20:17 -0700 Subject: [Tutor] [Edu-sig] nice() In-Reply-To: <038701c63004$733603c0$132c4fca@csmith> References: <038701c63004$733603c0$132c4fca@csmith> Message-ID: <113575776.20060212212017@freshsources.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060212/e19c43f5/attachment.html -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ulps.h Url: http://mail.python.org/pipermail/tutor/attachments/20060212/e19c43f5/attachment.pot -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: prog1.cpp Url: http://mail.python.org/pipermail/tutor/attachments/20060212/e19c43f5/attachment.asc From faq at lanl.gov Mon Feb 13 18:01:16 2006 From: faq at lanl.gov (Francesco A. Queirolo) Date: Mon, 13 Feb 2006 10:01:16 -0700 (MST) Subject: [Tutor] Interpackage access help-Please disregard other post with same name Message-ID: <2954.128.165.81.147.1139850076.squirrel@webmail.lanl.gov> Sorry about the double post but the first one was sent before I was completed with my question. I have the following directory structure on Windows XP running python 2.4.2 final: JavaInheritancePoly\ HierarchicalInheritancePoly.py Animals\ __init__.py Modules\ __init__.py Animal.py Test\ __init__.py AnimalTest.py When in AnimalTest.py I would like to access animal. I have tried: from JavaInheritancePoly.Animals.Modules import Animal and receive this error from the interpreter window: Traceback (most recent call last): File "", line 11, in ? ImportError: No module named JavaInheritancePoly.Animals.Modules Line 11 is of course the import statement. I am able to access Animal.py from HierarchicalInheritancePoly.py through either: from Animals.Modules import Animal OR import Animals.Modules.Animal I think it is some sort of problem with my path or sys.path but I am not totally sure what is going on. Thank you, Francesco -- Francesco Queirolo Safeguards Systems Group(N-4) Los Alamos National Laboratory TA 35-2 A156 +1 505 606 1960 faq at lanl.gov From kent37 at tds.net Mon Feb 13 21:42:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Feb 2006 15:42:59 -0500 Subject: [Tutor] Interpackage access help-Please disregard other post with same name In-Reply-To: <2954.128.165.81.147.1139850076.squirrel@webmail.lanl.gov> References: <2954.128.165.81.147.1139850076.squirrel@webmail.lanl.gov> Message-ID: <43F0EF53.1000702@tds.net> Francesco A. Queirolo wrote: > Sorry about the double post but the first one was sent before I was > completed with my question. > > I have the following directory structure on Windows XP running python > 2.4.2 final: > > JavaInheritancePoly\ > HierarchicalInheritancePoly.py > Animals\ > __init__.py > Modules\ > __init__.py > Animal.py > Test\ > __init__.py > AnimalTest.py > > When in AnimalTest.py I would like to access animal. I have tried: > > from JavaInheritancePoly.Animals.Modules import Animal For the above to work you need __init__.py in JavaInheritancePoly\ and the dir containing JavaInheritancePoly\ must be in sys.path either because it is in the working directory or some other means. Kent From eli.usmc.recon at gmail.com Tue Feb 14 07:00:10 2006 From: eli.usmc.recon at gmail.com (Eli Zabielski) Date: Mon, 13 Feb 2006 23:00:10 -0700 Subject: [Tutor] unknown error in simple program Message-ID: <3cc822320602132200o4b777c67h91c530319cc9647c@mail.gmail.com> I am reading "Python Programming for the absolute beginner" and am on chapter 4 challenges. It says to create a program to let the player guess letters of the word (I haven't tried to incorporate a guess limit yet like it says) my program looks fine to me, but I get a fat juicy error when I run it My program: # Guess My Word # Players pick letters in a random secret word # Eli Zabielski-2/13/06 import random print "Hello, I will give you 5 chances to guess letters of one of my secret words.\n On the final chance, you must guess the word" WORDS = ("python", "jumble", "difficult", "answer", "xylophone", "recon", "recordable") word=random.choice(WORDS) print "The word is", len(word), "letters long." guess=input("guess one letter") tried_good=() tried_bad=() guess_count=0 while guess not in word: guess_count+=1 guess+=tried_bad print "Nope, try again\n" print "Bad tries",tried_bad guess=input("\nguess one letter") if guess_count==4: "You have to guess the word now" guess_word=input("What say you") guess_word=guess_word.lower() while guess in word: print "Good, you got one" guess+=tried_good print "Bad tries",tried_bad print "Good tries", tried_good guess=input("\nguess one letter") if guess_count==4: "You have to guess the word now" guess_word=input("What say you") guess_word=guess_word.lower() if guess_word==word: print "Good, you got it!" elif guess_word != word: print "Aww, thats too bad, the word is mine forever" exit=input("Press enter to exit.") And I get: (No matter what letter I guess) Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Eli\Desktop\Games\Applications\Programs\Guess the word\Guess the word 1.0.py", line 10, in ? guess=input("guess one letter") File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\app.py", line 372, in Win32Input return eval(raw_input(prompt)) File "", line 0, in ? NameError: name 'e' is not defined >>> I have been attempting to find the problem for 2 hours now and try to solve it on my own, but I can't do it this time. Thanks for the help -- Eli Zabielski -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060213/027eebef/attachment.html -------------- next part -------------- # Guess My Word # Players pick letters in a random secret word # Eli Zabielski-2/13/06 import random print "Hello, I will give you 5 chances to guess letters of one of my secret words.\n On the final chance, you must guess the word" WORDS = ("python", "jumble", "difficult", "answer", "xylophone", "recon", "recordable") word=random.choice(WORDS) print "The word is", len(word), "letters long." guess=input("guess one letter") tried_good=() tried_bad=() guess_count=0 while guess not in word: guess_count+=1 guess+=tried_bad print "Nope, try again\n" print "Bad tries",tried_bad guess=input("\nguess one letter") if guess_count==4: "You have to guess the word now" guess_word=input("What say you") guess_word=guess_word.lower() while guess in word: print "Good, you got one" guess+=tried_good print "Bad tries",tried_bad print "Good tries", tried_good guess=input("\nguess one letter") if guess_count==4: "You have to guess the word now" guess_word=input("What say you") guess_word=guess_word.lower() if guess_word==word: print "Good, you got it!" elif guess_word != word: print "Aww, thats too bad, the word is mine forever" exit=input("Press enter to exit.") From ewald.ertl at hartter.com Tue Feb 14 08:28:25 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue, 14 Feb 2006 08:28:25 +0100 Subject: [Tutor] unknown error in simple program In-Reply-To: <3cc822320602132200o4b777c67h91c530319cc9647c@mail.gmail.com> References: <3cc822320602132200o4b777c67h91c530319cc9647c@mail.gmail.com> Message-ID: <43F18699.5000509@hartter.com> Hi Eli! You have a lot of calls to input() in your code. When requesting help on input you get the following output: >>> help(input) Help on built-in function input: input(...) input([prompt]) -> value Equivalent to eval(raw_input(prompt)). As you can see, the data you input is put as argument to eval, which tries to interpret the input as Python-source code. What you intended is a raw_input(). This reads the data from standard input and returns it to you. HTH Ewald Eli Zabielski wrote: > I am reading "Python Programming for the absolute beginner" and am on > chapter 4 challenges. > It says to create a program to let the player guess letters of the word > (I haven't tried to incorporate a guess limit yet like it says) > my program looks fine to me, but I get a fat juicy error when I run it > > My program: > > # Guess My Word > # Players pick letters in a random secret word > # Eli Zabielski-2/13/06 > import random > print "Hello, I will give you 5 chances to guess letters of one of my > secret words.\n On the final chance, you must guess the word" > WORDS = ("python", "jumble", "difficult", "answer", "xylophone", > "recon", "recordable") > word=random.choice(WORDS) > print "The word is", len(word), "letters long." > guess=input("guess one letter") > tried_good=() > tried_bad=() > guess_count=0 > while guess not in word: > guess_count+=1 > guess+=tried_bad > print "Nope, try again\n" > print "Bad tries",tried_bad > guess=input("\nguess one letter") > if guess_count==4: > "You have to guess the word now" > guess_word=input("What say you") > guess_word=guess_word.lower() > while guess in word: > print "Good, you got one" > guess+=tried_good > print "Bad tries",tried_bad > print "Good tries", tried_good > guess=input("\nguess one letter") > if guess_count==4: > "You have to guess the word now" > guess_word=input("What say you") > guess_word=guess_word.lower() > if guess_word==word: > print "Good, you got it!" > elif guess_word != word: > print "Aww, thats too bad, the word is mine forever" > exit=input("Press enter to exit.") > > > > And I get: (No matter what letter I guess) > > Traceback (most recent call last): > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Documents and > Settings\Eli\Desktop\Games\Applications\Programs\Guess the word\Guess > the word 1.0.py ", line 10, in ? > guess=input("guess one letter") > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\app.py", > line 372, in Win32Input > return eval(raw_input(prompt)) > File "", line 0, in ? > NameError: name 'e' is not defined >>>> > > I have been attempting to find the problem for 2 hours now and try to > solve it on my own, but I can't do it this time. > > Thanks for the help > > -- > Eli Zabielski > > From m.haft at abdn.ac.uk Tue Feb 14 16:15:54 2006 From: m.haft at abdn.ac.uk (Michael Haft) Date: Tue, 14 Feb 2006 15:15:54 +0000 Subject: [Tutor] lists Message-ID: <5.2.1.1.0.20060214151134.00bd0540@mailms.abdn.ac.uk> Hello, I have a list of 15 str values called p, when I try the following code: for x in p: p[x] = float(p[x])/10 print p I get: Traceback (most recent call last): File "C:/Python24/CRU_2_Century code/CRU_2_DNDC.py", line 62, in -toplevel- p[x] = float(p[x])/10 TypeError: list indices must be integers If it helps p=['1900', '51.50', '11.50', '15.30', '11.80', '5.00', '17.40', '25.30', '7.90', '1.00', '2.20', '12.10', '26.00', '10.00', '8.80'] I'm confused because if I try it without the for loop, i.e.: x = 3 p[x] = float(p[x])/10 print p It works just fine, I assume it doesn't like me floating the value but why does it work out of the loop but not in the loop? Cheers Mike ------------ Michael Haft School of Biological Sciences Plant & Soil Science Cruickshank Building St.Machar Drive Aberdeen AB24 3UU E-mail: m.haft at abdn.ac.uk From kent37 at tds.net Tue Feb 14 16:34:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Feb 2006 10:34:27 -0500 Subject: [Tutor] lists In-Reply-To: <5.2.1.1.0.20060214151134.00bd0540@mailms.abdn.ac.uk> References: <5.2.1.1.0.20060214151134.00bd0540@mailms.abdn.ac.uk> Message-ID: <43F1F883.1020706@tds.net> Michael Haft wrote: > > > Hello, > I have a list of 15 str values called p, when I try the following code: > > for x in p: > p[x] = float(p[x])/10 > print p The problem is that iterating a list yields the actual values in the list, not the indices to the list: >>> p = ['1900', '51.50', '11.50'] >>> for x in p: ... print x ... 1900 51.50 11.50 The above are string values though you can't tell from the print. Indexing p by a string gives the error you saw: >>> p['1900'] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers One way to do what you want is to change the loop to iterate over indices of p rather than elements of p: >>> for i in range(len(p)): ... p[i] = float(p[i])/10 ... >>> print p [190.0, 5.1500000000000004, 1.1499999999999999] That works but it's not very Pythonic - there are better ways. For example the enumerate funcion yields pairs of (index, value) for each value in a list. It is handy when you need both the index and the value, as you do here: >>> p = ['1900', '51.50', '11.50'] >>> for i, x in enumerate(p): ... p[i] = float(x)/10 ... >>> p [190.0, 5.1500000000000004, 1.1499999999999999] But even better is to use a list comprehension. This is a very useful Python construct that lets you build a new list from an existing list with a very elegant syntax: >>> p = ['1900', '51.50', '11.50'] >>> p = [ float(x)/10 for x in p] >>> p [190.0, 5.1500000000000004, 1.1499999999999999] Kent From ds-python-tutor at sidorof.com Tue Feb 14 19:14:25 2006 From: ds-python-tutor at sidorof.com (DS) Date: Tue, 14 Feb 2006 10:14:25 -0800 Subject: [Tutor] exec, execfile, rexec Message-ID: <43F21E01.9060708@sidorof.com> I have been writing a web-based application in which users would be able to input expressions which would be evaluated on the server. I had read about the dangers of using eval for such things, and so I parse the expressions myself, and calculate the expressions using my own code. This wasn't too bad, because that gave me a chance to learn about parsing expressions, AST, and other aspects of coding that I wasn't particularly familiar with. If that was all I needed to do, my code seems adequate for this purpose. Now, I've been starting to think about adding multiline expressions, or really, at this point, programs. I don't think it would be all that bad to implement some simple structure for doing that, but I can't help but think that it would make more sense to simply use Python directly. Not only is it already implemented, but I certainly like to use it, and it might promote the use of Python just a bit more. Is this simply such a bad idea that I should not even consider it? Is there a way that I can limit usage by filtering all programs for operating system calls, certain imports, maybe not allowing lambdas? I would hate to get compromised in some way that I don't understand. Thanks for any guidance. ds From kent37 at tds.net Tue Feb 14 19:44:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Feb 2006 13:44:50 -0500 Subject: [Tutor] exec, execfile, rexec In-Reply-To: <43F21E01.9060708@sidorof.com> References: <43F21E01.9060708@sidorof.com> Message-ID: <43F22522.1040009@tds.net> DS wrote: > I have been writing a web-based application in which users would be able > to input expressions which would be evaluated on the server. I had read > about the dangers of using eval for such things, and so I parse the > expressions myself, and calculate the expressions using my own code. > This wasn't too bad, because that gave me a chance to learn about > parsing expressions, AST, and other aspects of coding that I wasn't > particularly familiar with. If that was all I needed to do, my code > seems adequate for this purpose. > > Now, I've been starting to think about adding multiline expressions, or > really, at this point, programs. I don't think it would be all that bad > to implement some simple structure for doing that, but I can't help but > think that it would make more sense to simply use Python directly. Not > only is it already implemented, but I certainly like to use it, and it > might promote the use of Python just a bit more. > > Is this simply such a bad idea that I should not even consider it? Is > there a way that I can limit usage by filtering all programs for > operating system calls, certain imports, maybe not allowing lambdas? I > would hate to get compromised in some way that I don't understand. It is very challenging to even come close to safety. If you search comp.lang.python for eval or exec you will find many discussions of this. For example http://groups.google.com/group/comp.lang.python/browse_frm/thread/cf6093c5551a6587/23ddf23a6dfc3e11?q=eval&rnum=1#23ddf23a6dfc3e11 One approach is to use the compiler module to parse the input data and write a custom visitor for the parse tree that only allows 'safe' parse elements to be processed. There is some discussion here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5f4d7e2c397c2ca/5d1af7f9c7b1789b?q=python+compiler+safe+eval&rnum=1#5d1af7f9c7b1789b There is also a hack that provides an empty __builtin__ namespace to eval which prevents at least naive attempts at hacking. Bottom line - it's a very hard problem which I don't think anyone has solved to the satisfaction of all observers, though there are limited solutions which some people find acceptable. Kent From carroll at tjc.com Tue Feb 14 21:15:46 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 14 Feb 2006 12:15:46 -0800 (PST) Subject: [Tutor] exec, execfile, rexec In-Reply-To: <43F22522.1040009@tds.net> Message-ID: On Tue, 14 Feb 2006, Kent Johnson wrote: > Bottom line - it's a very hard problem which I don't think anyone has > solved to the satisfaction of all observers, though there are limited > solutions which some people find acceptable. I think it's telling that the restricted execution modules, rexex and Bastion, became disabled as of python 2.3; that gives an indication of how difficult a problem it is to fix. http://www.python.org/doc/lib/restricted.html From pkraus at pelsupply.com Tue Feb 14 21:16:57 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 14 Feb 2006 15:16:57 -0500 Subject: [Tutor] Build Python 2.4 SCO OpenServer 5 Message-ID: <200602141516.57755.pkraus@pelsupply.com> Everything configures fine but when I build it dies here... (If this is not the right place for this please point me to where I should be posting.) gcc -Wl,-Bexport -o python \ Modules/python.o \ libpython2.4.a -lsocket -lnsl -ldl -lpthread -lm case $MAKEFLAGS in \ *-s*) CC='gcc' LDSHARED='gcc -Wl,-G,-Bexport' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes -m486 -DSCO5' ./python -E ./setup.py -q build;; \ *) CC='gcc' LDSHARED='gcc -Wl,-G,-Bexport' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes -m486 -DSCO5' ./python -E ./setup.py build;; \ esac /bin/sh: 9056 Memory fault - core dumped make: *** [sharedmods] Error 139 -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From dyoo at hkn.eecs.berkeley.edu Tue Feb 14 21:30:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Feb 2006 12:30:52 -0800 (PST) Subject: [Tutor] Build Python 2.4 SCO OpenServer 5 In-Reply-To: <200602141516.57755.pkraus@pelsupply.com> Message-ID: On Tue, 14 Feb 2006, Paul Kraus wrote: > Everything configures fine but when I build it dies here... > (If this is not the right place for this please point me to where I should be > posting.) Hi Paul, Try the comp.lang.python newsgroup; this installation question seems very specialized, and SCO is somewhat of a marginalized platform for newcomers; very few of us here on Tutor can give much helpful advice on this topic. The only SCO-specific material I see so far in the README is: """ SCO: The following apply to SCO 3 only; Python builds out of the box on SCO 5 (or so we've heard). 1) Everything works much better if you add -U__STDC__ to the defs. This is because all the SCO header files are broken. Anything that isn't mentioned in the C standard is conditionally excluded when __STDC__ is defined. 2) Due to the U.S. export restrictions, SCO broke the crypt stuff out into a separate library, libcrypt_i.a so the LIBS needed be set to: LIBS=' -lsocket -lcrypt_i' """ But there's no mention of an anticipated memory core dump during the build. The folks at comp.lang.python will be better equipped to help you diagnose your problem. Good luck! From mbroe at columbus.rr.com Tue Feb 14 21:39:27 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 14 Feb 2006 15:39:27 -0500 Subject: [Tutor] map vs. list comprehension Message-ID: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> I read somewhere that the function 'map' might one day be deprecated in favor of list comprehensions. But I can't see a way to do this in a list comprehension: >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) [2, 4, 8, 16] Is there a way? Cheers, Mike From andre.roberge at gmail.com Tue Feb 14 21:46:43 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 14 Feb 2006 16:46:43 -0400 Subject: [Tutor] map vs. list comprehension In-Reply-To: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> References: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> Message-ID: <7528bcdd0602141246i1410673j8fc1cf03bea251fc@mail.gmail.com> On 2/14/06, Michael Broe wrote: > I read somewhere that the function 'map' might one day be deprecated > in favor of list comprehensions. > > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] >>> [2**i for i in [1, 2, 3, 4]] [2, 4, 8, 16] Andr? > > Is there a way? > > Cheers, > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jason.massey at gmail.com Tue Feb 14 21:46:53 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 14 Feb 2006 14:46:53 -0600 Subject: [Tutor] map vs. list comprehension In-Reply-To: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> References: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> Message-ID: <7e3eab2c0602141246h4ab20bf0m6b0d7978181bd7e0@mail.gmail.com> How about: >>> [pow(2,x) for x in [1,2,3,4]] [2, 4, 8, 16] On 2/14/06, Michael Broe wrote: > > I read somewhere that the function 'map' might one day be deprecated > in favor of list comprehensions. > > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] > > Is there a way? > > Cheers, > Mike > _______________________________________________ > 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/20060214/c1456e6e/attachment.htm From kent37 at tds.net Tue Feb 14 21:55:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Feb 2006 15:55:50 -0500 Subject: [Tutor] map vs. list comprehension In-Reply-To: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> References: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> Message-ID: <43F243D6.1050003@tds.net> Michael Broe wrote: > I read somewhere that the function 'map' might one day be deprecated > in favor of list comprehensions. > > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] > > Is there a way? The current plan is to drop map() in Python 3.0 which is a "hypothetical future release of Python". http://www.python.org/peps/pep-3000.html List comps aren't so handy as a replacement for map() with a function of more than one argument. You have to use zip() to convert the separate arg lists to a single list of arg tuples: >>> [ pow(x, y) for x, y in zip([2, 2, 2, 2], [1, 2, 3, 4]) ] [2, 4, 8, 16] or if you prefer >>> [pow(*args) for args in zip([2, 2, 2, 2], [1, 2, 3, 4])] [2, 4, 8, 16] Kent From mbroe at columbus.rr.com Tue Feb 14 21:57:25 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 14 Feb 2006 15:57:25 -0500 Subject: [Tutor] map vs. list comprehension In-Reply-To: <7528bcdd0602141246i1410673j8fc1cf03bea251fc@mail.gmail.com> References: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> <7528bcdd0602141246i1410673j8fc1cf03bea251fc@mail.gmail.com> Message-ID: On Feb 14, 2006, at 3:46 PM, Andre Roberge wrote: > [2**i for i in [1, 2, 3, 4]] Ah yes, I'm sorry, I was thinking of the most general case, where the arguments are two arbitrary lists. My example was too specific. Is there a way to do something like the following in a list comprehension? map(pow, [1, 7, 6, 2], [3, 8, 2, 5]) Mike From ds-python-tutor at sidorof.com Tue Feb 14 22:21:22 2006 From: ds-python-tutor at sidorof.com (DS) Date: Tue, 14 Feb 2006 13:21:22 -0800 Subject: [Tutor] exec, execfile, rexec In-Reply-To: <43F22522.1040009@tds.net> References: <43F21E01.9060708@sidorof.com> <43F22522.1040009@tds.net> Message-ID: <43F249D2.8060707@sidorof.com> Kent Johnson wrote: >It is very challenging to even come close to safety. If you search >comp.lang.python for eval or exec you will find many discussions of >this. For example >http://groups.google.com/group/comp.lang.python/browse_frm/thread/cf6093c5551a6587/23ddf23a6dfc3e11?q=eval&rnum=1#23ddf23a6dfc3e11 > >One approach is to use the compiler module to parse the input data and >write a custom visitor for the parse tree that only allows 'safe' parse >elements to be processed. There is some discussion here: >http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5f4d7e2c397c2ca/5d1af7f9c7b1789b?q=python+compiler+safe+eval&rnum=1#5d1af7f9c7b1789b > > > Thanks for the references. I played with the parse tree yesterday a little bit, for which I now have a little bit more understanding, since I implemented my own extremely primitive version. It had seemed like I ought to be able to take advantage of it, if I had an adequate stop list. >There is also a hack that provides an empty __builtin__ namespace to >eval which prevents at least naive attempts at hacking. > >Bottom line - it's a very hard problem which I don't think anyone has >solved to the satisfaction of all observers, though there are limited >solutions which some people find acceptable. > > > Terry Carroll wrote: >On Tue, 14 Feb 2006, Kent Johnson wrote: > > > >>Bottom line - it's a very hard problem which I don't think anyone has >>solved to the satisfaction of all observers, though there are limited >>solutions which some people find acceptable. >> >> > >I think it's telling that the restricted execution modules, rexex and >Bastion, became disabled as of python 2.3; that gives an indication of how >difficult a problem it is to fix. > >http://www.python.org/doc/lib/restricted.html > > > I hate to admit it, but there are times when fear should be listened to, and I think this is one of them. So, I guess I'll move on to parsing it myself. Seems a shame though. ds From john.corry at ntlworld.com Tue Feb 14 22:48:25 2006 From: john.corry at ntlworld.com (John Corry) Date: Tue, 14 Feb 2006 21:48:25 -0000 Subject: [Tutor] Gadfly Database Problems Message-ID: Hi, I have a python program that accesses glade and a gadfly database. The program works fine on my computer but I want to compile it so that I can put it on other computers without having to install everything that my computer has. I have had a go at compiling it using py2exe. I have used the standard setup.py from the example. I have listed the glade file and my two database files as my data_files. The compiler runs and I get the dist + build folders. When I double click the exe, the program loads and runs ok. When I get to the point of the program where the program accesses the database, the program freezes. The error log message says: Traceback (most recent call last): File "shopcard.py", line 188, in callback4 File "shopcard.py", line 228, in calc File "gadfly\dbapi20.pyo", line 26, in connect File "gadfly\dbapi20.pyo", line 46, in __init__ File "gadfly\database.pyo", line 27, in __init__ File "gadfly\sql.pyo", line 16, in getSQL ImportError: Couldn't find sql_mar.py - has setup.py been run? Callback4 is a function which calls the calc function. The calc function tries to connect to the database files. I can see the database files in the dist folder. Are there other files which I have to manually copy into the dist folder such as the sql_mar.py? Any help or pointers would be greatly appreciated. I know that this is a py2exe specific question but I have already e-mailed that list and have had no reply. Thanks, John. From dyoo at hkn.eecs.berkeley.edu Tue Feb 14 22:59:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Feb 2006 13:59:35 -0800 (PST) Subject: [Tutor] exec, execfile, rexec In-Reply-To: <43F249D2.8060707@sidorof.com> Message-ID: > I hate to admit it, but there are times when fear should be listened to, > and I think this is one of them. So, I guess I'll move on to parsing it > myself. Seems a shame though. Hi DS, Yeah, I'd recommend listening to fear. *grin* Python's a powerful language, and I'd recommend erring on the side of caution here. By the way, if you have a lot of time on your hands and are of a CS bent, you might find the following PDF book interesting: http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ From dyoo at hkn.eecs.berkeley.edu Tue Feb 14 23:10:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Feb 2006 14:10:03 -0800 (PST) Subject: [Tutor] map vs. list comprehension In-Reply-To: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> Message-ID: > I read somewhere that the function 'map' might one day be deprecated in > favor of list comprehensions. > > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] Hi Michael, If my hands were forcibly tied to avoid map(), I'd try something like: ######################################################## [pow(base, exponent) for (base, exponent) in zip([2, 2, 2, 2], [1, 2, 3, 4])] ########################################################## But even if map() no longer stays as a builtin, we can always get it back: ###### >>> def mymap(f, *args): ... return [f(*elts) for elts in zip(*args)] ... >>> def square(x): ... return x*x ... >>> mymap(square, range(20)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361] ###### (You might notice that mymap() looks very analogous to what we've done in the pow() list comprehension above.) So I would not be too concerned about what happens in Python 3000: if things change, we can route around damage. Best of wishes to you! From ms at cerenity.org Tue Feb 14 23:00:16 2006 From: ms at cerenity.org (Michael Sparks) Date: Tue, 14 Feb 2006 22:00:16 +0000 Subject: [Tutor] map vs. list comprehension In-Reply-To: References: <552FEFC4-5417-4056-8504-9198EA4DA25A@columbus.rr.com> <7528bcdd0602141246i1410673j8fc1cf03bea251fc@mail.gmail.com> Message-ID: <200602142200.17005.ms@cerenity.org> On Tuesday 14 February 2006 20:57, Michael Broe wrote: ... > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] >>> [ x**y for x,y in zip([2,2,2,2],[1,2,3,4]) ] [2, 4, 8, 16] To me this is clearer. (despite having written some substantial amount of code in SML - a functional language where higher order functions are common) Why ? Because it's easier to mentally break down into its parts for someone less familiar with tools like map. >>> zip([2,2,2,2],[1,2,3,4]) [(2, 1), (2, 2), (2, 3), (2, 4)] >>> [ x**y for x,y in [(2, 1), (2, 2), (2, 3), (2, 4)] ] [2, 4, 8, 16] > Is there a way to do something like the following in a list > comprehension? > > map(pow, [1, 7, 6, 2], [3, 8, 2, 5]) >>> [ x**y for x,y in zip([1,7,6,2],[3,8,2,5]) ] [1, 5764801, 36, 32] Regards, Michael. From ds-python-tutor at sidorof.com Wed Feb 15 00:37:26 2006 From: ds-python-tutor at sidorof.com (DS) Date: Tue, 14 Feb 2006 15:37:26 -0800 Subject: [Tutor] exec, execfile, rexec In-Reply-To: References: Message-ID: <43F269B6.1010707@sidorof.com> Danny Yoo wrote: >>I hate to admit it, but there are times when fear should be listened to, >>and I think this is one of them. So, I guess I'll move on to parsing it >>myself. Seems a shame though. >> >> > >Hi DS, > >Yeah, I'd recommend listening to fear. *grin* Python's a powerful >language, and I'd recommend erring on the side of caution here. > > >By the way, if you have a lot of time on your hands and are of a CS bent, >you might find the following PDF book interesting: > > http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ > > > Thanks, I'm downloading it now. Not sure about the "lot of time my hands" part, but I'll try to learning something from it. Thanks ds From oztriking at hotmail.com Wed Feb 15 12:05:39 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 15 Feb 2006 22:05:39 +1100 Subject: [Tutor] G'day Message-ID: G'day, I'm new to Python and new to the list and just thought I'd say a quick hello before asking my 1st dumb question. My name is John and I live in Australia, I've been using computers since about 1983. I haven't done any programming since the commodore 64 basic days, I was fairly proficient with basic so I'm hoping I can pick up python without too much grief. I'm running Fedora Core 4 and using Python 2.4.1. My 1st dumb question: I have a copy of Teach Yourself Python in 24 Hours, printed in 2000 so I guess it's virtually usless but i was hoping to learn some of the basics from it. There is a small bit of code near the beginning... print "Hello, World!"print ' 'Goodbye, World!" which returns a syntax error for the 2nd line. I thought it was a typo and changed it to print "Goodbye, World!". This would be fine except further on the book there is similar syntax in some of the longer scripts. My guess is that syntax was ok for an older version of Python that book was written for. I would like to know what the correct code should be. John _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060215/b4e0f184/attachment.htm From klappnase at freenet.de Wed Feb 15 13:42:43 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 15 Feb 2006 13:42:43 +0100 Subject: [Tutor] G'day In-Reply-To: References: Message-ID: <20060215134243.57f521ea.klappnase@freenet.de> On Wed, 15 Feb 2006 22:05:39 +1100 "John Connors" wrote: > G'day, I'm new to Python and new to the list and just thought I'd say a quick hello before asking my 1st dumb question. My name is John and I live in Australia, I've been using computers since about 1983. I haven't done any programming since the commodore 64 basic days, I was fairly proficient with basic so I'm hoping I can pick up python without too much grief. I'm running Fedora Core 4 and using Python 2.4.1. My 1st dumb question: I have a copy of Teach Yourself Python in 24 Hours, printed in 2000 so I guess it's virtually usless but i was hoping to learn some of the basics from it. There is a small bit of code near the beginning... print "Hello, World!"print ' 'Goodbye, World!" which returns a syntax error for the 2nd line. I thought it was a typo and changed it to print "Goodbye, World!". This would be fine except further on the book there is similar syntax in some of the longer scripts. My guess is that syntax was ok for an older version of Python that book was written for. I would like to know what the correct code should be. John Hi John, I don't think the book is completely useless, it just misses the features added to python since 1.5.2; it was my first book, too, and I think it's still fine to learn the basics. I don't have it at hand right now, so I cannot look for your example, and mine is a german copy, so it probably won't have the same typo. If the code example looks like: print "Hello world" print ''Goodbye world" it's a typo. It is just a guess, maybe the example later in the book looks rather like: print 'I say "Hello world"' or print "You say 'Goodbye world'" ? In python you can use both single (') or double (") quotes to delimit a string, but you need to use the same character both at the beginning and the end of the string. The character that is not used to delimit the string can be used inside the string. I hope this helps Michael From kent37 at tds.net Wed Feb 15 14:19:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Feb 2006 08:19:41 -0500 Subject: [Tutor] G'day In-Reply-To: <20060215134243.57f521ea.klappnase@freenet.de> References: <20060215134243.57f521ea.klappnase@freenet.de> Message-ID: <43F32A6D.4020408@tds.net> Michael Lange wrote: > On Wed, 15 Feb 2006 22:05:39 +1100 > "John Connors" wrote: > I have a copy of Teach Yourself Python in 24 Hours, printed in 2000 so I guess it's virtually usless but i was hoping to learn some of the basics from it. > > I don't think the book is completely useless, it just misses the features added to python since 1.5.2; Python 1.5.2 is getting pretty long in the tooth. The Python developers are very good at maintaining backward compatibility, so most of what you learn will be correct and work, but some of it will no longer be idiomatic usage and you will not learn about the many new features that have been introduced in subsequent versions. At the very least you should skim the "What's New with Python 2.x" documents to get an idea what you are missing. Older versions of this document can be found here: http://www.amk.ca/python/ The Python 2.4 version comes with the Python docs. You might also want to look at an on-line tutorial to get some more modern usage. Several are listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Both Learning to Program and A Byte of Python are popular with beginners. Kent From kermit at polaris.net Wed Feb 15 09:53:23 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 15 Feb 2006 03:53:23 -0500 (Eastern Standard Time) Subject: [Tutor] Sqrt is listed as always available. Message-ID: <43F2EC03.000003.02932@YOUR-4105E587B6> Sqrt is listed as always available. Why did I get these diagnostics? >>> Sqrt(J0) Traceback (most recent call last): File "", line 1, in -toplevel- Sqrt(J0) NameError: name 'Sqrt' is not defined >>> >>> sqrt(J0) Traceback (most recent call last): File "", line 1, in -toplevel- sqrt(J0) NameError: name 'sqrt' is not defined >>> SQRT(J0) Traceback (most recent call last): File "", line 1, in -toplevel- SQRT(J0) NameError: name 'SQRT' is not defined >>> From bgailer at alum.rpi.edu Wed Feb 15 16:19:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 15 Feb 2006 07:19:56 -0800 Subject: [Tutor] Sqrt is listed as always available. In-Reply-To: <43F2EC03.000003.02932@YOUR-4105E587B6> References: <43F2EC03.000003.02932@YOUR-4105E587B6> Message-ID: <43F3469C.3050902@alum.rpi.edu> Kermit Rose wrote: > Sqrt is listed as always available. > Where did you see that? Try: >>> import math >>> math.sqrt(24) 4.8989794855663558 > Why did I get these diagnostics? > > > >>>> Sqrt(J0) >>>> > > Traceback (most recent call last): > File "", line 1, in -toplevel- > Sqrt(J0) > NameError: name 'Sqrt' is not defined > >>>> sqrt(J0) >>>> > > Traceback (most recent call last): > File "", line 1, in -toplevel- > sqrt(J0) > NameError: name 'sqrt' is not defined > >>>> SQRT(J0) >>>> > > Traceback (most recent call last): > File "", line 1, in -toplevel- > SQRT(J0) > NameError: name 'SQRT' is not defined > >>>> >>>> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From m_webber_sydney at yahoo.com.au Wed Feb 15 16:29:00 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Wed, 15 Feb 2006 15:29:00 -0000 Subject: [Tutor] Sqrt is listed as always available. In-Reply-To: <43F2EC03.000003.02932@YOUR-4105E587B6> Message-ID: <001201c63244$8da714a0$0200a8c0@kookaburra> This works for me under Python 2.4 - import math math.sqrt(4) When you state "Sqrt is listed as always available", where does it say that? For future problem reports, let us know which Python release you are running. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kermit Rose Sent: 15 February 2006 08:53 To: tutor at python.org Subject: [Tutor] Sqrt is listed as always available. Sqrt is listed as always available. Why did I get these diagnostics? >>> Sqrt(J0) Traceback (most recent call last): File "", line 1, in -toplevel- Sqrt(J0) NameError: name 'Sqrt' is not defined >>> >>> sqrt(J0) Traceback (most recent call last): File "", line 1, in -toplevel- sqrt(J0) NameError: name 'sqrt' is not defined >>> SQRT(J0) Traceback (most recent call last): File "", line 1, in -toplevel- SQRT(J0) NameError: name 'SQRT' is not defined >>> From mbroe at columbus.rr.com Wed Feb 15 23:45:48 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Wed, 15 Feb 2006 17:45:48 -0500 Subject: [Tutor] Unexpected behavior of += Message-ID: I just discovered the following behavior, but can't find any documentation about it: >>> list = [] >>> list = list + 'abc' Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "str") to list but: >>> list = [] >>> list += 'abc' >>> list ['a', 'b', 'c'] Is this a special characteristic that has been added to the augmented assignment operator +=; or is it an automatic consequence of += assignment being performed'in place'? (Tho I can't see how it could be...) It just seems very un-Pythonesque to be able to successfully concatenate objects of different types like this. And it seems very inconsistent with standard assignment. Indeed, the Python Reference Manual, section 6.3.1 states: "With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations." ...which is patently not the case here. I was scandalized lol! From kent37 at tds.net Thu Feb 16 00:10:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Feb 2006 18:10:10 -0500 Subject: [Tutor] Unexpected behavior of += In-Reply-To: References: Message-ID: <43F3B4D2.2070704@tds.net> Michael Broe wrote: > I just discovered the following behavior, but can't find any > documentation about it: > > >>> list = [] > >>> list = list + 'abc' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: can only concatenate list (not "str") to list > > but: > > >>> list = [] > >>> list += 'abc' > >>> list > ['a', 'b', 'c'] There was a recent thread on c.l.py that started with exactly this question. The consensus seems to be that it is a mistake but oh well. http://groups.google.com/group/comp.lang.python/browse_frm/thread/c96f9830c6919354/94cab5c3b99a9ffa?tvc=1#94cab5c3b99a9ffa Kent From tim at johnsons-web.com Thu Feb 16 04:51:27 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 15 Feb 2006 18:51:27 -0900 Subject: [Tutor] using popen(n) to intercept stdout Message-ID: <20060216035127.GA1805@johnsons-web.com> Hi: I've got a question about popen2. Consider the following code: (on linux) import popen2 fin, fout = popen2.popen2("man nothere") ## interpreter outputs the following: No manual entry for nothere The following queries of the returned file objects give the following: >>> fin ', mode 'r' at 0x404935e0> >>> fout ', mode 'w' at 0x401758a0> >>> fin.read() '' Question: How do I intercept the first response? I.E. How do I get "No manual entry for nothere" into a variable? The object is to call another process on the same machine and capture the output of that process, assuming that the child process is writing to stdout. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From hugonz-lists at h-lab.net Thu Feb 16 06:07:14 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Feb 2006 23:07:14 -0600 Subject: [Tutor] using popen(n) to intercept stdout In-Reply-To: <20060216035127.GA1805@johnsons-web.com> References: <20060216035127.GA1805@johnsons-web.com> Message-ID: <43F40882.5020304@h-lab.net> Hi Tim, You are correctly using the filehandles you have, but the man command must be sending the response into STDERR instead of STDOUT. This makes sense, since it is an error message. Take a look at popen4() and popen3() which both let you catch the standard error of a process. Also, in more recent versions of Python, take a look at the module named Subprocess. Hope that helps, Hugo > > Question: > How do I intercept the first response? > I.E. How do I get "No manual entry for nothere" > into a variable? > > The object is to call another process on the same machine and capture > the output of that process, assuming that the child process is writing > to stdout. > > thanks > tim > From hugonz-lists at h-lab.net Thu Feb 16 06:12:13 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Feb 2006 23:12:13 -0600 Subject: [Tutor] using popen(n) to intercept stdout In-Reply-To: <20060216035127.GA1805@johnsons-web.com> References: <20060216035127.GA1805@johnsons-web.com> Message-ID: <43F409AD.5000801@h-lab.net> I also noticed that if you want to get the manpage, you will be hurt by the interactivity of 'man' (it uses less for paging) One way to get the whole manpage as text without paging is to do: man -P /bin/cat So you won't have to do strange stuff in stdin to get it to give you the whole text. Hugo From tim at johnsons-web.com Thu Feb 16 06:46:19 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 15 Feb 2006 20:46:19 -0900 Subject: [Tutor] using popen(n) to intercept stdout In-Reply-To: <43F409AD.5000801@h-lab.net> References: <20060216035127.GA1805@johnsons-web.com> <43F409AD.5000801@h-lab.net> Message-ID: <20060216054619.GB1805@johnsons-web.com> Hey Hugo: I now realize that to properly test this, I should use a command that returns legitimate data: I think the following gets me started: f = os.popen('ls *.py','r').read() now I have captured the output from 'ls *.py'. So, if I do this with popen3: >>> a,b,c = os.popen3('wt *.py','r') >>> res = a.read() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 9] Bad file descriptor >>> err = c.read() >>> err '/bin/sh: line 1: wt: command not found\n' Then I can trap for IOError and hand either a legal response or an error. Hope I'm still on the right track. thanks tim * Hugo Gonz?lez Monteverde [060215 20:25]: > I also noticed that if you want to get the manpage, you will be hurt by > the interactivity of 'man' (it uses less for paging) One way to get the > whole manpage as text without paging is to do: > > man -P /bin/cat > > So you won't have to do strange stuff in stdin to get it to give you the > whole text. > > Hugo -- Tim Johnson http://www.alaska-internet-solutions.com From hugonz-lists at h-lab.net Thu Feb 16 06:46:09 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 15 Feb 2006 23:46:09 -0600 Subject: [Tutor] using popen(n) to intercept stdout In-Reply-To: <20060216054619.GB1805@johnsons-web.com> References: <20060216035127.GA1805@johnsons-web.com> <43F409AD.5000801@h-lab.net> <20060216054619.GB1805@johnsons-web.com> Message-ID: <43F411A1.5050807@h-lab.net> Hi Tim, Yes, you're on the right track. >>>>a,b,c = os.popen3('wt *.py','r') >>>>res = a.read() The error you're getting has nothing to do with the result of the command, but check, from the docs: popen3( cmd[, mode[, bufsize]]) Executes cmd as a sub-process. Returns the file objects (child_stdin, child_stdout, child_stderr). Availability: Unix, Windows. New in version 2.0. > > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 9] Bad file descriptor > >>> The 'a' variable is supposed to be the process' STDIN, you are supposed to write to it. So if you want to read, it is the wrong file object, and it is in write mode, therefore the IOError. Also check that the above docs are for os.popen(), popen2.popen() returns filehandles in a different order. Hugo From broek at cc.umanitoba.ca Thu Feb 16 14:36:15 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 16 Feb 2006 07:36:15 -0600 Subject: [Tutor] problems with the shebang line and linux Message-ID: <43F47FCF.3030304@cc.umanitoba.ca> Hi all, I've switched to Linux fairly recently and am still at the fumbling about stage :-) I'm having a devil of a time with the shebang line and running a py file from a command line. I wrote the following little test script with IDLE 1.1.2 under Python 2.4.2 on Ubuntu 5.10: #!/usr/bin/python print "Working!" I then C & P'ed it to another .py file. testerlyfoo.py is the original, testerlybar.py is the pasted copy. Here's my command line results: brian at Cedric:~$ which python /usr/bin/python brian at Cedric:~$ cd /media/windata/ brian at Cedric:/media/windata$ ./testerlyfoo.py Working! brian at Cedric:/media/windata$ ./testerlybar.py bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory brian at Cedric:/media/windata$ I even retyped the testerlybar.py file, but I end up with the same results as when the small script was copied and pasted. Likewise, I got the same results after saving the two files to my Home directory on the hail mary thought that perhaps the fact I'd save the originals on a FAT32 mounted drive might be making things goofy. I'm stumped. Any steps I can take to work out what's going on? Best to all, Brian vdB From adam.jtm30 at gmail.com Thu Feb 16 15:23:25 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 16 Feb 2006 14:23:25 +0000 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: <43F47FCF.3030304@cc.umanitoba.ca> References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: On 16/02/06, Brian van den Broek wrote: > > Hi all, > > I've switched to Linux fairly recently and am still at the fumbling > about stage :-) I'm having a devil of a time with the shebang line > and running a py file from a command line. > > I wrote the following little test script with IDLE 1.1.2 under Python > 2.4.2 on Ubuntu 5.10: > > > #!/usr/bin/python > print "Working!" > > > I then C & P'ed it to another .py file. testerlyfoo.py is the > original, testerlybar.py is the pasted copy. > > Here's my command line results: > > brian at Cedric:~$ which python > /usr/bin/python > brian at Cedric:~$ cd /media/windata/ > brian at Cedric:/media/windata$ ./testerlyfoo.py > Working! > brian at Cedric:/media/windata$ ./testerlybar.py > bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > file or directory It seems to me that that ^M is your problem although I'm not quite sure where it came from there seems to be an extra character on the end of the copied one. Here's a little test I did: #! /bin/py print "What the hell!!" adam at darkstar:~$ ./test.py -bash: ./test.py: /bin/py: bad interpreter: No such file or directory and there doesn't seem to be any weird thing on the end even though that file doesn't exist. brian at Cedric:/media/windata$ > > I even retyped the testerlybar.py file, but I end up with the same > results as when the small script was copied and pasted. > > Likewise, I got the same results after saving the two files to my Home > directory on the hail mary thought that perhaps the fact I'd save the > originals on a FAT32 mounted drive might be making things goofy. > > I'm stumped. Any steps I can take to work out what's going on? > > Best to all, > > Brian vdB > _______________________________________________ > 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/20060216/96174ff1/attachment.htm From Senthil_OR at Dell.com Thu Feb 16 15:22:06 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Thu, 16 Feb 2006 08:22:06 -0600 Subject: [Tutor] problems with the shebang line and linux Message-ID: >> bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory brian at Cedric:/media/windata$ Note the ^M the additional fileformat character inserted. That is causing the problem. Instead of copying and pasting try to use cp file1 file2. Else, open the copied file and try to remove ^M from it. Under vim, it is :%s/\r//g ( this removed the additional line break character which your editor or something had introduced. -- Senthil -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Brian van den Broek Sent: Thursday, February 16, 2006 7:06 PM To: Tutor Subject: [Tutor] problems with the shebang line and linux Hi all, I've switched to Linux fairly recently and am still at the fumbling about stage :-) I'm having a devil of a time with the shebang line and running a py file from a command line. I wrote the following little test script with IDLE 1.1.2 under Python 2.4.2 on Ubuntu 5.10: #!/usr/bin/python print "Working!" I then C & P'ed it to another .py file. testerlyfoo.py is the original, testerlybar.py is the pasted copy. Here's my command line results: brian at Cedric:~$ which python /usr/bin/python brian at Cedric:~$ cd /media/windata/ brian at Cedric:/media/windata$ ./testerlyfoo.py Working! brian at Cedric:/media/windata$ ./testerlybar.py bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory brian at Cedric:/media/windata$ I even retyped the testerlybar.py file, but I end up with the same results as when the small script was copied and pasted. Likewise, I got the same results after saving the two files to my Home directory on the hail mary thought that perhaps the fact I'd save the originals on a FAT32 mounted drive might be making things goofy. I'm stumped. Any steps I can take to work out what's going on? Best to all, Brian vdB _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From nixonron at yahoo.com Thu Feb 16 16:07:41 2006 From: nixonron at yahoo.com (Ron Nixon) Date: Thu, 16 Feb 2006 07:07:41 -0800 (PST) Subject: [Tutor] python mechanize examples Message-ID: <20060216150742.78450.qmail@web34206.mail.mud.yahoo.com> Anyone have or know where I can find working examples of python's mechanize modules. Try to reverse engineer a script to see how it works. Ron --------------------------------- Yahoo! Autos. Looking for a sweet ride? Get pricing, reviews, & more on new and used cars. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060216/14cf0029/attachment.htm From tiagosaboga at terra.com.br Thu Feb 16 15:48:24 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 16 Feb 2006 12:48:24 -0200 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: <200602161248.25637.tiagosaboga@terra.com.br> Em Qui 16 Fev 2006 12:23, Adam escreveu: > > brian at Cedric:/media/windata$ ./testerlybar.py > > bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > > file or directory > > It seems to me that that ^M is your problem although I'm not quite sure > where it came from there seems to be an extra character on the end of the > copied one. I'm pretty sure the problem is the different way linux and windows/dos mark the end of line (IIRC, linux -> LF, windows -> CR+LF). Just try (it's installed on my debian box, I can check which package it is, if you want): $ fromdos -b testerlybar.py Of course, reading the manual page for fromdos is a good thing. tiago saboga. From broek at cc.umanitoba.ca Thu Feb 16 16:33:16 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 16 Feb 2006 09:33:16 -0600 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: References: Message-ID: <43F49B3C.1050700@cc.umanitoba.ca> Senthil_OR at Dell.com said unto the world upon 16/02/06 08:22 AM: >>>bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > > file or directory brian at Cedric:/media/windata$ > > Note the ^M the additional fileformat character inserted. That is > causing the problem. > > Instead of copying and pasting try to use cp file1 file2. > Else, open the copied file and try to remove ^M from it. Under vim, it > is :%s/\r//g ( this removed the additional line break character which > your editor or something had introduced. Hi, thanks; I did notice the '^M' and was puzzled by it. It persisted even when I manually retyped the script in IDLE. Or, more conservatively, I feel certain that this is so :-) Either way, the cp dance worked. I call Gremlins! ;-) Best, Brian vdB From kent37 at tds.net Thu Feb 16 16:42:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Feb 2006 10:42:42 -0500 Subject: [Tutor] python mechanize examples In-Reply-To: <20060216150742.78450.qmail@web34206.mail.mud.yahoo.com> References: <20060216150742.78450.qmail@web34206.mail.mud.yahoo.com> Message-ID: <43F49D72.2050603@tds.net> Ron Nixon wrote: > Anyone have or know where I can find working examples of python's > mechanize modules. Try to reverse engineer a script to see how it works. There are a few examples on the mechanize home page and in the source download (not in the egg). There is quite a bit of help in the docstrings - either browse the source or use e.g. help(mechanize.Browser) in Python. http://wwwsearch.sourceforge.net/mechanize/ Kent From python at venix.com Thu Feb 16 16:43:24 2006 From: python at venix.com (Python) Date: Thu, 16 Feb 2006 10:43:24 -0500 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: <43F47FCF.3030304@cc.umanitoba.ca> References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: <1140104604.17747.232.camel@www.venix.com> On Thu, 2006-02-16 at 07:36 -0600, Brian van den Broek wrote: > Hi all, > > I've switched to Linux fairly recently and am still at the fumbling > about stage :-) I'm having a devil of a time with the shebang line > and running a py file from a command line. > The file has dos/windows format with CR/LF markers to separate lines. A normal posix file should only use LF. dos2unix is a handy utility for converting text files. Depending on your distribution, you should be able to install it using apt or yum e.g. yum install dos2unix or use the GUI interface to your package manager (yumex is the yum GUI, I do not remember the name of the apt GUI). On a shared partition, keeping .py files in a posix format (LF only) has never caused any problems for me. The Python compiler/interpreter on Windows will happily process either format. -- Lloyd Kvam Venix Corp From nick at javacat.f2s.com Thu Feb 16 15:26:57 2006 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 16 Feb 2006 14:26:57 -0000 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: Hi Brian, it's the ^M characters that are catching you out here. Often files from a windows PC will have ^M as the newline char when viewed in linux/unix. On linux you should be able to check if a file has ^M in by running either 'vi -b filename' or 'sed -n l filename'. Try this with the file vi filename escape :%s/^M// That should get rid of all the ^M chars. (not on linux at the mo so not 100% sure). The ^M is done in vi by actually typing in 'Ctl-V M' not shift6 M. What I wrote above may not sound too clear, but feel free to email me off list if you need any vi or linux commandline help (altho ive never used ubuntu so anything ubuntu specific I wont be much use with). Good luck, Nick . > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Brian van den Broek > Sent: 16 February 2006 13:36 > To: Tutor > Subject: [Tutor] problems with the shebang line and linux > > > Hi all, > > I've switched to Linux fairly recently and am still at the fumbling > about stage :-) I'm having a devil of a time with the shebang line > and running a py file from a command line. > > I wrote the following little test script with IDLE 1.1.2 under Python > 2.4.2 on Ubuntu 5.10: > > > #!/usr/bin/python > print "Working!" > > > I then C & P'ed it to another .py file. testerlyfoo.py is the > original, testerlybar.py is the pasted copy. > > Here's my command line results: > > brian at Cedric:~$ which python > /usr/bin/python > brian at Cedric:~$ cd /media/windata/ > brian at Cedric:/media/windata$ ./testerlyfoo.py > Working! > brian at Cedric:/media/windata$ ./testerlybar.py > bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > file or directory > brian at Cedric:/media/windata$ > > I even retyped the testerlybar.py file, but I end up with the same > results as when the small script was copied and pasted. > > Likewise, I got the same results after saving the two files to my Home > directory on the hail mary thought that perhaps the fact I'd save the > originals on a FAT32 mounted drive might be making things goofy. > > I'm stumped. Any steps I can take to work out what's going on? > > Best to all, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.375 / Virus Database: 267.15.9/261 - Release Date: 15/02/2006 > From david at graniteweb.com Thu Feb 16 17:47:34 2006 From: david at graniteweb.com (David Rock) Date: Thu, 16 Feb 2006 10:47:34 -0600 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: <20060216164734.GA3012@wdfs.graniteweb.com> * Adam [2006-02-16 14:23]: > On 16/02/06, Brian van den Broek wrote: > > It seems to me that that ^M is your problem although I'm not quite sure > where it came from there seems to be an extra character on the end of the > copied one. Here's a little test I did: > > #! /bin/py > print "What the hell!!" > > adam at darkstar:~$ ./test.py > -bash: ./test.py: /bin/py: bad interpreter: No such file or directory > and there doesn't seem to be any weird thing on the end even though that > file doesn't exist. I would verify that /bin/py is the actual location of your python interperter. That's a really weird location. > > I even retyped the testerlybar.py file, but I end up with the same > > results as when the small script was copied and pasted. > > > > Likewise, I got the same results after saving the two files to my Home > > directory on the hail mary thought that perhaps the fact I'd save the > > originals on a FAT32 mounted drive might be making things goofy. > > > > I'm stumped. Any steps I can take to work out what's going on? I have verified that ^M at the end _will_ break it. I also verified that having a space doesn't matter, either. Both work: #!/usr/bin/python #! /usr/bin/python When you retyped it, what editor did you use? When you cat the file: cat testerlybar.py What does the output look like? If you have xxd installed (you probably do): xxd testerlybar.py What does the output look like? This will help us see EXACTLY what's in the file. It will look something like this: drock at mojojojo ~ $ xxd foo.py 0000000: 2321 202f 7573 722f 6269 6e2f 7079 7468 #! /usr/bin/pyth 0000010: 6f6e 0a70 7269 6e74 2022 4865 6c6c 6f22 on.print "Hello" 0000020: 0a . Bottom line, the error means bash can not find the application you told it to use, so something is wrong with the path you have in the file. -- David Rock david at graniteweb.com From rschroev_nospam_ml at fastmail.fm Thu Feb 16 18:14:32 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 16 Feb 2006 18:14:32 +0100 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: Adam schreef: > > > On 16/02/06, *Brian van den Broek* > wrote: > > brian at Cedric:~$ which python > /usr/bin/python > brian at Cedric:~$ cd /media/windata/ > brian at Cedric:/media/windata$ ./testerlyfoo.py > Working! > brian at Cedric :/media/windata$ ./testerlybar.py > bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > file or directory > > > It seems to me that that ^M is your problem although I'm not quite sure > where it came from there seems to be an extra character on the end of > the copied one. Here's a little test I did: That ^M looks familiar to me: normally it means that the file is in DOS/Windows format instead of UNIX format, i.e. with CR/LF at the end of each line instead of only CR. Converting the file with dos2unix or a similar utility should solve the problem in that case. I guess it's there because the file comes from a FAT32 file system, and I presume it has mount options that make the filesystem translate the line endings automatically (though I don't know if such an option even exists). Strange thing is that the problem persists after retyping the file, but I guess that's because the editor was still in CR/LF mode. Did you create a new file before starting to retype, or did you just clear everything? -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From nick at javacat.f2s.com Thu Feb 16 20:41:03 2006 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 16 Feb 2006 19:41:03 -0000 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: Message-ID: Take no notice of this, others have already answered. My emails to the tutor list seem to take about 5 hours to get thru for some reason. Nick . > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Nick Lunt > Sent: 16 February 2006 14:27 > To: Brian van den Broek; Tutor > Subject: Re: [Tutor] problems with the shebang line and linux > > > Hi Brian, > > it's the ^M characters that are catching you out here. > > Often files from a windows PC will have ^M as the newline char when viewed > in linux/unix. > > On linux you should be able to check if a file has ^M in by running either > 'vi -b filename' or 'sed -n l filename'. > > Try this with the file > > vi filename > escape > :%s/^M// > > That should get rid of all the ^M chars. (not on linux at the mo > so not 100% > sure). > The ^M is done in vi by actually typing in 'Ctl-V M' not shift6 M. > > What I wrote above may not sound too clear, but feel free to email me off > list if you need any vi or linux commandline help (altho ive never used > ubuntu so anything ubuntu specific I wont be much use with). > > Good luck, > Nick . > > > > -----Original Message----- > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > > Behalf Of Brian van den Broek > > Sent: 16 February 2006 13:36 > > To: Tutor > > Subject: [Tutor] problems with the shebang line and linux > > > > > > Hi all, > > > > I've switched to Linux fairly recently and am still at the fumbling > > about stage :-) I'm having a devil of a time with the shebang line > > and running a py file from a command line. > > > > I wrote the following little test script with IDLE 1.1.2 under Python > > 2.4.2 on Ubuntu 5.10: > > > > > > #!/usr/bin/python > > print "Working!" > > > > > > I then C & P'ed it to another .py file. testerlyfoo.py is the > > original, testerlybar.py is the pasted copy. > > > > Here's my command line results: > > > > brian at Cedric:~$ which python > > /usr/bin/python > > brian at Cedric:~$ cd /media/windata/ > > brian at Cedric:/media/windata$ ./testerlyfoo.py > > Working! > > brian at Cedric:/media/windata$ ./testerlybar.py > > bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such > > file or directory > > brian at Cedric:/media/windata$ > > > > I even retyped the testerlybar.py file, but I end up with the same > > results as when the small script was copied and pasted. > > > > Likewise, I got the same results after saving the two files to my Home > > directory on the hail mary thought that perhaps the fact I'd save the > > originals on a FAT32 mounted drive might be making things goofy. > > > > I'm stumped. Any steps I can take to work out what's going on? > > > > Best to all, > > > > Brian vdB > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > > No virus found in this incoming message. > > Checked by AVG Free Edition. > > Version: 7.1.375 / Virus Database: 267.15.9/261 - Release Date: > 15/02/2006 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.375 / Virus Database: 267.15.9/261 - Release Date: 15/02/2006 > > From dyoo at hkn.eecs.berkeley.edu Thu Feb 16 22:28:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Feb 2006 13:28:19 -0800 (PST) Subject: [Tutor] python mechanize examples In-Reply-To: <20060216150742.78450.qmail@web34206.mail.mud.yahoo.com> Message-ID: On Thu, 16 Feb 2006, Ron Nixon wrote: > Anyone have or know where I can find working examples of python's > mechanize modules. Try to reverse engineer a script to see how it works. Hi Ron, I'm assuming, for the moment, that you're talking about the third-party 'mechanize' module: http://wwwsearch.sourceforge.net/mechanize/ Is this what you're talking about? Talk to you later! From john at fouhy.net Thu Feb 16 23:00:45 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 17 Feb 2006 11:00:45 +1300 Subject: [Tutor] G'day In-Reply-To: References: Message-ID: <5e58f2e40602161400o131d2c1eu@mail.gmail.com> On 16/02/06, John Connors wrote: > My 1st dumb question: I have a copy of Teach Yourself Python in 24 Hours, > printed in 2000 so I guess it's virtually usless but i was hoping to learn > some of the basics from it. There is a small bit of code near the > beginning... Check out the tutorial on the website at http://python.org/. Although you might find some concepts have changed a bit since the basic days.. I've also heard that Alan Gauld's tutorial is pretty good: http://www.freenetpages.co.uk/hp/alan.gauld/ Plus, the author is pretty responsive :-) > print "Hello, World!" > > print ' 'Goodbye, World!" > > which returns a syntax error for the 2nd line. I thought it was a typo and > changed it to print "Goodbye, World!". Err, yeah. That's a bit odd. Strings in python are delimited either by single quotes or double quotes, but you can't mix and match. So, you could do this: print 'Hello world!' or this: print "Hello world!" but you can't replace a double quote with two single quotes. -- John. From broek at cc.umanitoba.ca Thu Feb 16 23:25:33 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 16 Feb 2006 16:25:33 -0600 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: References: <43F47FCF.3030304@cc.umanitoba.ca> Message-ID: <43F4FBDD.3050708@cc.umanitoba.ca> Thanks to all for the replies. Indeed, it must have been the DOS vs. Unix line terminators as several people suggested. A couple of comments in-line below. Roel Schroeven said unto the world upon 16/02/06 11:14 AM: >>On 16/02/06, *Brian van den Broek* >> wrote: >> >> brian at Cedric:~$ which python >> /usr/bin/python >> brian at Cedric:~$ cd /media/windata/ >> brian at Cedric:/media/windata$ ./testerlyfoo.py >> Working! >> brian at Cedric :/media/windata$ ./testerlybar.py >> bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such >> file or directory > That ^M looks familiar to me: normally it means that the file is in > DOS/Windows format instead of UNIX format, i.e. with CR/LF at the end of > each line instead of only CR. Converting the file with dos2unix or a > similar utility should solve the problem in that case. While I'm unable to recall exactly what I did, this must have been it. I *think* I created the offending file while running ubuntu, but launched IDLE by using a right-click context menu entry for "Open with IDLE" on a file originally created earlier today while running Windows. So, my guess is that doing this put IDLE into Win endings mode. > I guess it's there because the file comes from a FAT32 file system, and > I presume it has mount options that make the filesystem translate the > line endings automatically (though I don't know if such an option even > exists). This doesn't seem to be the case as older .py files created on Windows before the last Windows reinstall that inspired me to try ubuntu show Unix endings. (Knowing that Windows takes Unix endings just fine for .py's, I'd set my previous Windows install's IDLE to use Unix endings. I guess I didn't make that setting after reinstalling Windows.) > Strange thing is that the problem persists after retyping the file, but > I guess that's because the editor was still in CR/LF mode. Did you > create a new file before starting to retype, or did you just clear > everything? Just cleared. So, somewhere in the complex of ill-recalled events surely lives the answer. Anyway, thanks again to all for the help! Brian vdB From alan.gauld at freenet.co.uk Fri Feb 17 00:07:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 16 Feb 2006 23:07:31 -0000 Subject: [Tutor] using popen(n) to intercept stdout References: <20060216035127.GA1805@johnsons-web.com><43F409AD.5000801@h-lab.net> <20060216054619.GB1805@johnsons-web.com> Message-ID: <006601c6334d$c466fd20$0b01a8c0@xp> Hi Tim, > I now realize that to properly test this, I should use a command that > returns legitimate data: > I think the following gets me started: > f = os.popen('ls *.py','r').read() > now I have captured the output from 'ls *.py'. You probably should consider using the Popen class in the new subprocess module. It makes all previous mechanisms (system, popen, commands, fork, execv etc) obsolescent. There are basic instructions for using Popen to replace popen[n] etc in my new OS topic on the web site and the documentation gives some rather terse examples too... 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 Feb 17 00:20:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 16 Feb 2006 23:20:51 -0000 Subject: [Tutor] problems with the shebang line and linux References: Message-ID: <001201c6334f$a12f9180$0b01a8c0@xp> > Try this with the file > > vi filename > escape > :%s/^M// > Or just run the dos2unix command that comes with most Linux distros... Or even use Python to write a script to strip() each line and write it back with a \n... In fact there's a prewritten script called crlf.py in the Tools folder of a standard Python install.... Alan G. From adam.jtm30 at gmail.com Fri Feb 17 00:59:32 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 16 Feb 2006 23:59:32 +0000 Subject: [Tutor] problems with the shebang line and linux In-Reply-To: <20060216164734.GA3012@wdfs.graniteweb.com> References: <43F47FCF.3030304@cc.umanitoba.ca> <20060216164734.GA3012@wdfs.graniteweb.com> Message-ID: On 16/02/06, David Rock wrote: > > * Adam [2006-02-16 14:23]: > > On 16/02/06, Brian van den Broek wrote: > > > > It seems to me that that ^M is your problem although I'm not quite sure > > where it came from there seems to be an extra character on the end of > the > > copied one. Here's a little test I did: > > > > #! /bin/py > > print "What the hell!!" > > > > adam at darkstar:~$ ./test.py > > -bash: ./test.py: /bin/py: bad interpreter: No such file or directory > > and there doesn't seem to be any weird thing on the end even though that > > file doesn't exist. > > I would verify that /bin/py is the actual location of your python > interperter. That's a really weird location. The whole idea was to use a path where there was nothing just to prove you don't get the ^M on all errors of that type. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060216/260e7faf/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Feb 17 01:49:26 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Feb 2006 16:49:26 -0800 (PST) Subject: [Tutor] python mechanize examples In-Reply-To: <20060216233246.95008.qmail@web34205.mail.mud.yahoo.com> Message-ID: > Yeah that's the module I'm talking about. I installed it and trying to > get it to work using the docs, but it would be good to see some actual > working examples. Hi Ron, I haven't played around with mechanize, but according to: http://wwwsearch.sourceforge.net/mechanize/#tests working examples should come with the source there: http://codespeak.net/svn/wwwsearch/mechanize/trunk/examples/ Good luck! From alan.gauld at freenet.co.uk Fri Feb 17 11:02:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 17 Feb 2006 10:02:01 -0000 Subject: [Tutor] G'day References: <5e58f2e40602161400o131d2c1eu@mail.gmail.com> Message-ID: <002e01c633a9$3279f1e0$0b01a8c0@xp> On 16/02/06, John Connors wrote: > My 1st dumb question: I have a copy of Teach Yourself Python in 24 Hours, > printed in 2000 so I guess it's virtually usless but i was hoping to learn > some of the basics from it. There is a small bit of code near the > beginning... I missed the original post but.... The book is sufficiently basic that virtually everything is still valid so no problems there. The biggest issue is that it uses the string module functions rather than the newer string methods but thats easily fixed later, and the string module is still there so his code works... Its not a bad book IMHO apart from Ivan's fixation with Mayan calendars! :-) > print "Hello, World!" > > print ' 'Goodbye, World!" If you are referring to the bit on page 25 it is the same style of quote in both examples in my copy of the book. Are you sure its different? Or are you looking at another page? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From garcia.servando at gmail.com Fri Feb 17 14:06:29 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Fri, 17 Feb 2006 07:06:29 -0600 Subject: [Tutor] unable to insert data into database Message-ID: <43F5CA55.7030405@gmail.com> Hello to all I have been trying to insert data into a database using MySQLdb with no success. I have no idea why this script is not working. I took it from a tutorial from DEV Shed. #!/usr/bin/python import MySQLdb # connect db = MySQLdb.connect(host="localhost", user="root", passwd="******",db="tutorial") # create a cursor cursor = db.cursor() #User Input name = raw_input("Please enter a name: ") color = raw_input("Please enter a color: ") #Insert data into table "Horses" cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color)) From prabhu.chinnee at gmail.com Fri Feb 17 14:13:01 2006 From: prabhu.chinnee at gmail.com (Prabhakar K) Date: Fri, 17 Feb 2006 18:43:01 +0530 Subject: [Tutor] Problem wxPython Message-ID: <3ae549770602170513o1c4a51e2x67fc09024df1f40@mail.gmail.com> Hai to all, I installed ActivePython-2.4.1-247-win32-ix86 and wxPython2.6-win32-ansi-2.6.2.1-py2 in my system. When i Run a wxPython example.. geeting an Errors Traceback (most recent call last): File "E:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "F:\python\wx.py", line 1, in ? from wxPython.wx import * File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\__init__.py", line 10, in ? import _wx File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\_wx.py", line 3, in ? from _core import * File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\_core.py", line 15, in ? import wx._core File "F:\python\wx.py", line 1, in ? from wxPython.wx import * ImportError: No module named wx Program Code: from wxPython.wx import * class MyApp(wxApp): def OnInit(self): frame = wxFrame(NULL, -1, "Hello from wxPython") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060217/a38e1d7c/attachment.html From andre.roberge at gmail.com Fri Feb 17 14:22:09 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Fri, 17 Feb 2006 09:22:09 -0400 Subject: [Tutor] Problem wxPython In-Reply-To: <3ae549770602170513o1c4a51e2x67fc09024df1f40@mail.gmail.com> References: <3ae549770602170513o1c4a51e2x67fc09024df1f40@mail.gmail.com> Message-ID: <7528bcdd0602170522i395a391dp8af5e56305e409cb@mail.gmail.com> On 2/17/06, Prabhakar K wrote: > Hai to all, > > I installed ActivePython-2.4.1-247-win32-ix86 and > wxPython2.6-win32-ansi-2.6.2.1-py2 in my system. When i Run > a wxPython example.. geeting an Errors > [snip] > File "F:\python\wx.py", line 1, in ? > from wxPython.wx import * > ImportError: No module named wx > > wxPython changed "notation" between version 2.4 and 2.6 (if memory is right), and your code is using the old notation with the new package. Try (untested) the following changes: > from wxPython.wx import * import wx > > class MyApp(wxApp): class MyApp(wx.App): > def OnInit(self): #no change > frame = wxFrame(NULL, -1, "Hello from wxPython") frame = wx.Frame(None, -1, "Hello from wxPython") > frame.Show(true) frame.Show(True) > self.SetTopWindow(frame) #no change > return true return True > > app = MyApp(0) > app.MainLoop() > Andr? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kraus at hagen-partner.de Fri Feb 17 14:24:04 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 17 Feb 2006 14:24:04 +0100 Subject: [Tutor] unable to insert data into database In-Reply-To: <43F5CA55.7030405@gmail.com> References: <43F5CA55.7030405@gmail.com> Message-ID: Servando Garcia wrote: > Hello to all > I have been trying to insert data into a database using MySQLdb > with no success. I have no idea why this script is not working. I took > it from a tutorial from DEV Shed. > > #!/usr/bin/python > import MySQLdb > # connect > db = MySQLdb.connect(host="localhost", user="root", > passwd="******",db="tutorial") > > # create a cursor > cursor = db.cursor() > > #User Input > name = raw_input("Please enter a name: ") > color = raw_input("Please enter a color: ") > > #Insert data into table "Horses" > cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color)) > > First of all: Does the database "tutorial" exists? Is there a table "horses" in that database? Please show the complete error message you get. The code looks good so far. HTH Wolfram From kent37 at tds.net Fri Feb 17 14:26:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Feb 2006 08:26:49 -0500 Subject: [Tutor] unable to insert data into database In-Reply-To: <43F5CA55.7030405@gmail.com> References: <43F5CA55.7030405@gmail.com> Message-ID: <43F5CF19.6070705@tds.net> Servando Garcia wrote: > Hello to all > I have been trying to insert data into a database using MySQLdb > with no success. I have no idea why this script is not working. I took > it from a tutorial from DEV Shed. What happens when you try it? "Not working" doesn't give us much to go on. If you get an error message, show it to us with the complete stack trace (copy and paste the whole thing). Did it run without error but not change the database? > > #!/usr/bin/python > import MySQLdb > # connect > db = MySQLdb.connect(host="localhost", user="root", > passwd="******",db="tutorial") > > # create a cursor > cursor = db.cursor() > > #User Input > name = raw_input("Please enter a name: ") > color = raw_input("Please enter a color: ") > > #Insert data into table "Horses" > cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color)) Should be VALUES Kent From kraus at hagen-partner.de Fri Feb 17 16:15:17 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 17 Feb 2006 16:15:17 +0100 Subject: [Tutor] unable to insert data into database In-Reply-To: References: <43F5CA55.7030405@gmail.com> Message-ID: <43F5E885.5000901@hagen-partner.de> Wolfram Kraus wrote: > Servando Garcia wrote: > >>Hello to all >> I have been trying to insert data into a database using MySQLdb >>with no success. I have no idea why this script is not working. I took >>it from a tutorial from DEV Shed. >> >>#!/usr/bin/python >>import MySQLdb >># connect >>db = MySQLdb.connect(host="localhost", user="root", >>passwd="******",db="tutorial") >> >># create a cursor >>cursor = db.cursor() >> >>#User Input >>name = raw_input("Please enter a name: ") >>color = raw_input("Please enter a color: ") >> >>#Insert data into table "Horses" >>cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color)) >> >> > > First of all: Does the database "tutorial" exists? Is there a table > "horses" in that database? > Please show the complete error message you get. The code looks good so far. > > HTH > Wolfram > Servando Garcia wrote: ## I have tested the database from a MySQL command line and yes the database exists so does the table. The code runs without error but the database is not affected ## Please keep the replies on the list! Sorry for asking the obvious (Database/Table exists)! You are missing db.commit() db.close() in your code. IIRC auto-commit was switched of for MySQLdb long time ago. HTH, Wolfram From garcia.servando at gmail.com Fri Feb 17 16:22:46 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Fri, 17 Feb 2006 09:22:46 -0600 Subject: [Tutor] Once again I am in error Message-ID: <43F5EA46.9070408@gmail.com> Hello list Seems once again unknowingly I have violated the rules of this list. I posted a request for help with working with a database. A few members of this list were kind enough to reply. When I answered their emails. I simply hit the reply button which sent out a personal email and not a reply to the list. Please forgive this error it will not happen again. Servando Garcia From challman at gmail.com Fri Feb 17 16:28:32 2006 From: challman at gmail.com (Chris Hallman) Date: Fri, 17 Feb 2006 10:28:32 -0500 Subject: [Tutor] TypeError: 'str' object is not callable Message-ID: <9f68812f0602170728x5a1c4001i39794ca37b269cb2@mail.gmail.com> Here is my script: send_file.py import os, random, re, string, sys, telnetlib, threading, time from time import strftime from threading import Thread class ConfigIT(threading.Thread): def __init__(self,host): Thread.__init__(self) self.host = host self.filename = filename def run(self): try: tn = telnetlib.Telnet(self.host) tn.read_until("Username: ", 7) except: output.write(self.host + " - not responding.\n") output.flush() return tn.write(user + "\n") tn.read_until("Password: ", 7) tn.write(pswd + "\n") (index, match, read) = tn.expect(["#"], 7) if not match: output.write(self.host + " - sign-on failure.\n") output.flush() return tn.write("conf t\n") rpath = (dirPath + "\\" + self.filename) print rpath input = file(rpath, "r") for line in file(rpath): time.sleep(random.uniform(0,2)) text = input.readline() tn.write(text) (index, match, read) = tn.expect(["%"], 1) if match: output.write(self.host + " - config error on line = " + text) output.flush() return tn.write("end\n") tn.read_until(self.host.upper() + "#") time.sleep(random.uniform(0,2)) # write config to NVRAM tn.write("wr\n") tn.read_until(self.host.upper() + "#") time.sleep(random.uniform(0,2)) # write config to TFTP tn.write("wr net\n") tn.read_until("]?") time.sleep(random.uniform(0,2)) tn.write("192.168.19.201\n") tn.read_until("]?") time.sleep(random.uniform(0,2)) tn.write("\n") tn.read_until("[confirm]") time.sleep(random.uniform(0,2)) tn.write("\n") (index, match, read) = tn.expect(["OK"], 15) if "Error opening tftp" in read: output.write(self.host + " - config write net failed.\n") output.flush() return # if host = *swa, then write vlan.dat to SYSMAN m = match_swa.match(self.host) if m: tn.write("copy flash tftp\n") tn.read_until("]? ") time.sleep(random.uniform(0,2)) tn.write("vlan.dat\n") tn.read_until("]? ") time.sleep(random.uniform(0,2)) tn.write("192.168.19.201\n") tn.read_until("dat]? ") time.sleep(random.uniform(0,2)) tn.write(self.host + ".vlan.dat\n") (index, match, read) = tn.expect(["OK"], 15) if "Error opening tftp" in read: output.write(self.host + " - VLAN write net failed.\n") output.flush() return tn.write("exit\n") def count_active(): """ returns the number of Getter threads that are alive """ num_active = 0 for thread in tlist: if thread.isAlive(): num_active += 1 return num_active threads = [] dirPath = (r"c:\temp\config") dirList = os.listdir(dirPath) match_swa = re.compile('^s\d\d\d\d[s][w][a]') Max_Threads = 10 pswd = "Activ8" tlist = [] user = "cworks" logFile = (r"c:\logs\send_file.log") output = file(logFile, "a") output.write("\n" + "send_file script started -" + strftime(" %H:%M:%S %x") + "\n") output.flush() for file in dirList: filename = file.lower() host = filename.replace('.txt', '') while count_active() >= Max_Threads: time.sleep(1) threads = ConfigIT(host) tlist.append(threads) threads.start() for thread in tlist: thread.join() output.write("send_file script completed -" + strftime(" %H:%M:%S %x") + "\n") output.flush() output.close() Here is the error: >pythonw -u "send_file.py" c:\temp\config\rtr0544.txt Exception in thread Thread-1: Traceback (most recent call last): File "c:\python24\lib\threading.py", line 442, in __bootstrap self.run() File "send_file.py", line 45, in run input = file(rpath, "r") TypeError: 'str' object is not callable >Exit code: 0 The above script was created using the following script: send_file.r1.py # # This script obtains a directory listing, strips the extensions and telnets to the # device (which is the filename in the directory). Then it writes the commands in the # file to the device, saves config and writes it back to SYSMAN. It can be run using: # python send_file.py # # Note: "os" is imported for future functionality. # # by: TCDH # on: 10/17/05 # revised: 10/18/05 TCDH - Added logic to check for offline devices and sign-on failures. # import os, re, string, sys, telnetlib, threading, time from time import strftime from threading import Thread dirPath = (r"c:\temp\config") dirList = os.listdir(dirPath) pswd = "Activ8" user = "cworks" logFile = (r"c:\logs\send_file.log") output = file(logFile, "a") output.write("\n" + "send_file script started -" + strftime(" %H:%M:%S %x") + "\n") output.flush() class ConfigIT(threading.Thread): def __init__(self,host): Thread.__init__(self) self.host = host self.filename = filename def run(self): try: tn = telnetlib.Telnet(self.host) tn.read_until("Username: ", 7) except: output.write(self.host + ": not responding.\n") return tn.write(user + "\n") tn.read_until("Password: ", 7) tn.write(pswd + "\n") (index, match, read) = tn.expect(["#"], 7) if not match: output.write(self.host + ": sign-on failure.\n") return tn.write("conf t\n") rpath = (dirPath + "\\" + self.filename) print rpath input = file(rpath, "r") for line in file(rpath): tn.write(input.readline()) tn.write("end\n") tn.read_until(self.host.upper() + "#") tn.write("wr\n") tn.read_until(self.host.upper() + "#") tn.write("wr net\n") tn.read_until("host []?") tn.write("192.168.19.201\n") tn.read_until("confg]? ") tn.write("\n") tn.read_until("[confirm]") tn.write("\n") (index, match, read) = tn.expect(["OK"], 15) if "Error opening tftp" in read: output.write(self.host + ": write net failed.\n") return tn.write("exit\n") tlist = [] for host in dirList: filename = host.lower() host = host.lower() host = host.replace('.txt', '') current = ConfigIT(host) tlist.append(current) current.start() for entry in tlist: entry.join() output.write("send_file script completed -" + strftime(" %H:%M:%S %x") + "\n") output.flush() output.close() They both use the same syntax to open the input file, however only send_file.py receives an error. What gives? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060217/8c8ec745/attachment-0001.html From kent37 at tds.net Fri Feb 17 16:42:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Feb 2006 10:42:56 -0500 Subject: [Tutor] TypeError: 'str' object is not callable In-Reply-To: <9f68812f0602170728x5a1c4001i39794ca37b269cb2@mail.gmail.com> References: <9f68812f0602170728x5a1c4001i39794ca37b269cb2@mail.gmail.com> Message-ID: <43F5EF00.10805@tds.net> Chris Hallman wrote: > > Here is my script: > input = file(rpath, "r") > for line in file(rpath): > for file in dirList: > filename = file.lower() You use the name 'file' for a global variable. This hides the builtin function 'file'. This is a bit of a gotcha for newbies - the names of builtins are not reserverd words, so they can be reasigned to your own variables. Some of the names that are commonly (mis)used this way are file, list and dict. You just have to learn not to do this. When you try input = file(rpath, "r") file contains a string value, which is not callable the way a function is. Hence the error. The fix is to use a different name for your variable, e.g. 'f'. Also you are opening the file twice, you don't need the very first line above. And 'input' is also the name of a builtin ;) For reference, here is a list of the built-in functions: http://docs.python.org/lib/built-in-funcs.html > Here is the error: > > >pythonw -u "send_file.py" > c:\temp\config\rtr0544.txt > Exception in thread Thread-1: > Traceback (most recent call last): > File "c:\python24\lib\threading.py", line 442, in __bootstrap > self.run() > File "send_file.py", line 45, in run > input = file(rpath, "r") > TypeError: 'str' object is not callable OK, this is saying that you are trying to call a string object, and strings can't be called. You call something with the () syntax. So the thing you are trying to call is the value of the symbol 'file'. Evidently that is a string rather than the built-in file function. Kent From struggleyb at gmail.com Fri Feb 17 16:42:16 2006 From: struggleyb at gmail.com (struggle) Date: Fri, 17 Feb 2006 23:42:16 +0800 Subject: [Tutor] Sqrt is listed as always available. In-Reply-To: <43F3469C.3050902@alum.rpi.edu> References: <43F2EC03.000003.02932@YOUR-4105E587B6> <43F3469C.3050902@alum.rpi.edu> Message-ID: <43F5EED8.1010606@gmail.com> Hello everybody : I feel very interest in the python language ! And I want to learn something about the language , I want to know how it be designed and implemented . I look into the www.python.org , but I didn't find anything about that , can you help me ? From struggleyb at gmail.com Fri Feb 17 16:46:02 2006 From: struggleyb at gmail.com (struggle) Date: Fri, 17 Feb 2006 23:46:02 +0800 Subject: [Tutor] How is python designed ? In-Reply-To: <43F3469C.3050902@alum.rpi.edu> References: <43F2EC03.000003.02932@YOUR-4105E587B6> <43F3469C.3050902@alum.rpi.edu> Message-ID: <43F5EFBA.20809@gmail.com> Hello everybody : I feel very interest in the python language ! And I want to learn something about the language , I want to know how it be designed and implemented . I look into the www.python.org , but I didn't find anything about that , can you help me ? From kent37 at tds.net Fri Feb 17 17:01:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Feb 2006 11:01:11 -0500 Subject: [Tutor] Sqrt is listed as always available. In-Reply-To: <43F5EED8.1010606@gmail.com> References: <43F2EC03.000003.02932@YOUR-4105E587B6> <43F3469C.3050902@alum.rpi.edu> <43F5EED8.1010606@gmail.com> Message-ID: <43F5F347.6040205@tds.net> struggle wrote: > Hello everybody : > I feel very interest in the python language ! And I want to learn > something about the language , > I want to know how it be designed and implemented . I look into the > www.python.org , but I didn't > find anything about that , can you help me ? If you want to know about the *process* by which Python is designed and implemented, the links on this page might help: http://www.python.org/dev/ If you are asking about the internals of the current design and implementation, some PEPs have a discussion of design and implementation: http://www.python.org/peps/ Other than that I don't think there is much to help you except the actual source code which is available here: http://www.python.org/download/ You might also be interested in reading comp.lang.python or the python-dev mailing list which is where new designs and implementations are hashed out. Kent From challman at gmail.com Fri Feb 17 17:08:51 2006 From: challman at gmail.com (Chris Hallman) Date: Fri, 17 Feb 2006 11:08:51 -0500 Subject: [Tutor] TypeError: 'str' object is not callable In-Reply-To: <43F5EF00.10805@tds.net> References: <9f68812f0602170728x5a1c4001i39794ca37b269cb2@mail.gmail.com> <43F5EF00.10805@tds.net> Message-ID: <9f68812f0602170808s3a2514e1n3c7bde9b168b53a3@mail.gmail.com> Oh, gee. Do I feel sheepish. I knew I had been staring at the error all along, but yet couldn't see it. Thanks!! On 2/17/06, Kent Johnson wrote: > > Chris Hallman wrote: > > > > Here is my script: > > input = file(rpath, "r") > > for line in file(rpath): > > > for file in dirList: > > filename = file.lower() > > You use the name 'file' for a global variable. This hides the builtin > function 'file'. This is a bit of a gotcha for newbies - the names of > builtins are not reserverd words, so they can be reasigned to your own > variables. Some of the names that are commonly (mis)used this way are > file, list and dict. You just have to learn not to do this. > > When you try > input = file(rpath, "r") > file contains a string value, which is not callable the way a function > is. Hence the error. > > The fix is to use a different name for your variable, e.g. 'f'. > > Also you are opening the file twice, you don't need the very first line > above. And 'input' is also the name of a builtin ;) > > For reference, here is a list of the built-in functions: > http://docs.python.org/lib/built-in-funcs.html > > > Here is the error: > > > > >pythonw -u "send_file.py" > > c:\temp\config\rtr0544.txt > > Exception in thread Thread-1: > > Traceback (most recent call last): > > File "c:\python24\lib\threading.py", line 442, in __bootstrap > > self.run() > > File "send_file.py", line 45, in run > > input = file(rpath, "r") > > TypeError: 'str' object is not callable > > OK, this is saying that you are trying to call a string object, and > strings can't be called. You call something with the () syntax. So the > thing you are trying to call is the value of the symbol 'file'. > Evidently that is a string rather than the built-in file function. > > Kent > > _______________________________________________ > 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/20060217/2ac19413/attachment.htm From mbroe at columbus.rr.com Fri Feb 17 22:57:08 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Fri, 17 Feb 2006 16:57:08 -0500 Subject: [Tutor] 'in-place' methods Message-ID: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> I think I understand this sorting-a-list 'in place' stuff, and things of that kind (reversing for example); but I am finding it very difficult to get used to, since sorting a list doesn't return the sorted list as a value, but simply does the work as a side effect. The place where it really trips me up is when I want to do something like pass a sorted list as a value in a program, say. Here is a trivial example. Say I want to define a function to always print lists in sorted form. I can't do it as follows, tho it's what I want to do intuitively: def sort_print(L): print L.sort() This is on a strict analogy to writing a function that prints strings in upper case only: def upper_print(s): print s.upper() (The fact that the second works and the first doesn't really does bug me as a newbie.) Anyway, first question: is the fact that the first doesn't work purely a function of the fact that lists are mutable? (At least I could kind of understand that, that methods work differently for objects of different types). Or is it possible to have methods like .upper() that return the result of performing the operation even for lists? Second question. Do I really have to write the sort_print() function like this: def sort_print(L): L.sort() print L i.e. first perform the operation in-place, then pass the variable? Is this the idiomatic way of doing it? Third question: is this in-place behavior of methods in effect restricted to lists, or are there other places I should be on the lookout for it? Cheers, Mike From singingxduck at gmail.com Fri Feb 17 23:30:48 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 17 Feb 2006 17:30:48 -0500 Subject: [Tutor] 'in-place' methods In-Reply-To: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> Message-ID: <43F64E98.4060800@gmail.com> Michael Broe wrote: >I think I understand this sorting-a-list 'in place' stuff, and things >of that kind (reversing for example); but I am finding it very >difficult to get used to, since sorting a list doesn't return the >sorted list as a value, but simply does the work as a side effect. > >The place where it really trips me up is when I want to do something >like pass a sorted list as a value in a program, say. > >Here is a trivial example. Say I want to define a function to always >print lists in sorted form. I can't do it as follows, tho it's what I >want to do intuitively: > >def sort_print(L): > print L.sort() > >This is on a strict analogy to writing a function that prints strings >in upper case only: > >def upper_print(s): > print s.upper() > >(The fact that the second works and the first doesn't really does bug >me as a newbie.) > >Anyway, first question: is the fact that the first doesn't work >purely a function of the fact that lists are mutable? (At least I >could kind of understand that, that methods work differently for >objects of different types). Or is it possible to have methods >like .upper() that return the result of performing the operation even >for lists? > >Second question. Do I really have to write the sort_print() function >like this: > >def sort_print(L): > L.sort() > print L > >i.e. first perform the operation in-place, then pass the variable? Is >this the idiomatic way of doing it? > >Third question: is this in-place behavior of methods in effect >restricted to lists, or are there other places I should be on the >lookout for it? > >Cheers, >Mike > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Well, to answer the specific case of l.sort(), there's a built-in that returns a sorted list - sorted(l). So to do what you want, you'd need: >>> import random # as you can see, not all operations have >>> examplelist = random.sample(range(10), 10) # non-in-place counterparts, or i would have >>> print sorted(examplelist) # used random.shuffle(range(10)) [1,2,3,4,5,6,7,8,9] Except for a few specific cases, to use a non-in-place version of an in-place operation, you'll probably have to end up writing your own, similar to the way you currently deal with l.sort(). As for why this is, I think you've hit on the answer: the default, if you will, is to perform operations in-place, to avoid the necessity of reassigning a list to it's sorted version, to give one example. However, this only works on mutable objects - you can't modify a string, because, well, strs are immutable, so performing an operation in-place is nonsense. That's why s.upper() returns a value, as opposed to modifying s. To answer your second question, in general, yes. If there isn't already a way to do it in the library, you'll have to write your own function. Btw, another in-place list operation with a non-in-place counterpart is l.reverse(), which has a few: reversed(l) and l[::-1] come to mind. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From wescpy at gmail.com Sat Feb 18 00:06:19 2006 From: wescpy at gmail.com (w chun) Date: Fri, 17 Feb 2006 15:06:19 -0800 Subject: [Tutor] 'in-place' methods In-Reply-To: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> Message-ID: <78b3a9580602171506j630a6a3dm24a50f6463591f1f@mail.gmail.com> hi mike, welcome to python. :-) your query is quite common amongst beginners, and i have actually spend some time on this topic in my courses. On 2/17/06, Michael Broe wrote: > I think I understand this sorting-a-list 'in place' stuff, and things > of that kind (reversing for example); but I am finding it very > difficult to get used to, since sorting a list doesn't return the > sorted list as a value, but simply does the work as a side effect. > > def sort_print(L): > print L.sort() > > def upper_print(s): > print s.upper() > > (The fact that the second works and the first doesn't really does bug > me as a newbie.) as i hinted to above, this confusion happens quite regularly. > Anyway, first question: is the fact that the first doesn't work > purely a function of the fact that lists are mutable? this is the primary reason. the side effect is also a reason why the sorted() BIF (built-in function) was added to Python. > Second question. Do I really have to write the sort_print() function > like this: if using sorted() doesn't work for you, then yes. > Third question: is this in-place behavior of methods in effect > restricted to lists, or are there other places I should be on the > lookout for it? since most all other Python types are immutable, no in-place operations can occur, so this is not an issue. and altho dictionaries are Python's other mutable type (ignoring sets at the moment), ordering isn't a feature of hashes/mapping types, so no one gets bitten there either. hope this helps... a little! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at freenet.co.uk Sat Feb 18 00:50:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 17 Feb 2006 23:50:58 -0000 Subject: [Tutor] 'in-place' methods References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> Message-ID: <008101c6341d$005defd0$0b01a8c0@xp> >I think I understand this sorting-a-list 'in place' stuff, and things > of that kind (reversing for example); but I am finding it very > difficult to get used to, since sorting a list doesn't return the > sorted list as a value, but simply does the work as a side effect. If its any consolation I personally think this ois one of the worst aspects of Python. Most of its features I either like or can tolerate but this one just seems insane to me. > Third question: is this in-place behavior of methods in effect > restricted to lists, or are there other places I should be on the > lookout for it? The other place where a None return seems unintuitive is in Tkinter. The layout manager methods(pack, grid etc) all return None when most folks intuitively expect them to return the widget. But I think the reason for that is that the underlying Tk code does the same. Alan G. From alan.gauld at freenet.co.uk Sat Feb 18 00:55:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 17 Feb 2006 23:55:14 -0000 Subject: [Tutor] 'in-place' methods References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> <43F64E98.4060800@gmail.com> Message-ID: <008501c6341d$99142cd0$0b01a8c0@xp> > is, I think you've hit on the answer: the default, if you will, is to > perform operations in-place, to avoid the necessity of reassigning a > list to it's sorted version, to give one example. But that isn't necessary, you could just return a reference to the sorted list, that is: x = L.sort() is identical to L.sort() x = L That is quite resource efficient and allows things l;ike print L.sort() This is the default technique in SmallTalk methods, if you don't know what else to return then return self It's a pretty good default rule IMHO. Alan G. From kent37 at tds.net Sat Feb 18 03:13:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Feb 2006 21:13:19 -0500 Subject: [Tutor] 'in-place' methods In-Reply-To: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> Message-ID: <43F682BF.3070005@tds.net> Michael Broe wrote: > I think I understand this sorting-a-list 'in place' stuff, and things > of that kind (reversing for example); but I am finding it very > difficult to get used to, since sorting a list doesn't return the > sorted list as a value, but simply does the work as a side effect. > > The place where it really trips me up is when I want to do something > like pass a sorted list as a value in a program, say. > > Anyway, first question: is the fact that the first doesn't work > purely a function of the fact that lists are mutable? (At least I > could kind of understand that, that methods work differently for > objects of different types). Or is it possible to have methods > like .upper() that return the result of performing the operation even > for lists? list.sort() certainly could have been written to return the list as well as sort in place. It was an intentional design decision not to do this - mutating methods all return None by choice. I think the reasoning is - The current situation causes errors when you think the mutating methods will return the object being mutated, but instead they return None. These errors show up quickly and are easily found. - If the mutating methods also returned a value, it would be possible to write code thinking that they are *not* mutating - for example your attempt to print a sorted list - but this code would have subtle side effects that could lead to hard-to-find bugs. I think I have that right... Ruby has an interesting approach to this - the names of mutating methods end with !. So it would be list.sort!() which gives a strong cue to what is happening. Kent From garcia.servando at gmail.com Sat Feb 18 05:01:32 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Fri, 17 Feb 2006 22:01:32 -0600 Subject: [Tutor] MySQLdb update Message-ID: <43F69C1C.1010907@gmail.com> Here is an update concerning my MySQLdb issue.( unable to insert data into database using Python and MySQLdb) I have tested the scripts that I posted here on both my Mac and Linux machines the script functioned as expected, ran without error and inserted data into database. It is my conclusion that there is something wrong with my python/MySQLdb configuration on my windows machine. My present course of action is to uninstall python and MySQldb. Reinstall both and try again. From ml.cyresse at gmail.com Sat Feb 18 06:34:13 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 18 Feb 2006 18:34:13 +1300 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: <43E887D6.3010500@tds.net> References: <43E72ED5.7040805@tds.net> <43E887D6.3010500@tds.net> Message-ID: Hi, Just coming back to the server end of things. Kent, could I please ask you to confirm that I'm not doing anything abnormal with the ThreadingMixIn? The code is here at rafb: http://www.rafb.net/paste/results/915JVm90.html Basically, when I test it using a script to generate the datagrams via localhost, the server misses anywhere between 200 - 400 datagrams out of 1041. As my appn will be receiving packets over a LAN, I've stuck time.sleep() in the packet generator with a delay of 5ms to simulate LAN latency, and the server copes fine, so no doubt I'm worrying needlessly, but I just want to check that I am using the Thread mix in correctly. Just refined my tests down, at a delay of 2.5ms, all packets are received, at 2ms, 40-50 are missed. How I'm testing will likely never occur in production use, I'm generating a continuous stream of packets via loopback, production will be sporadic packets via network or loopback, but I'm just being paranoid. Much thanks, Liam Clarke On 2/8/06, Kent Johnson wrote: > Liam Clarke wrote: > > On 2/7/06, Kent Johnson wrote: > > > >>Liam Clarke wrote: > >> > >>>Hi all, > >>> > >>>About to embark on my first foray into threading, and rather unsure of > >>>initial approach. I have a basic UDPServer from SocketServer running > >>>using serve_forever(). I'd like to stick this in a thread where it can > >>>endlessly loop waiting for incoming packets, and pushing the received > >>>data into a list where it can be retrieved and operated on by another > >>>thread, until such time as the controlling app terminates it. > >> > >>Threaded servers are supported by the standard library. Instead of using > >>UDPServer use this class: > >> class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass > >> > >>Then your request handler will be called in a separate thread. You don't > >>need to queue the requests yourself, the server will create the thread > >>and dispatch to it when a request is received. > >> > >>Kent > > > > Ah... so then calling serve_forever() won't block? > > It will still block, but your request handler will be called in a new > thread for each request. > > > > My current code, which illustrates what I'm attempting can be found > > here - http://www.rafb.net/paste/results/oIqI3Q11.html > > This is probably fine. You will only be able to handle one request at a > time but the request handling is fast - just read the data and drop it > in the Queue - so that may well be OK. You could also change it to use > ThreadingUDPServer leaving everything else the same - this would allow > multiple simultaneous connections. > > With your design, you will process the requests one at a time in the > data_cruncher and you need only one database connection. > > An alternate design is to use ThreadingUDPServer and have the request > handler do the data crunching and database access. Each handler would > have its own database connection. The advantage of this would be to have > multiple threads of crunching and database access running at one time > which *may* allow faster throughput. > > Yet another alternative would be to have a thread pool pulling requests > from the Queue. This gives you better control over the number of worker > threads and would let you persist the database connection for each > worker. You can find several recipes for thread pools in the online > Python cookbook. > > HTH > Kent > > > > > Basically, the server isn't the main focus, what I'm aiming for looks > > similar to this > > > > server-----Queue--data_cruncher--MySQLconnection > > server---/ / > > server-/ / > > server -/ > > > > So basically having data_cruncher to crunch whatever data there is in > > the queue and send it off to the database is the priority. I'm having > > trouble with SocketServer, need to do some more experimenting, so I'll > > get back to it. > > > > Regards, > > > > Liam Clarke > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Feb 18 10:38:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Feb 2006 09:38:15 -0000 Subject: [Tutor] My web site crashed Message-ID: <00b301c6346f$0b398110$0b01a8c0@xp> My web site has died, only the front page is showing, anything beyond that is showing empty file warnings. Unfortunately their ftp server is also dead so I can't upload replacements yet. Apologies to users but its in the hands of my ISP. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Sat Feb 18 04:09:05 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 17 Feb 2006 22:09:05 -0500 (Eastern Standard Time) Subject: [Tutor] Need to write a python and call it within a python main program Message-ID: <43F68FD1.000003.00212@YOUR-4105E587B6> I need to write a function that modifies its 4 imput values, a,b,c,d according to the following rules. set j = 8 * mod(a,2) + 4 * mod(b,2) + 2 * mod(c,2) + mod(d,2) if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 if j = 1, a,b,c,d = -1,-1,-1,-1 if j = 2, a,b,c,d = a,b/2,c,d/2 if j = 3, a,b,c,d = a,(a+b)/2,c,(d-c)/2 if j = 4, a,b,c,d = a,b,c/2,d/2 if j = 5, a,b,c,d = a,b,(a+c)/2,(d-b)/2 if j = 6, a,b,c,d = b,a,d,c if j = 7, a,b,c,d = b,a,d,c if j = 8, a,b,c,d = -1,-1,-1,-1 if j = 9, a,b,c,d = 2*a,a+b,a+c,(d-a-b-c)/2 if j = 10, a,b,c,d = b,a,d,c if j = 11, a,b,c,d = 2*a,a+b,c,(d-c)/2 if j = 12, a,b,c,d = b,a,d,c if j = 13, a,b,c,d = 2*a,b,a+c,(d-b)/2 if j = 14, a,b,c,d = b,a,d,c if j = 15, a,b,c,d = a,a+b,a+c,d-a-b-c I also need to find out how to write the main program that calls this function repeatedly, testing the output values for the solution to the equation. Kermit < kermit at polaris.net > From broek at cc.umanitoba.ca Sat Feb 18 13:04:28 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 18 Feb 2006 06:04:28 -0600 Subject: [Tutor] 'in-place' methods In-Reply-To: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> Message-ID: <43F70D4C.2070402@cc.umanitoba.ca> Michael Broe said unto the world upon 17/02/06 03:57 PM: > Second question. Do I really have to write the sort_print() function > like this: > > def sort_print(L): > L.sort() > print L > > i.e. first perform the operation in-place, then pass the variable? Is > this the idiomatic way of doing it? Hi Michael, others have answered what you asked; I thought I'd try to head off a potential problem for you. Perhaps you've seen this already, but since you are wrapping the print in a function, I suspect you want the original list to be unmodified. Thus, compare: >>> def sort_print1(a_list): a_list.sort() print a_list >>> def sort_print2(a_list): t = list(a_list) t.sort() print t >>> list1 = ["sort_print1", "mutates", "the", "original"] >>> list2 = ["sort_print2", "doesn't", "mutate", "the", "original"] >>> sort_print1(list1) ['mutates', 'original', 'sort_print1', 'the'] >>> list1 ['mutates', 'original', 'sort_print1', 'the'] >>> sort_print2(list2) ["doesn't", 'mutate', 'original', 'sort_print2', 'the'] >>> list2 ['sort_print2', "doesn't", 'mutate', 'the', 'original'] >>> HTH, Brian vdB From oztriking at hotmail.com Sat Feb 18 13:11:47 2006 From: oztriking at hotmail.com (John Connors) Date: Sat, 18 Feb 2006 23:11:47 +1100 Subject: [Tutor] G'day In-Reply-To: <002e01c633a9$3279f1e0$0b01a8c0@xp> Message-ID: G'day, Thanks to the people who replied, I only found them today and hopefully I didn't miss any. For some reason hotmail was sending them to junk even though it allowed the 1st message through and I had added tutor at python.org to my contact list. Should be sorted now I hope! > > print "Hello, World!" > > > > print ' 'Goodbye, World!" > >If you are referring to the bit on page 25 it is the same style of >quote in both examples in my copy of the book. Are you sure >its different? Or are you looking at another page? It was a library book and I have taken it back, there was typos all through it. I figured out that most of the syntax errors I was getting were from incorrect indentation. I knew indentation was important in python but I didn't realise it would return a syntax error if it was wrong. Not the authors fault BTW, just errors in the printing I think. I'm now using an ebook I found called Dive Into Python. I much prefer using a book so I can duck back a few pages to refresh my memory and reading on the monitor is a real pain. It seems an excellent reference though so I'll get around to printing it out sooner or latter (when the Mrs isn't here so she won't complain about me wasting ink and paper). John _________________________________________________________________ realestate.com.au: the biggest address in property http://ninemsn.realestate.com.au From kent37 at tds.net Sat Feb 18 13:35:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Feb 2006 07:35:53 -0500 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: References: <43E72ED5.7040805@tds.net> <43E887D6.3010500@tds.net> Message-ID: <43F714A9.3000604@tds.net> Liam Clarke wrote: > Hi, > > Just coming back to the server end of things. Kent, could I please ask > you to confirm that I'm not doing anything abnormal with the > ThreadingMixIn? The code is here at rafb: > http://www.rafb.net/paste/results/915JVm90.html > > Basically, when I test it using a script to generate the datagrams via > localhost, the server misses anywhere between 200 - 400 datagrams out > of 1041. I don't have time for a detailed response but it looks OK except ThreadingMixin needs to be the first base class because it overrides a method of UDPServer. It turns out there is a class SocketServer.ThreadingUDPServer that does this. Also I'm surprised the program stays running - ISTM with the server thread marked daemon and the main thread exiting the program should exit... Kent From python-tutor at toddmaynard.com Sat Feb 18 14:12:12 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sat, 18 Feb 2006 08:12:12 -0500 Subject: [Tutor] G'day In-Reply-To: References: Message-ID: <200602180812.12377.python-tutor@toddmaynard.com> John, Just as an FYI, Dive into Python is available in printed form. The http://diveintopython.org website has a link to it on Amazon.com. It might be cheaper than printing it out yourself.. --Todd Maynard -- The world is coming to an end ... SAVE YOUR BUFFERS!!! On Saturday 18 February 2006 07:11, John Connors wrote: > G'day, > > Thanks to the people who replied, I only found them today and hopefully I > didn't miss any. For some reason hotmail was sending them to junk even > though it allowed the 1st message through and I had added tutor at python.org > to my contact list. Should be sorted now I hope! > > > > print "Hello, World!" > > > > > > print ' 'Goodbye, World!" > > > >If you are referring to the bit on page 25 it is the same style of > >quote in both examples in my copy of the book. Are you sure > >its different? Or are you looking at another page? > > It was a library book and I have taken it back, there was typos all through > it. I figured out that most of the syntax errors I was getting were from > incorrect indentation. I knew indentation was important in python but I > didn't realise it would return a syntax error if it was wrong. Not the > authors fault BTW, just errors in the printing I think. > > I'm now using an ebook I found called Dive Into Python. I much prefer using > a book so I can duck back a few pages to refresh my memory and reading on > the monitor is a real pain. It seems an excellent reference though so I'll > get around to printing it out sooner or latter (when the Mrs isn't here so > she won't complain about me wasting ink and paper). > > John > > _________________________________________________________________ > realestate.com.au: the biggest address in property > http://ninemsn.realestate.com.au > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From garcia.servando at gmail.com Sat Feb 18 17:19:11 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Sat, 18 Feb 2006 10:19:11 -0600 Subject: [Tutor] MySQLdb: at a complete loss Message-ID: <43F748FF.5030901@gmail.com> Hello List I am at a complete loss. Here is a recap, just to be clear, I have been unable insert into a database using MySQLdb. I can only view the database. My current configuration: 1. Windows XP 2. Python 2.4.2 3 MySQLdb current version 4. mysql 5.0.18-nt 5. DEV-c++ current version. My last script was very sloppy here is my current version #!/usr/bin/python import MySQLdb,pdb #pdb.set_trace() try: db=MySQLdb.connect(host='localhost',user='root',passwd='081300',db='tut') cursor=db.cursor() name = raw_input("Please enter a Name: ") color =raw_input("Please enter a Color: ") cursor.execute("""INSERT INTO horses(name,color) VALUES("%s","%s")"""%(name,color)) cursor.close() except MySQLdb.OperationalError,message: errorMessage ='Error %d:n %s'%(message[0],message[1]) print errorMessage this script runs without error and does not affect the database in any manner. The database does exist. User/Password are valid. I have run the above script , unchanged, on both Macintosh and Ubuntu with success. From wescpy at gmail.com Sat Feb 18 18:33:22 2006 From: wescpy at gmail.com (w chun) Date: Sat, 18 Feb 2006 09:33:22 -0800 Subject: [Tutor] MySQLdb: at a complete loss In-Reply-To: <43F748FF.5030901@gmail.com> References: <43F748FF.5030901@gmail.com> Message-ID: <78b3a9580602180933y441449cam7e5d5f66a4124894@mail.gmail.com> On 2/18/06, Servando Garcia wrote: > Hello List > I am at a complete loss. Here is a recap, just to be clear, I have > been unable insert into a database using MySQLdb. I can only view the > database. servando, sorry to hear about these problems. it seems highly unlikely that it is your script that is not working (esp since you have it running on Ubuntu and MacOSX). have you tried to do a manual insert from the msql cmd from a DOS command window? i'm curious as to whether that works. if it does, then i would further pinpoint that the problem lies in the mySQLdb adapter somewhere, otherwise we're still at the same place. hope this helps, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Feb 18 19:06:00 2006 From: wescpy at gmail.com (w chun) Date: Sat, 18 Feb 2006 10:06:00 -0800 Subject: [Tutor] 'in-place' methods In-Reply-To: <43F70D4C.2070402@cc.umanitoba.ca> References: <8460F81E-A67B-4592-B502-1A331543EEDB@columbus.rr.com> <43F70D4C.2070402@cc.umanitoba.ca> Message-ID: <78b3a9580602181006k2e9ffcd4i1199068f695aef87@mail.gmail.com> > Perhaps you've seen this already, but since you are wrapping the print > in a function, I suspect you want the original list to be unmodified. > Thus, compare: > > >>> def sort_print1(a_list): > a_list.sort() > print a_list > > > >>> def sort_print2(a_list): > t = list(a_list) > t.sort() > print t > > >>> list1 = ["sort_print1", "mutates", "the", "original"] > >>> list2 = ["sort_print2", "doesn't", "mutate", "the", "original"] > >>> sort_print1(list1) > ['mutates', 'original', 'sort_print1', 'the'] > >>> list1 > ['mutates', 'original', 'sort_print1', 'the'] > >>> sort_print2(list2) > ["doesn't", 'mutate', 'original', 'sort_print2', 'the'] > >>> list2 > ['sort_print2', "doesn't", 'mutate', 'the', 'original'] this is a slight tangent to mike's original question but is *another* gotcha for newbies who are swimming in the new waters of Python objects. and that is, that although Brian appears to make a copy of the original list in sort_print2() using the list() factory built-in function, it is only (called) a "shallow copy." bear in mind that if you use list() to generate a(nother) list object, you are only copying references or aliases to the objects in the original data structure (here it is also a list), whether mutable or otherwise; but if it is the former, then be aware that you are NOT MAKING A COPY of those mutable objects, just references. those objects can then be modified whether you access the original or the one in the shallow copy: >>> def sort_print2(a_list): t = list(a_list) t[-1][-1] = 'Yes' t.sort() print t >>> foo = [ 'Have I been trumped?', 'No' ] >>> myList = [ 456, 'abc', 1.23, foo ] >>> sort_print2(myList) [1.23, 456, ['Have I been trumped?', 'Yes'], 'abc'] >>> myList [456, 'abc', 1.23, ['Have I been trumped?', 'Yes']] >>> see how i'm modifying 't' and not 'a_list'. changing either one will have the exact same outcome because they both contain a reference to the same object 'foo'. in other words, no copy of 'foo' was made, so that's why it's affected. if you really need a complete copy (of objects *and* the ones contained within recursively), then read up on the deepcopy() function of the copy module. (caveat tho, that is doesn't copy EVERYTHING, but enough to make you feel like it does. for example, it doesn't copy files, functions/methods, stack frames, etc.) cheers, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From brian at daviesinc.com Sat Feb 18 18:47:40 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 18 Feb 2006 12:47:40 -0500 Subject: [Tutor] MySQLdb: at a complete loss In-Reply-To: <43F748FF.5030901@gmail.com> References: <43F748FF.5030901@gmail.com> Message-ID: <43F75DBC.1060409@daviesinc.com> Servando Garcia wrote: > Hello List > I am at a complete loss. Here is a recap, just to be clear, I have > been unable insert into a database using MySQLdb. I can only view the > database. > My current configuration: > 1. Windows XP > 2. Python 2.4.2 > 3 MySQLdb current version > 4. mysql 5.0.18-nt > 5. DEV-c++ current version. > > My last script was very sloppy here is my current version > #!/usr/bin/python > import MySQLdb,pdb > > #pdb.set_trace() > try: > > db=MySQLdb.connect(host='localhost',user='root',passwd='081300',db='tut') > cursor=db.cursor() > name = raw_input("Please enter a Name: ") > color =raw_input("Please enter a Color: ") > cursor.execute("""INSERT INTO horses(name,color) > VALUES("%s","%s")"""%(name,color)) > cursor.close() I might suggest single quoting the values as in return = cursor.execute("""INSERT INTO horses(name,color) VALUES('%s','%s')"""%(name,color)) print return # get a return value of the operation and print it - helps in debuugging > > except MySQLdb.OperationalError,message: > errorMessage ='Error %d:n %s'%(message[0],message[1]) > print errorMessage > > this script runs without error and does not affect the database in any > manner. The database does exist. User/Password are valid. I have run > the above script , unchanged, on both Macintosh and Ubuntu with success. > I notice that some of your activities have no return value - these are highly useful in debugging- typically I will capture return values into a list or dict so I can examine them after the script executes, or empty them out after wards if I set debugging = off in my scripts. Bri! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:43f74a3f294671847412610! > > From benmarkwell at gmail.com Sat Feb 18 20:00:14 2006 From: benmarkwell at gmail.com (benmarkwell at gmail.com) Date: Sat, 18 Feb 2006 14:00:14 -0500 Subject: [Tutor] First program -- would like comments and criticisms Message-ID: Here is my first stab at putting together a working program. It is a glossary that you can add words and definitions to, or look up words and their definitions. There are a couple of problems here and there, but it basically does what I set out for it to do. All comments and criticisms are welcome. I attached the data file that goes with the script in case anybody wanted to actually run it, so they wouldn't have to make their own dictionary file to access. Thanks in advance. Ben # File gloss.py # Author Ben Markwell # Date Feb 2006 ''' This script is a glossary in which you can input definitions and look up words and their definitions. ''' import cPickle as p import textwrap as t f = file(r'g:\dev\python\data\gloss.data', 'r') gloss = p.load(f) #---Def Functions---#000000#FFFFFF-------------------------------------------------- def findWord(): words = gloss.keys() letter = raw_input('That word is not in the glossary. \nWhat is the first letter of the word? ') for x in range(len(words)): if words[x].startswith(letter): print words[x] # Get word and check if it is in the glossary then print the def. def getWordDef(): word = raw_input('enter a word: ') if gloss.has_key(word): line = gloss.get(word) lineWrap(word) else: findWord() word = raw_input('Enter the word: ') line = gloss.get(word) lineWrap(word) # Print a menu of choices to the screen def printMenu(): print '1 - Enter a word and definition.' print '2 - Look up a word.' print '3 - Quit' print # Wrap the output so it fits the screen nicely def lineWrap(word): line = gloss.get(word) if len(line) < 81: print line else: wrapLines = t.wrap(line, 80) for line in range(len(wrapLines)): print wrapLines[line] # End of Def Functions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx num = '0' printMenu() while num != '3': num = raw_input('What do you want to do? ') if num == '1': # if 1 in choice enter a word to look up word = raw_input('Enter word: ') _def = raw_input('Enter definition: ') gloss[word] = _def elif num == '2': # if 2 is the choice enter word and def getWordDef() elif num == '3': # if 3 is the choice, save changes and quit newGloss = file(r'g:\dev\python\data\gloss.data', 'w') p.dump(gloss, newGloss) newGloss.close() f.close() print print 'Goodbye' break else: printMenu() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060218/0ffc85e6/attachment.htm From garcia.servando at gmail.com Sat Feb 18 20:16:27 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Sat, 18 Feb 2006 13:16:27 -0600 Subject: [Tutor] MySQLdb: at a complete loss In-Reply-To: <78b3a9580602180933y441449cam7e5d5f66a4124894@mail.gmail.com> References: <43F748FF.5030901@gmail.com> <78b3a9580602180933y441449cam7e5d5f66a4124894@mail.gmail.com> Message-ID: <43F7728B.4070902@gmail.com> w chun wrote: > On 2/18/06, Servando Garcia wrote: > >> Hello List >> I am at a complete loss. Here is a recap, just to be clear, I have >> been unable insert into a database using MySQLdb. I can only view the >> database. >> > > > servando, > > sorry to hear about these problems. it seems highly unlikely that it > is your script that is not working (esp since you have it running on > Ubuntu and MacOSX). > > have you tried to do a manual insert from the msql cmd from a DOS > command window? i'm curious as to whether that works. if it does, > then i would further pinpoint that the problem lies in the mySQLdb > adapter somewhere, otherwise we're still at the same place. > > hope this helps, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2006,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > > Yes, I can insert from a mysql command line. I was thinking that it may be the lack of a Microsoft c++ compiler. I read some where on the Internet that MySQLdb needed Microsoft C++ ( http://mail.zope.org/pipermail/zope-db/2002-August/000826.html ). Surely this could not be the problem. From alan.gauld at freenet.co.uk Sat Feb 18 20:26:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Feb 2006 19:26:52 -0000 Subject: [Tutor] Need to write a python and call it within a python mainprogram References: <43F68FD1.000003.00212@YOUR-4105E587B6> Message-ID: <003a01c634c1$45b685c0$0b01a8c0@xp> > I need to write a function that modifies its 4 imput values, > a,b,c,d according to the following rules. > > ...snipped rules ... > > I also need to find out how to write the main program that calls this > function repeatedly, testing the output values for the solution to the > equation. Sounds like an interesting problem. How are you going about solving it? Are you hitting some kind of problem? I'm not sure if you are just telling us about your project for future reference or whether there is a specific question to be answered? Alan G. From dyoo at hkn.eecs.berkeley.edu Sat Feb 18 20:43:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Feb 2006 11:43:44 -0800 (PST) Subject: [Tutor] Need to write a python and call it within a python main program In-Reply-To: <43F68FD1.000003.00212@YOUR-4105E587B6> Message-ID: > > I need to write a function that modifies its 4 imput values, > a,b,c,d according to the following rules. [program description cut] > I also need to find out how to write the main program that calls this > function repeatedly, testing the output values for the solution to the > equation. Hi Kermit, ... this looks like a crazy program, but oh well. *grin* So... what do you need help on? I mean this in all seriousness: you have to tell us what you're having trouble with, because otherwise, we can't do much. We want to help you so that you can write your program, but we don't want to write the program for you, as this looks way too close to some homework problem (even if it looks absolutely bizarre to me.) Do you already have programming experience in another language? Do you already know how to write functions? Do you already know about conditionals? Do you know how to test a function? I really can't pinpoint what problems you have yet, so you're going to have to tell us more. If you don't have programming experience yet, the tutorials at: http://wiki.python.org/moin/BeginnersGuide http://wiki.python.org/moin/BeginnersGuide/NonProgrammers may be helpful to you. Good luck to you. From tiagosaboga at terra.com.br Sat Feb 18 20:51:26 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Sat, 18 Feb 2006 17:51:26 -0200 Subject: [Tutor] unable to insert data into database In-Reply-To: <43F5E885.5000901@hagen-partner.de> References: <43F5CA55.7030405@gmail.com> <43F5E885.5000901@hagen-partner.de> Message-ID: <200602181751.27198.tiagosaboga@terra.com.br> Em Sex 17 Fev 2006 13:15, Wolfram Kraus escreveu: > Wolfram Kraus wrote: [SNIP] > Sorry for asking the obvious (Database/Table exists)! You are missing > > db.commit() > db.close() > > in your code. IIRC auto-commit was switched of for MySQLdb long time ago. Hi! I'm Tiago, from Brazil, I'm new to this list and, err, I'm getting into python. I'm very interested on the mysql module, and this thread sounds interesting. I've tried pretty much the same code from the original code, and I don't need to commit changes. All I have is a cursor.close(), and it works ok. So, I think it have a sort of auto-commit. But I was wondering if it's the same behavior for all database engines, as I've read somewhere on the mysql reference that Innodb tables need a commit command. And it could even be an explanation to the different behavior observed by Servando: if you create different sorts of tables on windows, mac and linux, you'll have different behaviors... I hope you'll understand my poor english... Tiago Saboga. From dyoo at hkn.eecs.berkeley.edu Sat Feb 18 20:51:45 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Feb 2006 11:51:45 -0800 (PST) Subject: [Tutor] MySQLdb: at a complete loss In-Reply-To: <43F748FF.5030901@gmail.com> Message-ID: > db=MySQLdb.connect(host='localhost',user='root',passwd='081300',db='tut') > cursor=db.cursor() > name = raw_input("Please enter a Name: ") > color =raw_input("Please enter a Color: ") > cursor.execute("""INSERT INTO horses(name,color) > VALUES("%s","%s")"""%(name,color)) ^^^^^^^^^ Hi Servando, Don't do this: don't try to interpolate the variables yourself, but pass the parameters as part of the execution call: http://mail.python.org/pipermail/tutor/2003-April/022010.html > this script runs without error and does not affect the database in any > manner. The database does exist. User/Password are valid. I have run > the above script , unchanged, on both Macintosh and Ubuntu with success. Are you familiar with database transactions? Look at the description of close() in the Python DB API: """Close the connection now (rather than whenever __del__ is called)... Note that closing a connection without committing the changes first will cause an implicit rollback to be performed.""" (http://www.python.org/peps/pep-0249.html) Does this last sentence ring some bells? *grin* Newest versions of the MySQLdb module do NOT autocommit anymore. You have to commit at the end or else you're not going to see any mutation affect the database: every change you make will just roll back. Good luck! From dyoo at hkn.eecs.berkeley.edu Sat Feb 18 21:00:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Feb 2006 12:00:38 -0800 (PST) Subject: [Tutor] unable to insert data into database In-Reply-To: <200602181751.27198.tiagosaboga@terra.com.br> Message-ID: > I'm Tiago, from Brazil, I'm new to this list and, err, I'm getting into > python. Hi Tiago, Welcome aboard! > I'm very interested on the mysql module, and this thread sounds > interesting. I've tried pretty much the same code from the original > code, and I don't need to commit changes. All I have is a > cursor.close(), and it works ok. So, I think it have a sort of > auto-commit. Yes, older versions of MySQLdb had autocommit behavior, because MySQL at some distant, medieval epoch did not support transactions. MySQL finally does with InnoDB tables, and so the MySQLdb module was changed to support that transaction feature. > But I was wondering if it's the same behavior for all database engines, > as I've read somewhere on the mysql reference that Innodb tables need a > commit command. And it could even be an explanation to the different > behavior observed by Servando: if you create different sorts of tables > on windows, mac and linux, you'll have different behaviors... Yes, it's probably that problem. Either his tables are MyISAM in some places and not in others, or he has an old version of MySQLdb installed in one place and not in another. There are at least two possible ways of seeing what he's getting. Although his Python program is the same, the environment around his program is different, and so he has to account for these free-floating conditions. He should be using conn.commit() for the code to really work, according to the Python DB API. > I hope you'll understand my poor english... Don't worry! You write excellent English. From dyoo at hkn.eecs.berkeley.edu Sat Feb 18 21:04:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Feb 2006 12:04:11 -0800 (PST) Subject: [Tutor] Need to write a python and call it within a python main program (fwd) Message-ID: ---------- Forwarded message ---------- Date: Sat, 18 Feb 2006 15:02:47 -0500 (Eastern Standard Time) From: Kermit Rose To: Danny Yoo Subject: Re: [Tutor] Need to write a python and call it within a python main program From: Danny Yoo Date: 02/18/06 14:44:20 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] Need to write a python and call it within a python main program > > I need to write a function that modifies its 4 imput values, > a,b,c,d according to the following rules. [program description cut] > I also need to find out how to write the main program that calls this > function repeatedly, testing the output values for the solution to the > equation. Hi Kermit, .... this looks like a crazy program, but oh well. *grin* So... what do you need help on? ******* I need help on the SYNTAX of Python I have programming experience in Fortran and a little bit of C. ******** I mean this in all seriousness: you have to tell us what you're having trouble with, because otherwise, we can't do much. We want to help you so that you can write your program, but we don't want to write the program for you, as this looks way too close to some homework problem (even if it looks absolutely bizarre to me.) **************** Right. I understand the prohibition against doing student's homework for them. I don't know how to get started. I've downloaded Python, and have used the idle as a desk calculator, but do not yet know how to write programs in it. ****** Do you already have programming experience in another language? Do you already know how to write functions? ********************* I do not know how to write functions in Python. I know how to write functions in Fortran. ****************** Do you already know about conditionals? ******************* I know about the == relational operator. *************** Do you know how to test a function? ************************* Do you mean (1) call the function with test values to see if it performs the way you want it to? (2) something else that is Python related that I know nothing about? ********************* I really can't pinpoint what problems you have yet, so you're going to have to tell us more. ********************** Yes. I will do the best I can. ***************** If you don't have programming experience yet, the tutorials at: http://wiki.python.org/moin/BeginnersGuide http://wiki.python.org/moin/BeginnersGuide/NonProgrammers may be helpful to you. ******** Thanks. I have downloaded the second one. The first one looked very useful also, but I would like it to have more examples. Please help me with the syntax. I don't know how to tell python to run a main program and use subroutines. I don't know how to make those subroutines available to the main program. Kermit < kermit at polaris.net > From dyoo at hkn.eecs.berkeley.edu Sat Feb 18 21:18:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Feb 2006 12:18:05 -0800 (PST) Subject: [Tutor] Need to write a python and call it within a python main program (fwd) In-Reply-To: Message-ID: > I need help on the SYNTAX of Python > > I have programming experience in Fortran and a little bit of C. Ah, ok; let's see if we can transfer some concepts from your previous experience into Python. Just as a note: please use your email client's "Reply to All" feature so that our correspondence stays on the Python-tutor mailing list. The idea is that if I say something that is inaccurate or incomplete, the other helpers can come and compensate for my weaknesses. > I don't know how to get started. > > I've downloaded Python, and have used the idle as a desk calculator, but > do not yet know how to write programs in it. You may want to do a quick run-through of: http://www.python.org/doc/tut/ which will help give you a better sense of the syntax of the language. > Do you already know about conditionals? > > ******************* > > I know about the == relational operator. > > *************** Python has a familiar control-flow syntax for branches in the 'if' statement. For example, here is an interactive session that shows how one can use it for a simple case-analysis: ###### >>> def is_even(n): ... if n % 2 == 0: ## % is the modulo operator ... return "yes" ... else: ... return "no" ... >>> is_even(42) 'yes' >>> is_even(13) 'no' ###### This is a function that takes an argument 'n', and returns either a 'yes' or 'no' output. If you look through a tutorial like the official Python tutorial, you should see more usage of the "if" statement to handle an arbitrary number of cases. > Do you know how to test a function? > > Do you mean > (1) call the function with test values to see if it performs the way you > want it to? > (2) something else that is Python related that I know nothing about? #1. I was running under the assumption that you hadn't programmed before. But since you have, I think you know how to test a program so that you have a reasonable idea of how well a program is doing what you want. > Please help me with the syntax. I don't know how to tell python to run > a main program and use subroutines. I don't know how to make those > subroutines available to the main program. I think the best thing I can do is point you to tutorials that you can use to get a handle for the syntax. There is: http://www.python.org/doc/tut/ as I pointed to earlier, but there's also: http://wiki.python.org/moin/BeginnersGuide/Programmers which are tutorials that are targetted toward people who already know how to program. If you have more questions, please feel free to email 'tutor at python.org'. Good luck! From kermit at polaris.net Sat Feb 18 21:40:21 2006 From: kermit at polaris.net (Kermit Rose) Date: Sat, 18 Feb 2006 15:40:21 -0500 (Eastern Standard Time) Subject: [Tutor] Need to write a python and call it within a python main program (fwd) References: Message-ID: <43F78635.00001F.03420@YOUR-4105E587B6> From: Danny Yoo Date: 02/18/06 15:18:14 To: Kermit Rose Cc: Tutor Subject: Re: [Tutor] Need to write a python and call it within a python main program (fwd) Just as a note: please use your email client's "Reply to All" feature so that our correspondence stays on the Python-tutor mailing list. The idea is that if I say something that is inaccurate or incomplete, the other helpers can come and compensate for my weaknesses. ********* ok *************** > *************** Python has a familiar control-flow syntax for branches in the 'if' statement. For example, here is an interactive session that shows how one can use it for a simple case-analysis: ###### >>> def is_even(n): .... if n % 2 == 0: ## % is the modulo operator .... return "yes" .... else: .... return "no" .... >>> is_even(42) 'yes' >>> is_even(13) 'no' ###### ****** This is a very good example. Using it, I translate my pseudo code set j = 8 * mod(a,2) + 4 * mod(b,2) + 2 * mod(c,2) + mod(d,2) if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 if j = 1, a,b,c,d = -1,-1,-1,-1 if j = 2, a,b,c,d = a,b/2,c,d/2 if j = 3, a,b,c,d = a,(a+b)/2,c,(d-c)/2 if j = 4, a,b,c,d = a,b,c/2,d/2 if j = 5, a,b,c,d = a,b,(a+c)/2,(d-b)/2 if j = 6, a,b,c,d = b,a,d,c if j = 7, a,b,c,d = b,a,d,c if j = 8, a,b,c,d = -1,-1,-1,-1 if j = 9, a,b,c,d = 2*a,a+b,a+c,(d-a-b-c)/2 if j = 10, a,b,c,d = b,a,d,c if j = 11, a,b,c,d = 2*a,a+b,c,(d-c)/2 if j = 12, a,b,c,d = b,a,d,c if j = 13, a,b,c,d = 2*a,b,a+c,(d-b)/2 if j = 14, a,b,c,d = b,a,d,c if j = 15, a,b,c,d = a,a+b,a+c,d-a-b-c into >>> def trans01(a,b,c,d): .... j = 8 * a%2 + 4 * b%2 + 2 * c%2 + d%2 .... if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 .... if j = 1, a,b,c,d = -1,-1,-1,-1 .... if j = 2, a,b,c,d = a,b/2,c,d/2 .... if j = 3, a,b,c,d = a,(a+b)/2,c,(d-c)/2 .... if j = 4, a,b,c,d = a,b,c/2,d/2 .... if j = 5, a,b,c,d = a,b,(a+c)/2,(d-b)/2 .... if j = 6, a,b,c,d = b,a,d,c .... if j = 7, a,b,c,d = b,a,d,c .... if j = 8, a,b,c,d = -1,-1,-1,-1 .... if j = 9, a,b,c,d = 2*a,a+b,a+c,(d-a-b-c)/2 .... if j = 10, a,b,c,d = b,a,d,c .... if j = 11, a,b,c,d = 2*a,a+b,c,(d-c)/2 .... if j = 12, a,b,c,d = b,a,d,c .... if j = 13, a,b,c,d = 2*a,b,a+c,(d-b)/2 .... if j = 14, a,b,c,d = b,a,d,c .... if j = 15, a,b,c,d = a,a+b,a+c,d-a-b-c IndentationError: expected an indented block (, line 2) >>> >>> >>> Why did I get this error message? Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060218/7c883805/attachment-0001.htm From project5 at redrival.net Sat Feb 18 21:51:31 2006 From: project5 at redrival.net (Andrei) Date: Sat, 18 Feb 2006 21:51:31 +0100 Subject: [Tutor] First program -- would like comments and criticisms In-Reply-To: References: Message-ID: benmarkwell at gmail.com wrote: > Here is my first stab at putting together a working program. It is a > glossary that you can add words and definitions to, or look up words and > their definitions. There are a couple of problems here and there, but > it basically does what I set out for it to do. All comments and > criticisms are welcome. I attached the data file that goes with the > script in case anybody wanted to actually run it, so they wouldn't have > to make their own dictionary file to access. I haven't executed it, but it seems quite good, certainly for a first working program. For small programs there's no point in overengineering, but here are some simple improvements you could look into: - place a "if __name__=="__main__":" condition at the bottom and put your program code in there (or better yet, extract it in a function and call that function after the if __name__ stuff). This way the module can also be imported. - make the location of the dictionary a 'constant' (which in Python means a variable with all-uppercase name :)). Having magic strings in code is bad practice. - the menu system could be redesigned to make it more maintenance-friendly. At this point if you want to add/modify a choice, you'd have to modify a procedure and the main code. You could instead make a dictionary mapping each possible choice (keys) to tuples containing a description and a function name. Loop over the keys and print them with the description. Once the user makes a choice, you could look up the function in the dictionary and execute it. This way adding new functionality items only means you need to add an entry to that one dictionary. - you could replace the "while num != '3':" condition with a "while True:" - the loop is interrupted anyway if '3' is selected, because of the 'break'. This way you can also remove the initialization of num. - you could extract the actual logic (the glossary) to a class with methods like "load", "save", "lookup" and separate it completely from all the user interaction. The glossary class shouldn't print/ask for user input. It's overkill for such a small program, but you could then theoretically reuse the glossary in a different application (e.g. put a webbased interface onto it, or subclass it and make a glossary which can also do multiple language translations, or use a different storage backend, etc.). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) From carroll at tjc.com Sat Feb 18 23:05:51 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 18 Feb 2006 14:05:51 -0800 (PST) Subject: [Tutor] 'in-place' methods In-Reply-To: <43F682BF.3070005@tds.net> Message-ID: On Fri, 17 Feb 2006, Kent Johnson wrote: > Ruby has an interesting approach to this - the names of mutating methods > end with !. So it would be list.sort!() which gives a strong cue to what > is happening. What a great idea! Hmm.. maybe Python could do this, too; and use some other characters like $, @ and % to indicate if a name is a reference to a plain old variable, a list, or a dictionary! From tiagosaboga at terra.com.br Sat Feb 18 23:29:33 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Sat, 18 Feb 2006 20:29:33 -0200 Subject: [Tutor] MySQLdb: at a complete loss In-Reply-To: References: Message-ID: <200602182029.34249.tiagosaboga@terra.com.br> Em S?b 18 Fev 2006 17:51, Danny Yoo escreveu: > > db=MySQLdb.connect(host='localhost',user='root',passwd='081300',db='tut') > > cursor=db.cursor() > > name = raw_input("Please enter a Name: ") > > color =raw_input("Please enter a Color: ") > > cursor.execute("""INSERT INTO horses(name,color) > > VALUES("%s","%s")"""%(name,color)) > > ^^^^^^^^^ > > Hi Servando, > > Don't do this: don't try to interpolate the variables yourself, but pass > the parameters as part of the execution call: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html It's interesting, but I'm missing something. What does it mean, a "prepared statement"? I can see *why" to use it, but not *what* it is. But wait... is it simply a difference between concatenating variables and putting them "inline" in the string? So the on the second line of code below mysql will know for sure that c is the wanted value for xname, even if it is something that should be quoted? a="select xname,sname from people where xname='"+c+"'" cursor.execute("select xname,sname from people where xname=%s", c) > > this script runs without error and does not affect the database in any > > manner. The database does exist. User/Password are valid. I have run > > the above script , unchanged, on both Macintosh and Ubuntu with success. > > Are you familiar with database transactions? Look at the description of > close() in the Python DB API: > > """Close the connection now (rather than whenever __del__ is > called)... Note that closing a connection without > committing the changes first will cause an implicit > rollback to be performed.""" > > (http://www.python.org/peps/pep-0249.html) > > Does this last sentence ring some bells? *grin* > > Newest versions of the MySQLdb module do NOT autocommit anymore. You have > to commit at the end or else you're not going to see any mutation affect > the database: every change you make will just roll back. Even with MyIsam tables, which are not transactional? Tiago. From alan.gauld at freenet.co.uk Sat Feb 18 23:49:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Feb 2006 22:49:07 -0000 Subject: [Tutor] Need to write a python and call it within a python mainprogram (fwd) References: Message-ID: <005501c634dd$86fb22e0$0b01a8c0@xp> > I know how to write functions in Fortran. > > Please help me with the syntax. I don't know how to tell python to run a > main program and use subroutines. OK, Now we have some specifics. First to make a program run just create a text file and use an extension of .py, for example myprogram.py (You can use File->New from IDLE if you like) Then from the operating system command line type C:\> python myprogram.py (Assuming you are on Windows - tell us if you are on MacOS or Linux or something else...) To define a function called f that takes a parameter of x in python use the following syntax: def f(x): return x**2 Note the colon at the end of the definition, that starts a code block. (And was why you got the error in your if statement - no colon Note the indented block of code in the function body. Both are essential. To call the function f with an argument of 4 result = f(4) > I don't know how to make those subroutines available to > the main program. Put them in the same file in the first instance. Alternatively you could put them in another file called say myfuncs.py. Then in myprog.py import the myfuncs "module" import myfuncs # note no .py result = myfuncs.f(3) Note the use of the module name in font of the function name. Try going through the tutorials, they should answer the rest of your questions but if you get stuck come back to us with any specifics Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld currently broken! :-( From alan.gauld at freenet.co.uk Sat Feb 18 23:56:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Feb 2006 22:56:53 -0000 Subject: [Tutor] Need to write a python and call it within a python mainprogram (fwd) References: <43F78635.00001F.03420@YOUR-4105E587B6> Message-ID: <005d01c634de$9c65f730$0b01a8c0@xp> > Using it, I translate my pseudo code > into >>> def trans01(a,b,c,d): .... j = 8 * a%2 + 4 * b%2 + 2 * c%2 + d%2 .... if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 .... if j = 1, a,b,c,d = -1,-1,-1,-1 .... if j = 2, a,b,c,d = a,b/2,c,d/2 IndentationError: expected an indented block (, line 2) > Why did I get this error message? Indentation is how python determines block sytructure. In C you would do: void f(int x) { /// some code here } and the {} tell C that the code between them ids the function bvody In Python a colon says a block is coming up and everything up to the next unindented line is part of it. But the indentation must be consistent (it can be as big or little as you like, but it must be consistent - 2, 3 or 4 spaces is pretty normal) In your case the body of the function had inclonsistent indentation. The other issue is in the format of your if statements: .... if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 You need to use == as in C for comparisons, unlike C you cannot do an assignment in a test. The condition must be followed by a colon. You test thus becomes: if j == 0: a,b,c,d = a/2,b/2,c/2,d/2 Note the double equals and the colon. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Sun Feb 19 00:05:36 2006 From: kermit at polaris.net (Kermit Rose) Date: Sat, 18 Feb 2006 18:05:36 -0500 (Eastern Standard Time) Subject: [Tutor] Need to write a python : Thank you very much References: <005501c634dd$86fb22e0$0b01a8c0@xp> Message-ID: <43F7A840.000005.02380@YOUR-4105E587B6> From: Alan Gauld Date: 02/18/06 17:51:17 To: Danny Yoo; Tutor Subject: Re: [Tutor] Need to write a python and call it within a pythonmainprogram (fwd) > I know how to write functions in Fortran. > > Please help me with the syntax. I don't know how to tell python to run a > main program and use subroutines. OK, Now we have some specifics. . . . Try going through the tutorials, they should answer the rest of your questions but if you get stuck come back to us with any specifics ****** Thank you very much. I might be able to write my code now. If I have more trouble, I'll get back to you with any diagnostics that I can't figure out. Thanks. Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060218/c69c97b8/attachment.htm From kermit at polaris.net Sun Feb 19 00:10:44 2006 From: kermit at polaris.net (Kermit Rose) Date: Sat, 18 Feb 2006 18:10:44 -0500 (Eastern Standard Time) Subject: [Tutor] Need to write a python and call it within a python mainprogram (fwd): Thank you very much References: <005d01c634de$9c65f730$0b01a8c0@xp> Message-ID: <43F7A974.000007.02380@YOUR-4105E587B6> From: Alan Gauld Date: 02/18/06 18:00:09 To: Kermit Rose; Danny Yoo Cc: Tutor Subject: Re: [Tutor] Need to write a python and call it within a python mainprogram (fwd) ? Indentation is how python determines block sytructure. In Python a colon says a block is coming up and everything up to the next unindented line is part of it. But the indentation must be consistent (it can be as big or little as you like, but it must be consistent - 2, 3 or 4 spaces is pretty normal) In your case the body of the function had inclonsistent indentation. The other issue is in the format of your if statements: ..... if j = 0, a,b,c,d = a/2,b/2,c/2,d/2 You need to use == as in C for comparisons, unlike C you cannot do an assignment in a test. The condition must be followed by a colon. You test thus becomes: if j == 0: a,b,c,d = a/2,b/2,c/2,d/2 Note the double equals and the colon. HTH, ***** Thank you very much! Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060218/cbb5a68d/attachment.html From alan.gauld at freenet.co.uk Sun Feb 19 01:13:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 00:13:14 -0000 Subject: [Tutor] 'in-place' methods References: Message-ID: <007401c634e9$46d05300$0b01a8c0@xp> >> Ruby has an interesting approach to this - the names of mutating methods >> end with !. So it would be list.sort!() which gives a strong cue to what > > What a great idea! Hmm.. maybe Python could do this, too; and use some > other characters like $, @ and % to indicate if a name is a reference to a > plain old variable, a list, or a dictionary! :-) But don't even joke about it. Decorators are bad enough, no more line noise in Python. If we want weird characters in our code we can just learn Perl! I assume this was intended irony Terry?.... Alan G. From ml.cyresse at gmail.com Sun Feb 19 01:15:57 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 19 Feb 2006 13:15:57 +1300 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: <43F714A9.3000604@tds.net> References: <43E72ED5.7040805@tds.net> <43E887D6.3010500@tds.net> <43F714A9.3000604@tds.net> Message-ID: Thanks Kent, I'll try swapping it around and see how it goes. As for the setDaemon, my apologies. There's a while True: if msvcrt.kbhit(): break loop afterwards, so at a keypress it exits, hence the daemon stuff. On 2/19/06, Kent Johnson wrote: > Liam Clarke wrote: > > Hi, > > > > Just coming back to the server end of things. Kent, could I please ask > > you to confirm that I'm not doing anything abnormal with the > > ThreadingMixIn? The code is here at rafb: > > http://www.rafb.net/paste/results/915JVm90.html > > > > Basically, when I test it using a script to generate the datagrams via > > localhost, the server misses anywhere between 200 - 400 datagrams out > > of 1041. > > I don't have time for a detailed response but it looks OK except > ThreadingMixin needs to be the first base class because it overrides a > method of UDPServer. It turns out there is a class > SocketServer.ThreadingUDPServer that does this. > > Also I'm surprised the program stays running - ISTM with the server > thread marked daemon and the main thread exiting the program should exit... > > Kent > > From garcia.servando at gmail.com Sun Feb 19 02:39:34 2006 From: garcia.servando at gmail.com (Servando Garcia) Date: Sat, 18 Feb 2006 19:39:34 -0600 Subject: [Tutor] MySQLdb : I finally got it to work. Message-ID: <43F7CC56.7060404@gmail.com> Hello list It seems that true understanding must , at times, be painful. Danny Yoo thank you for not just giving me the answer but rather making me work for it. Here is how I got the code to run. 1. With my configuration, I need quotes around the values that are to be placed into the database, otherwise an error is raised example: ( n= blue --> Error 1054:n Unknown column 'blue' in 'field list' ) n = raw_input("Please enter a Name: ") c =raw_input("Please enter a Color: ") cursor.execute("INSERT INTO horses(name,color) VALUES('%s','%s')"%(n,c)) 2. I can not simply pass variables in the SQL query. Interpolation is necessary. Otherwise an error is raised. n = raw_input("Please enter a Name: ") c =raw_input("Please enter a Color: ") cursor.execute("INSERT INTO horses(name,color) VALUES(n,c)" ) Error 1054:n Unknown column 'n' in 'field list' 3 To update the database I needed an .commit() ( http://www.python.org/peps/pep-0249.html ) I added db.commit() after the INSERT statement and all was well. Once again thanks to all. From ismaelgf at adinet.com.uy Sun Feb 19 02:58:10 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat, 18 Feb 2006 23:58:10 -0200 Subject: [Tutor] Proxy Message-ID: <43F7D0B2.2090105@adinet.com.uy> Hi. I been looking in the web for a Proxy which I could modify, but I can't find anything useful. Basically what I want to do is to monitor what's being loaded and modify the page if it matches certain regexps and source locations (Ie: a particular server). I found: http://xhaus.com/alan/python/proxies.html , but it doesn't seem any of those will let me do what I want. At least, not that I can tell. Any idea of where I could find a proxy that'd let me do this or which one of those could be modified? Thanks Ismael From carroll at tjc.com Sun Feb 19 06:03:07 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 18 Feb 2006 21:03:07 -0800 (PST) Subject: [Tutor] Proxy In-Reply-To: <43F7D0B2.2090105@adinet.com.uy> Message-ID: On Sat, 18 Feb 2006, Ismael Garrido wrote: > I been looking in the web for a Proxy which I could modify, but I can't > find anything useful. Twisted, maybe? http://wiki.python.org/moin/Twisted-Examples http://twistedmatrix.com/ From carroll at tjc.com Sun Feb 19 06:07:25 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 18 Feb 2006 21:07:25 -0800 (PST) Subject: [Tutor] 'in-place' methods In-Reply-To: <007401c634e9$46d05300$0b01a8c0@xp> Message-ID: On Sun, 19 Feb 2006, Alan Gauld wrote: > But don't even joke about it. It is pretty cringe-worthy, isn't it? > Decorators are bad enough, no more line noise in Python. I was actually kind of sad to see that added. It struck me as the first grafted-on feature of Python that *felt* grafted-on. Fortunately, I'm not at the level of programming that I'm ever likely to run into it, so I can safely ignore it. Another one like this: the Generics feature of Java 5. Not that I care much for Java, anyway,[1] but yech. > If we want weird characters in our code we can just learn Perl! > I assume this was intended irony Terry?.... Absolutely. I'm a Perl refugee. [1] Every couple of years, I decide to learn Java, and start going through a book -- usually the same book. It doesn't go long before I say to my self, "Gosh, why would I ever want to program this language, anyway?" From saurabh_r_a at yahoo.com Sun Feb 19 06:02:59 2006 From: saurabh_r_a at yahoo.com (saurabh akshekar) Date: Sat, 18 Feb 2006 21:02:59 -0800 (PST) Subject: [Tutor] pdf syntax In-Reply-To: Message-ID: <20060219050259.56436.qmail@web52514.mail.yahoo.com> Hi all my name is saurabh i want create n manipulate pdf files. can anybody tell me what is pdf syntax n how it works? also best or efficient language in which i should write program please reply regards saurabh --------------------------------- Yahoo! Mail Use Photomail to share photos without annoying attachments. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060218/67217f48/attachment.htm From carroll at tjc.com Sun Feb 19 06:16:14 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 18 Feb 2006 21:16:14 -0800 (PST) Subject: [Tutor] pdf syntax In-Reply-To: <20060219050259.56436.qmail@web52514.mail.yahoo.com> Message-ID: On Sat, 18 Feb 2006, saurabh akshekar wrote: > i want create n manipulate pdf files. > can anybody tell me what is pdf syntax n how it works? > also best or efficient language in which i should write program I'm looking into this myself. From what I gather, Reportlab's PDF toolkit ("The ReportLab Open Source PDF library") looks like the only sensible way to go if you want to write PDF from Python. Check out http://www.reportlab.org/rl_toolkit.html to get the toolkit, and http://www-128.ibm.com/developerworks/linux/library/l-sc6.html For an example and intro. From ismaelgf at adinet.com.uy Sun Feb 19 08:10:11 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 19 Feb 2006 05:10:11 -0200 Subject: [Tutor] Package problems Message-ID: <43F819D3.4070308@adinet.com.uy> Hello. I'm trying to make a package (so that later I can "import package"). I created one dir with an __init__.py, main.py, one.py __init__.py : from main import * main.py : import one Now, main.py creates one instance of a class (and there can be only that one instance) and provides several general purpouse functions that direct that instance to do something. The problem comes with one.py, which contains especialized functions which must use that same instance main.py uses. I don't want to merge the two files (it would be too clumsy, I think). I tried making the instance a global: global a a = In() But that doesn't work, one.py can't access "a" The only solution that comes to my mind is to create a function in one.py that would create a global, something like: def init(instance): global a a = instance and then call it after finishing the instanciation of the class. I don't think this is a good solution. Can anyone suggest a better idea? Thanks for your time, Ismael From alan.gauld at freenet.co.uk Sun Feb 19 10:12:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 09:12:17 -0000 Subject: [Tutor] Tutorial back on line Message-ID: <009001c63534$94d66d50$0b01a8c0@xp> My web site is up and running again, apologies for the loss of service. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From oztriking at hotmail.com Sun Feb 19 11:33:37 2006 From: oztriking at hotmail.com (John Connors) Date: Sun, 19 Feb 2006 21:33:37 +1100 Subject: [Tutor] First Try Message-ID: G'day :) I started getting sick of reading tutorials so for a bit of a break I set myself the task of writing a program to pick lotto numbers, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. So I was prepared for the same problem with python but I found that python takes care of that for me so the program would only have to be one line. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose print print print "Here are your numbers :" print for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print "Hope you win!" I know this is a very simple program but... could I have done this a better way? John _________________________________________________________________ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT From python-tutor at toddmaynard.com Sun Feb 19 12:27:15 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sun, 19 Feb 2006 06:27:15 -0500 Subject: [Tutor] First Try In-Reply-To: References: Message-ID: <200602190627.15396.python-tutor@toddmaynard.com> Nice Job John. I made a few comments below on a few things I noticed..... On Sunday 19 February 2006 05:33, John Connors wrote: > G'day :) > > I started getting sick of reading tutorials so for a bit of a break I set > myself the task of writing a program to pick lotto numbers, 6 numbers > between 1 and 44 (inclusive). I had done this many years before in basic > and I thought back then it would be a simple task but I struck a problem of > the random number generator repeating numbers occasionally so I had to > check each number against the other and generate another random number if > there were duplicates. > > So I was prepared for the same problem with python but I found that python > takes care of that for me so the program would only have to be one line. I > decided to make it a little more user friendly and allow the user to pick > home many games they want generated. Then I made the output a little easier > to read with a few blank lines. Here is what I came up with: > > > import random > > numberof = int(raw_input('Enter how many games you would like generated > :')) #user input for number of games to choose 10,000 lines of code or 6months later (whichever comes first...) will you remember what numberof represents? Number of times the cow jumped over the moon? I try not to end a var with a prep (and will usually just omit it). I would personally go for num_games_wanted or num_tickets. (Actually to tell the truth I am a mixedCase kinda guy so would really go for numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so I am trying to break my ways.) > > print > print > print "Here are your numbers :" > print > If you desire you can use "\n" for return to reduce this all into one line: print "\n\n\Here are your numbers :\n\n" No big deal. > for games in range(1, numberof + 1): #loop for the number of games selected > by user > lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers > between 1 and 44 inclusive > print games, lotto > print > > else: > print > print "Hope you win!" You don't need an else block (you will always enter it, ). You can just do: for games in range(1,numberof + 1): lotto = random.sample(xrange(1,45),6) print games, lotto print print "\nHope you win!" > > > I know this is a very simple program but... could I have done this a better > way? Looks pretty good to me..... If you want to expand this a little more you can try: 1.) Assign all the lottery tickets to a variable and then print out the lottery tickets after you have them all. ( A list would be helpful here...) 2.) Break your program into functions so that you can do something like: (num_tickets_wanted, min_num, max_num) = get_user_input() lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) print_results(lotto_tickets) NOTE: It would be pure evil to drop that alll into one line..... print_results(generate_tickets(get_user_input())) I shouldn't have even mentioned that, but you get the idea..... > > John > > _________________________________________________________________ > Search for local singles online @ Lavalife - Click here > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2 >Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3 >Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Have some fun with it....at least until you win the lottery..... --Todd Maynard -- Computers are unreliable, but humans are even more unreliable. Any system which depends on human reliability is unreliable. -- Gilb From python-tutor at toddmaynard.com Sun Feb 19 12:31:41 2006 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sun, 19 Feb 2006 06:31:41 -0500 Subject: [Tutor] First Try In-Reply-To: <200602190627.15396.python-tutor@toddmaynard.com> References: <200602190627.15396.python-tutor@toddmaynard.com> Message-ID: <200602190631.41155.python-tutor@toddmaynard.com> and for a belated footnote: [1] = http://www.python.org/peps/pep-0008.html Style Guide for python code. --Todd On Sunday 19 February 2006 06:27, Todd Maynard wrote: > Nice Job John. I made a few comments below on a few things I noticed..... > > On Sunday 19 February 2006 05:33, John Connors wrote: > > G'day :) > > > > I started getting sick of reading tutorials so for a bit of a break I set > > myself the task of writing a program to pick lotto numbers, 6 numbers > > between 1 and 44 (inclusive). I had done this many years before in basic > > and I thought back then it would be a simple task but I struck a problem > > of the random number generator repeating numbers occasionally so I had to > > check each number against the other and generate another random number if > > there were duplicates. > > > > So I was prepared for the same problem with python but I found that > > python takes care of that for me so the program would only have to be one > > line. I decided to make it a little more user friendly and allow the user > > to pick home many games they want generated. Then I made the output a > > little easier to read with a few blank lines. Here is what I came up > > with: > > > > > > import random > > > > numberof = int(raw_input('Enter how many games you would like generated > > > > :')) #user input for number of games to choose > > 10,000 lines of code or 6months later (whichever comes first...) will you > remember what numberof represents? Number of times the cow jumped over > the moon? I try not to end a var with a prep (and will usually just omit > it). I would personally go for num_games_wanted or num_tickets. (Actually > to tell the truth I am a mixedCase kinda guy so would really go for > numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so > I am trying to break my ways.) > > > print > > print > > print "Here are your numbers :" > > print > > If you desire you can use "\n" for return to reduce this all into one line: > print "\n\n\Here are your numbers :\n\n" > No big deal. > > > for games in range(1, numberof + 1): #loop for the number of games > > selected by user > > lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers > > between 1 and 44 inclusive > > print games, lotto > > print > > > > else: > > print > > print "Hope you win!" > > You don't need an else block (you will always enter it, ). > > You can just do: > > for games in range(1,numberof + 1): > lotto = random.sample(xrange(1,45),6) > print games, lotto > print > print "\nHope you win!" > > > I know this is a very simple program but... could I have done this a > > better way? > > Looks pretty good to me..... If you want to expand this a little more you > can try: > > 1.) Assign all the lottery tickets to a variable and then print out the > lottery tickets after you have them all. ( A list would be helpful > here...) > > 2.) Break your program into functions so that you can do something like: > > (num_tickets_wanted, min_num, max_num) = get_user_input() > lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) > print_results(lotto_tickets) > > NOTE: It would be pure evil to drop that alll into one line..... > print_results(generate_tickets(get_user_input())) > > I shouldn't have even mentioned that, but you get the idea..... > > > John > > > > _________________________________________________________________ > > Search for local singles online @ Lavalife - Click here > > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom > >%2 > > Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26local > >e%3 Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > Have some fun with it....at least until you win the lottery..... > > --Todd Maynard From ml.cyresse at gmail.com Sun Feb 19 13:20:17 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 20 Feb 2006 01:20:17 +1300 Subject: [Tutor] Threading + socket server (blocking IO) In-Reply-To: References: <43E72ED5.7040805@tds.net> <43E887D6.3010500@tds.net> <43F714A9.3000604@tds.net> Message-ID: Hi, Just poking at threads, I'm contemplating doing something that I think may be a very dumb thing to do, or it may work fine. In the following code - import threading import Queue import reg import msvcrt class ParseThread(threading.Thread): def __init__(self, Q, parser): self.Q = Q self.parser = parser self.sendIt = False threading.Thread.__init__(self) def run(self): while True: if self.sendIt: parser.send_data() self.sendIt = False try: data = self.Q.get(False) self.parser.check(data) except Empty: continue if __name__ == "__main__": Q = Queue.Queue() parser = reg.Parser() t1 = ParseThread(Q, parser) t1.start() while True: if msvcrt.kbhit(): if msvcrt.getch()=="S": t1.sendIt = True It's the sendIt attribute in t1. Is setting an attribute of a running thread a very bad thing, or a just be careful thing? The only usages for the attribute are as above, if it's set to True. the thread calls a method of the parser object, and then resets it to False. I can see an interesting collision if an external source sets self.sendIt to True as the thread sets it to False. I intend to use this with a timer, so that very x minutes, the attribute is changed, which hopefully sidesteps that particular collision. But yes, very unfamiliar territory, and I'm worried about sowing the seeds of my own destruction by being too clever/dumb. Regards, Liam Clarke On 2/19/06, Liam Clarke wrote: > Thanks Kent, I'll try swapping it around and see how it goes. > > As for the setDaemon, my apologies. There's a > > while True: > if msvcrt.kbhit(): > break > > loop afterwards, so at a keypress it exits, hence the daemon stuff. > > > On 2/19/06, Kent Johnson wrote: > > Liam Clarke wrote: > > > Hi, > > > > > > Just coming back to the server end of things. Kent, could I please ask > > > you to confirm that I'm not doing anything abnormal with the > > > ThreadingMixIn? The code is here at rafb: > > > http://www.rafb.net/paste/results/915JVm90.html > > > > > > Basically, when I test it using a script to generate the datagrams via > > > localhost, the server misses anywhere between 200 - 400 datagrams out > > > of 1041. > > > > I don't have time for a detailed response but it looks OK except > > ThreadingMixin needs to be the first base class because it overrides a > > method of UDPServer. It turns out there is a class > > SocketServer.ThreadingUDPServer that does this. > > > > Also I'm surprised the program stays running - ISTM with the server > > thread marked daemon and the main thread exiting the program should exit... > > > > Kent > > > > > From alan.gauld at freenet.co.uk Sun Feb 19 15:58:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 14:58:37 -0000 Subject: [Tutor] 'in-place' methods References: Message-ID: <00b401c63564$f6b051f0$0b01a8c0@xp> > [1] Every couple of years, I decide to learn Java, and start going through > a book -- usually the same book. It doesn't go long before I say to my > self, "Gosh, why would I ever want to program this language, anyway?" I've taught myself Java three times(*), first from the O'Reilly Nutshell book and then from their 'Learning Java' book (very good, I recommend it) and now from 'JSP for Dummies' - which is not really Java but uses it a lot... Unfortunately I have to read a lot of Java at work and very occasionally actually program in it, but I do not like it at all. But I prefer it to either COBOL or Perl... (*)I did the same with SmallTalk but I quite liked it, it just was too big a paradigm shift in style from Lisp, Object Pascal and C++ first time around. Alan G. From alan.gauld at freenet.co.uk Sun Feb 19 16:03:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 15:03:47 -0000 Subject: [Tutor] pdf syntax References: Message-ID: <00b801c63565$afa54210$0b01a8c0@xp> >> i want create n manipulate pdf files. >> can anybody tell me what is pdf syntax n how it works? PDF syntax is, I believe, a subset of Postscript. Postscript is a page description language so it defines a document something like a programming language draws graphics. Lots of positioning commands, draw lines,arcs etc. I've never written code to generate raw PDF but I have done Postscript and I can say that its very hard work! If you can find a toolkit use it and if you can avoid it altogether and just run your output through a translator like Acrobat then thats better still! > I'm looking into this myself. From what I gather, Reportlab's PDF toolkit > ("The ReportLab Open Source PDF library") looks like the only sensible way > to go if you want to write PDF from Python. I seem to recall a Python module in the Vaults of Parnassus(sp?) that did PDF generation. But I might be wrong... Alan G. From alan.gauld at freenet.co.uk Sun Feb 19 16:54:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 15:54:28 -0000 Subject: [Tutor] First Try References: Message-ID: <00be01c6356c$c43f9840$0b01a8c0@xp> > I started getting sick of reading tutorials so for a bit of a break I set > myself the task of writing a program to pick lotto numbers, Thats always a good idea! :-) Sometimes you discover you don't know enough to finish it but you can always go back, but in this case.... > So I was prepared for the same problem with python but I found that python > takes care of that for me so the program would only have to be one line. Yep, thats a common "problem" with Python, you start with what sounds an interesting challenge only to discover that Python makes it trivially easy! (Of course sometimes the trivially easy turns out to be astonishingly hard!) Now for some very nit-picking style stuff... > import random > > numberof = int(raw_input('Enter how many games you would like generated > :')) #user input for number of games to choose Its traditional to put comments above the lines to which they refer. > print > print > print "Here are your numbers :" > print print '\n\nHere are your numbers : \n" \n is a newline. Or print ''' Here are your numbers : ''' Triple quotes allow newlines wiothin them. > for games in range(1, numberof + 1): #loop for the number of games > selected games is plural so implies some kind of collection or sequence, the singular form is more suitable here since its really a single game number that it holds > lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers > between 1 and 44 inclusive > print games, lotto > print I'd probably use some string formatting here to ensure a neat layout: print "%3s\t%s" % (game, lotto) That will print a number right justified in 3 character width then a tab(\t) followed by the list. > else: > print > print "Hope you win!" You don't need the else, you always want to print that at the end of the loop so just have it as part of the text. Its very rare to use the else part of a for loop. In fact I've never used it for anything real so far as I can recall! > I know this is a very simple program but... could I have done this a > better way? The technique is fine, the points above are really about style and therefore something of a matter of personal taste. One other technique you could have used is list comprehension (you probably haven't met those yet) which could have produced all of your output in one go then you would only need to print it. But the advantage in minimal. One enhancement you might like to try is to ask for an optional lucky number and only display sequences with the lucky number in (Hint: there is a very easy way to do this and there is a much harder way). HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Sun Feb 19 19:31:01 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 13:31:01 -0500 (Eastern Standard Time) Subject: [Tutor] Bug in python Message-ID: <43F8B965.000003.01932@YOUR-4105E587B6> >>> a = 1 >>> a2 = a%2 >>> a2 1 >>> 8*a2 8 >>> 8*(a%2) 8 >>> 8*a%2 0 >>> The * is being given equal priority to %. Why isn't % given higher priority than *? Also, why am I getting a syntax error in the following? The def in the definition of the second function is being highlighted. IDLE 1.1.2 >>> def transfac(v): a = v[0] b = v[1] c = v[2] d = v[3] m = v[4] n = v[5] z = v[6] k = v[7] k = k + 1 a2 = a%2 b2 = b%2 c2 = c%2 d2 = d%2 ma = ((d - n * c)/(a*m + b))/2 na = ((d - m * b)/(a * n +c) )/2 j = 8 * a2 + 4 * b2 + 2 * c2 + d2 if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 if j == 4: a,b,c,d,m,n = a,b,c/2,d/2,2*m,n if j == 5: a,b,c,d,m,n = a,b,(a+c)/2,(d-b)/2,2*m+1,n if j == 6: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 7: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 8: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 9: a,b,c,d,m,n = 2*a,a+b,a+c,(d-a-b-c)/2,2*m+1,2*n+1 if j == 10: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 11: a,b,c,d,m,n = 2*a,a+b,c,(d-c)/2 if j == 12: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 13: a,b,c,d,m,n = 2*a,b,a+c,(d-b)/2,m,2*n+1 if j == 14: a,b,c,d,m,n = 2*a,b,c,d/2,2 *m,2*n if j == 15: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na z = a * d + b * c v = [a,b,c,d,m,n,z,k] return v comment: the def in the following line has been highlighted. def gcd(a,b): r2 = a r3 = b flag = 1 while flag>0: if r3 == 0: return r2 flag = 0 else: r1=r2 r2=r3 r3 = r1 - r2*(r1/r2) def factor0(z): v = [1,0,0,341,1,1,341,1] v[3] = z v[6]= z flag = 1 while flag > 0: v = transfac(v) g = gcd(z,v[0]) if g>1: if g1: if g1: if g1: if g>> From john at fouhy.net Sun Feb 19 22:31:59 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Feb 2006 10:31:59 +1300 Subject: [Tutor] Bug in python In-Reply-To: <5e58f2e40602191331i27d6726br@mail.gmail.com> References: <43F8B965.000003.01932@YOUR-4105E587B6> <5e58f2e40602191331i27d6726br@mail.gmail.com> Message-ID: <5e58f2e40602191331v4ddd16ffl@mail.gmail.com> On 20/02/06, Kermit Rose wrote: > >>> 8*a%2 > 0 > The * is being given equal priority to %. > > Why isn't % given higher priority than *? Calling it a bug is a bit harsh when it's documented that way :-) See: http://docs.python.org/ref/summary.html *, / and % all have the same precedence. I guess the reasoning is that / is (approximately) the inverse of * and % is "remainder after /". > Also, why am I getting a syntax error in the following? When you're using the interactive interpreter, you need to end a function definition with an extra carriage return. (at least, that's the way it works in the console version) eg: >>> def foo(): ... pass ... def bar(): File "", line 3 def bar(): ^ SyntaxError: invalid syntax vs: >>> def foo(): ... pass ... >>> def bar(): ... pass ... >>> HTH! -- John. From kermit at polaris.net Sun Feb 19 23:03:23 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 17:03:23 -0500 (Eastern Standard Time) Subject: [Tutor] How can I make Python Shell see new version of function subroutine? References: <5e58f2e40602191331v4ddd16ffl@mail.gmail.com> Message-ID: <43F8EB2B.000003.00596@YOUR-4105E587B6> From: John Fouhy Date: 02/19/06 16:33:18 To: Python Tutor Subject: [Tutor] Bug in python See: http://docs.python.org/ref/summary.html *, / and % all have the same precedence. I guess the reasoning is that / is (approximately) the inverse of * and % is "remainder after /". Hello John. Ok. I got steamed too quickly. ********** > Also, why am I getting a syntax error in the following? When you're using the interactive interpreter, you need to end a function definition with an extra carriage return. (at least, that's the way it works in the console version) ****************************** I believe you. However, when I added extra carriage returns to the script file between the function subroutines, it made no difference. Why? Is it because the windows copy and paste throws away the extra carriage returns? I pasted the function subroutines, one at a time, into the shell, and entered the carriage return directly into the shell between copies, and it worked. However, I have a debugging dilemma. I made changes to one of the function subroutines, and recopied that function to the shell and I put print statements in the new version of the function subroutine. None of the new print statements are printing. It's as if the old version is still runing. Is there anything short of closing the shell and re-opening it that I can do to fix this? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/4b7c93a2/attachment.html From john at fouhy.net Sun Feb 19 23:12:46 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Feb 2006 11:12:46 +1300 Subject: [Tutor] How can I make Python Shell see new version of function subroutine? In-Reply-To: <43F8EB2B.000003.00596@YOUR-4105E587B6> References: <5e58f2e40602191331v4ddd16ffl@mail.gmail.com> <43F8EB2B.000003.00596@YOUR-4105E587B6> Message-ID: <5e58f2e40602191412l1813e2b4y@mail.gmail.com> On 20/02/06, Kermit Rose wrote: > Why? Is it because the windows copy and paste throws away the extra carriage returns? Um --- could be. Do you need to use copy and paste? For instance, say all your functions are in a file called "factorization.py". In IDLE, you could type "import factorization", and then you'll be able to call your functions by typing things like "factorization.gcd(x, y)". If you change the code, you can reload the module by using the 'reload' builtin function. > I made changes to one of the function subroutines, and recopied that function to the shell > and I put print statements in the new version of the function subroutine. > > None of the new print statements are printing. > > It's as if the old version is still runing. > > Is there anything short of closing the shell and re-opening it that I can do to fix this? Have you tried restarting IDLE? The first thing to do would be to verify that the problem is what you think it is (as opposed to a bug in your code, for example). -- John. From kermit at polaris.net Sun Feb 19 23:15:44 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 17:15:44 -0500 (Eastern Standard Time) Subject: [Tutor] How can I make Python Shell see new version of functionsubroutine? References: <43F8EB2B.000003.00596@YOUR-4105E587B6> Message-ID: <43F8EE10.000005.00596@YOUR-4105E587B6> From: Kermit Rose Date: 02/19/06 17:05:53 To: Python Tutor; John Fouhy Subject: [Tutor] How can I make Python Shell see new version of functionsubroutine? Hello John. Ok. I got steamed too quickly. ********** However, I have a debugging dilemma. I made changes to one of the function subroutines, and recopied that function to the shell and I put print statements in the new version of the function subroutine. None of the new print statements are printing. It's as if the old version is still runing. ***************** Never mind> I found the problem. I had misunderstood the purpose of the returrn statement. I had thought return g simply set the function value to g. I did not realize at first that return g also exits the function, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/92a89eaf/attachment.htm From kermit at polaris.net Sun Feb 19 23:27:34 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 17:27:34 -0500 (Eastern Standard Time) Subject: [Tutor] How can I make Python Shell see new version of functionsubroutine? References: <5e58f2e40602191412l1813e2b4y@mail.gmail.com> Message-ID: <43F8F0D6.000007.00596@YOUR-4105E587B6> From: John Fouhy Date: 02/19/06 17:14:39 To: Python Tutor Subject: Re: [Tutor] How can I make Python Shell see new version of functionsubroutine? Do you need to use copy and paste? For instance, say all your functions are in a file called "factorization.py". In IDLE, you could type "import factorization", and then you'll be able to call your functions by typing things like "factorization.gcd(x, y)". ***************** >>> import "c:\\math\\factoring\\factor30.py" SyntaxError: invalid syntax >>> >>> import "c:\math\factoring\factor30.py" SyntaxError: invalid syntax >>> ****************** If you change the code, you can reload the module by using the 'reload' builtin function. **************** Could you explain this more. I'm not compiling or recompiling the function subroutine. ************ Have you tried restarting IDLE? The first thing to do would be to verify that the problem is what you think it is (as opposed to a bug in your code, for example). ******************* Yes. I made a mistake. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/a72dca92/attachment.htm From kermit at polaris.net Mon Feb 20 00:11:19 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 18:11:19 -0500 (Eastern Standard Time) Subject: [Tutor] Generating small random integer Message-ID: <43F8FB17.000003.03488@YOUR-4105E587B6> Hello. How can I find documentation on the random number generator function. It's not listed in the math module. In general, how can I find documentation on any particular function if I don't know what module it is in? Kermit < kermit at polaris.net > From adam.jtm30 at gmail.com Mon Feb 20 00:24:14 2006 From: adam.jtm30 at gmail.com (Adam) Date: Sun, 19 Feb 2006 23:24:14 +0000 Subject: [Tutor] Generating small random integer In-Reply-To: <43F8FB17.000003.03488@YOUR-4105E587B6> References: <43F8FB17.000003.03488@YOUR-4105E587B6> Message-ID: On 19/02/06, Kermit Rose wrote: > > Hello. > > How can I find documentation on the random number generator function. > > It's not listed in the math module. You might want to try the random module. In general, how can I find documentation on any particular function if I > don't know what module it is in? do a search on http://www.python.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/b3ad8f2a/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Feb 20 00:31:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 23:31:06 -0000 Subject: [Tutor] Bug in python References: <43F8B965.000003.01932@YOUR-4105E587B6> Message-ID: <001a01c635ac$9b8c7b80$0b01a8c0@xp> >>>> 8*a%2 > 0 >>>> > > The * is being given equal priority to %. > > Why isn't % given higher priority than *? Because that's the way Guido designed I guess. ;-) Although why would you expect % to be higher precedence than *? You can always use parentheses, and if in any doubt should do so. > Also, why am I getting a syntax error in the following? > > The def in the definition of the second function is being highlighted. Its always good to send the complete error message. Python errors are extremely informative whemn you can see them in their entirety. >>>> def transfac(v): > a = v[0] > b = v[1] > c = v[2] > d = v[3] > m = v[4] > n = v[5] > z = v[6] > k = v[7] > k = k + 1 > a2 = a%2 > b2 = b%2 > c2 = c%2 > d2 = d%2 > ma = ((d - n * c)/(a*m + b))/2 > na = ((d - m * b)/(a * n +c) )/2 > j = 8 * a2 + 4 * b2 + 2 * c2 + d2 > if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n > if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 > if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n > if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 It might be better to use an elif chain here. It makes little differemce in this case but is more conventional for long chains like this. if x == 1: f(y) elif x == 2: g(y) elif x == 3: ...etc else: catch errors here > comment: the def in the following line has been highlighted. Comments in Python startt with a # character and extend to the end of line. I appreciate its not part of the code but I thought I'd point it out :-) > def gcd(a,b): > r2 = a > r3 = b > flag = 1 > while flag>0: > if r3 == 0: > return r2 When you doi a return execution leaves the function so any lines after return will be ignored. This is like C. Buit its not your error, Python simply ignores them. However the error may be above the indicated line but since your post has lost all indentation its hard to tell. > > SyntaxError: invalid syntax We really need to see the full error plus the actual code with indentation etc for say 10 lines above and below the marked line. 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 Feb 20 00:36:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 23:36:33 -0000 Subject: [Tutor] How can I make Python Shell see new version of functionsubroutine? References: <5e58f2e40602191331v4ddd16ffl@mail.gmail.com> <43F8EB2B.000003.00596@YOUR-4105E587B6> Message-ID: <002d01c635ad$51c0ec10$0b01a8c0@xp> > I pasted the function subroutines, one at a time, into the shell, and > entered the carriage return directly into the shell between copies, > and it worked. I'm not sure why you are copying the code into the shell? Do you know about modules and the import and reload statements in Python? You can write a script and then save it and import it into the shell for testing. Change the script, save it and then reload() it into the shell for further testing. Not that intuitive I agree... Alan G. From alan.gauld at freenet.co.uk Mon Feb 20 00:43:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 23:43:59 -0000 Subject: [Tutor] How can I make Python Shell see new version offunctionsubroutine? References: <5e58f2e40602191412l1813e2b4y@mail.gmail.com> <43F8F0D6.000007.00596@YOUR-4105E587B6> Message-ID: <003701c635ae$5b78c1a0$0b01a8c0@xp> >>> import "c:\\math\\factoring\\factor30.py" Just use >>> import factor30 the file will need to be in Pythons search path. The easiest way is to use a single folder for all your code. the folder called site-packages should be included by default so you might like to use that. Alternatively you can use another one and add that folder to an environment vartiable called PYTHONPATH > Could you explain this more. I'm not compiling or recompiling > the function subroutine. Actually you are. When python imports a file (foo.py say) it compiles it into bytecode (and creates a file called foo.pyc in the process). Reload makes sure you get the latest updated version. reload(foo) Alan G. From kermit at polaris.net Mon Feb 20 00:50:14 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 18:50:14 -0500 (Eastern Standard Time) Subject: [Tutor] Generating small random integer References: Message-ID: <43F90436.000005.03488@YOUR-4105E587B6> From: Adam Date: 02/19/06 18:25:05 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] Generating small random integer You might want to try the random module. ***************************** Why did I get this diagnostic? >>> factor0(3737) [1, 0, 0, 3737, 1, 1, 3737, 1] Traceback (most recent call last): File "", line 1, in -toplevel- factor0(3737) File "", line 12, in factor0 v = transfac(v) File "", line 19, in transfac na = na + randint(1,na) NameError: global name 'randint' is not defined In the function that calls randint, I placed the import command. def transfac(v): import random a = v[0] randint(a, b) Return a random integer N such that a <= N <= b. *********************** In general, how can I find documentation on any particular function if I don't know what module it is in? do a search on http://www.python.org/ ****************** Patch: 3-argument pow() function I found this, but it doesn't tell me how to use it. I wanted to write a pseudo prime number tester. So, I wanted to use this function to test the value of pow(2,(z-1)/2,z) for positive integers z. ******* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/5af198b8/attachment.html From alan.gauld at freenet.co.uk Mon Feb 20 00:50:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Feb 2006 23:50:37 -0000 Subject: [Tutor] Generating small random integer References: <43F8FB17.000003.03488@YOUR-4105E587B6> Message-ID: <003d01c635af$48bad2f0$0b01a8c0@xp> > How can I find documentation on the random number generator function. > It's not listed in the math module. Its in the random module. BTW There are lots of random functions inPython depending on the algorithm you need. > In general, how can I find documentation on any particular function if I > don't know what module it is in? I usually just use Google - sounds primitive, but it usually gets it in the first 5 entries... For example try searching for python random function :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Mon Feb 20 01:00:13 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Feb 2006 13:00:13 +1300 Subject: [Tutor] Generating small random integer In-Reply-To: <43F90436.000005.03488@YOUR-4105E587B6> References: <43F90436.000005.03488@YOUR-4105E587B6> Message-ID: <5e58f2e40602191600k39e81e75m@mail.gmail.com> On 20/02/06, Kermit Rose wrote: > NameError: global name 'randint' is not defined > > > In the function that calls randint, I placed the import command. > > def transfac(v): > import random > a = v[0] You need to tell python that randint is in the random module. ie, instead of calling randint(), call random.randint(). Have you been through the tutorial on python.org? It is quite helpful. -- John. From kermit at polaris.net Mon Feb 20 01:16:12 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 19:16:12 -0500 (Eastern Standard Time) Subject: [Tutor] Generating small random integer References: <5e58f2e40602191600k39e81e75m@mail.gmail.com> Message-ID: <43F90A4C.00000D.03488@YOUR-4105E587B6> From: John Fouhy Date: 02/19/06 19:01:26 To: tutor at python.org Subject: Re: [Tutor] Generating small random integer You need to tell python that randint is in the random module. ie, instead of calling randint(), call random.randint(). ********************** oops. I should have know that. ********************* Have you been through the tutorial on python.org? It is quite helpful. *********************** I skimmed it a couple of times. I did try to read it from "cover to cover", but too quickly got into places where I did not know what it talked about. So I am falling back on the tactic of using it as a reference to look things up as I develope my program, and if I can't find the answer there to ask you guys. Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/9102451e/attachment.htm From brian at daviesinc.com Mon Feb 20 01:18:56 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 19 Feb 2006 19:18:56 -0500 Subject: [Tutor] File handling: open a file at specified byte? Message-ID: <43F90AF0.9090102@daviesinc.com> HI. This is one I cant seem to find a solid answer on: First, some background: I have a log file that I wrote a python parser for it, and it works great , but in the interest of saving time and memory , and also to be able to read the currently active log file, say every 10 minutes , and update the static file, I was trying to find some way that I can get python to do this: Open log file, read lines up to end of file, and *very important* make a note of the bytes read, and stash this somewhere (I.E. "mark" the file) , and then handle the parsing of said file, until all lines have been read and parsed, write the new files, and close the handler. say, 10 minutes later, for example, the script would then check the bytes read , and *very important* start reading the file *from* the point it marked (I.E. pick up at the point it bookmarked) and read from that point. Since the log file will be active (webserver log file) it will have new data to be read, but I dont want to have to read through the *entire* log file all over again, just to get to the new data- I want to be able ot "bookmark" where the log file was read "up to" last time, and then open the file later at that point. My current script works well, but only reads the "day old" log file (post log rotate) , and it does very well, parsing as much as 3 GB in as little as 2 minutes if the server isnt heavily loaded when the parser runs. basically, the webserver runs Tux , which writes a log file for *all* domains on a server, and the script takes the tux log, and parses it, extracting the domain for which the log entry is for, and writes a new line into the domain's apache format CLF log file (this way we are able to run awstats on individual domains, and get relatively accurate stats) So.. my question is- is there any way to do what I want ? Open a live log file, read lines to x bytes, (say 845673231 bytes) , make a note of this, and 10 miutes later open the same file again *AT* 845673232 bytes - starting with the next byte after the bookmarked point, read to end of file, and update the bookmark. Thanks for any pointers- Advice appreciated. Bri! From alan.gauld at freenet.co.uk Mon Feb 20 01:51:18 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 00:51:18 -0000 Subject: [Tutor] How can I make Python Shell see new version offunctionsubroutine? References: <003701c635ae$5b78c1a0$0b01a8c0@xp> <43F906D7.000007.03488@YOUR-4105E587B6> Message-ID: <004b01c635b7$c2d00da0$0b01a8c0@xp> Restoring the tutor list on CC ----- Original Message ----- From: "Kermit Rose" To: "Alan Gauld" > How can I add "c:\math\factoring" to the PYTHONPATH? What OS are you using? Assuming Windows NT/2000/XP you go to My Computer and right click Select Properties and go to the Advanced tab Click Environment Variables button Under System Variables click New In Varable Name type PYTHONPATH in upper case In variable value type your folder name c:\math\factoring in this case **************** > is > > reload(foo) > > equivalent to > > import foo More or less, yes. There may be a few subtle differences but if so I don't know what they are! Except you can only reload *after* using an import. And using import twice will not reload the module. 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 Feb 20 01:56:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 00:56:55 -0000 Subject: [Tutor] Showing code with errors References: <001a01c635ac$9b8c7b80$0b01a8c0@xp> <43F9090D.00000B.03488@YOUR-4105E587B6> Message-ID: <005301c635b8$8bbb2470$0b01a8c0@xp> >>We really need to see the full error plus the actual code > I had thought I had shown you exactly the code and error message. You only gave the error text not the fll message. A Python error message is multi line and looks like: File "", line 2 def g(): pass ^ SyntaxError: invalid syntax >>> That shows the file name, the line at fault, the location within the line as well as the description. If the error ioccurs deep within a program there will be a full stack trace showing all of the nested function calls too. > I did not anticipate that the email programs would clobber > the indentation. Sadly it happens all too often. The best solution is to ensure you send in plain text rather than HTML or RTF formats. Another trick is to put a character in front of all blank lines (a dot or hyphen say) 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 Feb 20 02:09:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 01:09:25 -0000 Subject: [Tutor] File handling: open a file at specified byte? References: <43F90AF0.9090102@daviesinc.com> Message-ID: <007501c635ba$4afad6e0$0b01a8c0@xp> look at the file tell() and seek() methods. They will tell you the current location and allow you to move to a specific location. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Brian Gustin" To: Sent: Monday, February 20, 2006 12:18 AM Subject: [Tutor] File handling: open a file at specified byte? > HI. This is one I cant seem to find a solid answer on: > > First, some background: > I have a log file that I wrote a python parser for it, and it works > great , but in the interest of saving time and memory , and also to be > able to read the currently active log file, say every 10 minutes , and > update the static file, I was trying to find some way that I can get > python to do this: > > Open log file, read lines up to end of file, and *very important* make a > note of the bytes read, and stash this somewhere (I.E. "mark" the file) , > and then handle the parsing of said file, until all lines have been read > and parsed, write the new files, and close the handler. > say, 10 minutes later, for example, the script would then check the > bytes read , and *very important* start reading the file *from* the > point it marked (I.E. pick up at the point it bookmarked) and read from > that point. > Since the log file will be active (webserver log file) it will have new > data to be read, but I dont want to have to read through the *entire* > log file all over again, just to get to the new data- I want to be able > ot "bookmark" where the log file was read "up to" last time, and then > open the file later at that point. > > My current script works well, but only reads the "day old" log file > (post log rotate) , and it does very well, parsing as much as 3 GB in as > little as 2 minutes if the server isnt heavily loaded when the parser > runs. basically, the webserver runs Tux , which writes a log file for > *all* domains on a server, and the script takes the tux log, and parses > it, extracting the domain for which the log entry is for, and writes a > new line into the domain's apache format CLF log file (this way we are > able to run awstats on individual domains, and get relatively accurate > stats) > > So.. my question is- is there any way to do what I want ? > > Open a live log file, read lines to x bytes, (say 845673231 bytes) , > make a note of this, and 10 miutes later open the same file again *AT* > 845673232 bytes - starting with the next byte after the bookmarked > point, read to end of file, and update the bookmark. > > > Thanks for any pointers- Advice appreciated. > Bri! > > > From alan.gauld at freenet.co.uk Mon Feb 20 02:07:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 01:07:44 -0000 Subject: [Tutor] Generating small random integer References: <43F90436.000005.03488@YOUR-4105E587B6> Message-ID: <006f01c635ba$0ea80780$0b01a8c0@xp> > Traceback (most recent call last): > File "", line 1, in -toplevel- > factor0(3737) > File "", line 12, in factor0 > v = transfac(v) > File "", line 19, in transfac > na = na + randint(1,na) > NameError: global name 'randint' is not defined Reading from the bottom uip it tells us that randint is not defined. randint is in the random module. > def transfac(v): > import random > a = v[0] > randint(a, b) You need to prepend the function name with the module name - this prevents "name collisions" across modules. ie random.randint(a,b) > I found this, but it doesn't tell me how to use it. Having found your function (import the module if necessary) then use help() >>> import math >>> help(math) >>> help(math.sqrt) Note when using help() do not put parens after the required function name - that would ask for help on the returned value! Use 'Q' to exit the help screen. Use 'b' to reverse up a screeen BTW there is a built in pow which is slightly different to the one in the math module... Tip: You can also use dir() to find out the names of functions in a module, including the built in functions: dir(__builtins__) dir(math) Note 2 underscores each side of builtins coz its a 'magic' name, imported modules are named as usual... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Mon Feb 20 02:24:23 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 20:24:23 -0500 (Eastern Standard Time) Subject: [Tutor] How can I make Python Shell see new version offunctionsubroutine? References: <004b01c635b7$c2d00da0$0b01a8c0@xp> Message-ID: <43F91A47.000011.03488@YOUR-4105E587B6> From: Alan Gauld Date: 02/19/06 19:55:13 To: Kermit Rose Cc: Python Tutor list Subject: Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine? Restoring the tutor list on CC ****** Thanks for reminding me. Assuming Windows NT/2000/XP you go to My Computer and right click Select Properties and go to the Advanced tab Click Environment Variables button Under System Variables click New In Varable Name type PYTHONPATH in upper case In variable value type your folder name c:\math\factoring I saw the PYTHONPATH name being added to the variable list. how might I verify, after the fact, that the name is correct? **************** I did all that. Why did I get this diagnostic? >>> import factor30.py Traceback (most recent call last): File "", line 1, in -toplevel- import factor30.py ImportError: No module named factor30.py -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/15d69d4b/attachment.html From john at fouhy.net Mon Feb 20 02:33:05 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Feb 2006 14:33:05 +1300 Subject: [Tutor] How can I make Python Shell see new version offunctionsubroutine? In-Reply-To: <43F91A47.000011.03488@YOUR-4105E587B6> References: <004b01c635b7$c2d00da0$0b01a8c0@xp> <43F91A47.000011.03488@YOUR-4105E587B6> Message-ID: <5e58f2e40602191733tcaa2186i@mail.gmail.com> On 20/02/06, Kermit Rose wrote: > >>> import factor30.py > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import factor30.py > ImportError: No module named factor30.py Because the module is named 'factor30', not 'factor30.py' ... -- John. From kermit at polaris.net Mon Feb 20 03:26:33 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 19 Feb 2006 21:26:33 -0500 (Eastern Standard Time) Subject: [Tutor] How can I make Python Shell see new versionoffunctionsubroutine? References: <5e58f2e40602191733tcaa2186i@mail.gmail.com> Message-ID: <43F928D9.00000B.02268@YOUR-4105E587B6> From: John Fouhy Date: 02/19/06 20:34:13 To: tutor at python.org Subject: Re: [Tutor] How can I make Python Shell see new versionoffunctionsubroutine? > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import factor30.py > ImportError: No module named factor30.py Because the module is named 'factor30', not 'factor30.py' ... -- John. ******** Thank you very much -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060219/8ae53912/attachment.html From Hans.Dushanthakumar at navman.com Mon Feb 20 04:20:53 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Mon, 20 Feb 2006 16:20:53 +1300 Subject: [Tutor] Printing the Carriage return character Message-ID: <5667508E43F1B740BCFA57FF46E35300036E16F3@nav-akl-exch-c.newton.navman.com> Hi, Not sure if this is a python thing or a Operating system peculiarity, but here goes: Why does the line print "FirstLine" + "\rSecondLine" produce different output when run via IDLE and when run in the python prompt (both under Windows XP)? Output in IDLE (ver 1.1.1, python 2.4.1): >>> print "FirstLine" + "\rSecondLine" FirstLine SecondLine >>> Output at the python prompt (python 2.4.1): C:\QVCS\Mobile Data\>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print "FirstLine" + "\rSecondLine" SecondLine >>> Cheers Hans From benmarkwell at gmail.com Mon Feb 20 04:58:31 2006 From: benmarkwell at gmail.com (benmarkwell at gmail.com) Date: Sun, 19 Feb 2006 22:58:31 -0500 Subject: [Tutor] First program -- would like comments and criticisms In-Reply-To: References: Message-ID: Thanks Andrei for your input. I've already implemented a couple of your suggestions and will certainly give the others a go. On 2/18/06, Andrei wrote: > > benmarkwell at gmail.com wrote: > > Here is my first stab at putting together a working program. It is a > > glossary that you can add words and definitions to, or look up words and > > their definitions. There are a couple of problems here and there, but > > it basically does what I set out for it to do. All comments and > > criticisms are welcome. I attached the data file that goes with the > > script in case anybody wanted to actually run it, so they wouldn't have > > to make their own dictionary file to access. > > I haven't executed it, but it seems quite good, certainly for a first > working program. For small programs there's no point in overengineering, > but here are some simple improvements you could look into: > > - place a "if __name__=="__main__":" condition at the bottom and put > your program code in there (or better yet, extract it in a function and > call that function after the if __name__ stuff). This way the module can > also be imported. > > - make the location of the dictionary a 'constant' (which in Python > means a variable with all-uppercase name :)). Having magic strings in > code is bad practice. > > - the menu system could be redesigned to make it more > maintenance-friendly. At this point if you want to add/modify a choice, > you'd have to modify a procedure and the main code. You could instead > make a dictionary mapping each possible choice (keys) to tuples > containing a description and a function name. Loop over the keys and > print them with the description. Once the user makes a choice, you could > look up the function in the dictionary and execute it. This way adding > new functionality items only means you need to add an entry to that one > dictionary. > > - you could replace the "while num != '3':" condition with a "while > True:" - the loop is interrupted anyway if '3' is selected, because of > the 'break'. This way you can also remove the initialization of num. > > - you could extract the actual logic (the glossary) to a class with > methods like "load", "save", "lookup" and separate it completely from > all the user interaction. The glossary class shouldn't print/ask for > user input. It's overkill for such a small program, but you could then > theoretically reuse the glossary in a different application (e.g. put a > webbased interface onto it, or subclass it and make a glossary which can > also do multiple language translations, or use a different storage > backend, etc.). > > > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info: > ''.join([''.join(s) for s in zip( > "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", > "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) > > _______________________________________________ > 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/20060219/7d17c971/attachment.htm From ml.cyresse at gmail.com Mon Feb 20 08:18:13 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 20 Feb 2006 20:18:13 +1300 Subject: [Tutor] Fwd: Threading + socket server (blocking IO) In-Reply-To: <43F91DCF.5070004@tds.net> References: <43E72ED5.7040805@tds.net> <43E887D6.3010500@tds.net> <43F714A9.3000604@tds.net> <43F91DCF.5070004@tds.net> Message-ID: As requested. ---------- Forwarded message ---------- From: Kent Johnson Date: Feb 20, 2006 2:39 PM Subject: Re: [Tutor] Threading + socket server (blocking IO) To: Cc: ml.cyresse at gmail.com Liam Clarke wrote: > Hi, > > > Just poking at threads, I'm contemplating doing something that I think > may be a very dumb thing to do, or it may work fine. > > In the following code - > > > import threading > import Queue > import reg > import msvcrt > > class ParseThread(threading.Thread): > > def __init__(self, Q, parser): > self.Q = Q > self.parser = parser > self.sendIt = False > threading.Thread.__init__(self) > > def run(self): > while True: > if self.sendIt: > parser.send_data() > self.sendIt = False > try: > data = self.Q.get(False) > self.parser.check(data) > except Empty: > continue > > > if __name__ == "__main__": > > Q = Queue.Queue() > parser = reg.Parser() > > t1 = ParseThread(Q, parser) > t1.start() > > while True: > if msvcrt.kbhit(): > if msvcrt.getch()=="S": > t1.sendIt = True > > > It's the sendIt attribute in t1. Is setting an attribute of a running > thread a very bad thing, or a just be careful thing? The only usages > for the attribute are as above, if it's set to True. the thread calls > a method of the parser object, and then resets it to False. > > I can see an interesting collision if an external source sets > self.sendIt to True as the thread sets it to False. > > I intend to use this with a timer, so that very x minutes, the > attribute is changed, which hopefully sidesteps that particular > collision. > > But yes, very unfamiliar territory, and I'm worried about sowing the > seeds of my own destruction by being too clever/dumb. Setting an attribute in one thread and checking it in another is OK, I think. But setting an atribute in two threads raises the possibility of a race condition. There is definitely a chance of missing a setting of sendIt to true: ParseThread main thread if self.sendIt: # if sendIt is already true t1.sendIt = True # main thread sets it true again parser.send_data() self.sendIt = False # set it false If the test is much more frequent than the set, this is unlikely but it is a weakness in the design. Also you have a busy loop (an infinite loop that just keeps polling), you should at least put a sleep in it, better is to use a get() with timeout or a blocking get(). I don't understand what your run() loop is doing - it seems to read data from the queue and throw it away, optionally calling parser.send_data(). Can you explain what you are trying to do? Presumably this is part of your UDP server? Kent PS My mail server has been blacklisted, can you forward this to the tutor list? From ewald.ertl at hartter.com Mon Feb 20 08:30:53 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 20 Feb 2006 08:30:53 +0100 Subject: [Tutor] File handling: open a file at specified byte? In-Reply-To: <43F90AF0.9090102@daviesinc.com> References: <43F90AF0.9090102@daviesinc.com> Message-ID: <43F9702D.7020500@hartter.com> Hi Brian! There are two functions for an file-Object which deliver the position in the file and can seek-function to set the offset in the file: >>> f=open(".emacs", "r" ) >>> help(f.tell) Help on built-in function tell: tell(...) tell() -> current file position, an integer (may be a long integer). >>> help( f.seek ) Help on built-in function seek: seek(...) seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. HTH Ewald Brian Gustin wrote: > HI. This is one I cant seem to find a solid answer on: > > First, some background: > I have a log file that I wrote a python parser for it, and it works > great , but in the interest of saving time and memory , and also to be > able to read the currently active log file, say every 10 minutes , and > update the static file, I was trying to find some way that I can get > python to do this: > > Open log file, read lines up to end of file, and *very important* make a > note of the bytes read, and stash this somewhere (I.E. "mark" the file) , > and then handle the parsing of said file, until all lines have been read > and parsed, write the new files, and close the handler. > say, 10 minutes later, for example, the script would then check the > bytes read , and *very important* start reading the file *from* the > point it marked (I.E. pick up at the point it bookmarked) and read from > that point. > Since the log file will be active (webserver log file) it will have new > data to be read, but I dont want to have to read through the *entire* > log file all over again, just to get to the new data- I want to be able > ot "bookmark" where the log file was read "up to" last time, and then > open the file later at that point. > > My current script works well, but only reads the "day old" log file > (post log rotate) , and it does very well, parsing as much as 3 GB in as > little as 2 minutes if the server isnt heavily loaded when the parser > runs. basically, the webserver runs Tux , which writes a log file for > *all* domains on a server, and the script takes the tux log, and parses > it, extracting the domain for which the log entry is for, and writes a > new line into the domain's apache format CLF log file (this way we are > able to run awstats on individual domains, and get relatively accurate > stats) > > So.. my question is- is there any way to do what I want ? > > Open a live log file, read lines to x bytes, (say 845673231 bytes) , > make a note of this, and 10 miutes later open the same file again *AT* > 845673232 bytes - starting with the next byte after the bookmarked > point, read to end of file, and update the bookmark. > > > Thanks for any pointers- Advice appreciated. > Bri! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From alan.gauld at freenet.co.uk Mon Feb 20 08:53:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 07:53:48 -0000 Subject: [Tutor] How can I make Python Shell see new version offunctionsubroutine? References: <004b01c635b7$c2d00da0$0b01a8c0@xp> <43F91A47.000011.03488@YOUR-4105E587B6> Message-ID: <007b01c635f2$c8434f50$0b01a8c0@xp> > Why did I get this diagnostic? >>>> import factor30.py > ImportError: No module named factor30.py The module name is factor30 no need for the .py, thats the file name. Two differemt things! Alan g. From alan.gauld at freenet.co.uk Mon Feb 20 09:01:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 08:01:31 -0000 Subject: [Tutor] Fw: File handling: open a file at specified byte? Message-ID: <008501c635f3$dc425ea0$0b01a8c0@xp> Forwarding for list visibility ----- Original Message ----- From: "Brian Gustin" To: "Alan Gauld" Sent: Monday, February 20, 2006 2:23 AM Subject: Re: [Tutor] File handling: open a file at specified byte? > > > look at the file tell() and seek() methods. > > > > They will tell you the current location and allow you to move to a > > specific location. > > > OK..I did try using seek and tell, and couldnt get working code to do > what I needed it to, however, it did lead me to discover the fileinput > module, so.. Ive tested it on my test file, and it works quite well, I'd > like to see if you can offer any better suggestions - keeping in mind a > log file can grow to as large as 3 GB, so memory management will bee > important, as will execution time (I will need this parser to execute on > a file as large as 3 - 4 GB in under 10 minutes time, ideally shooting > for less than 1 minute) > > Code follows: > ##START CODE ########## > #!/usr/bin/python > #for testing of tux parser > # read "live" log file and parse it into separate domain files > import string > import re > import fileinput > > myfiles={} > line=1 > last=0 > try: > bkmk = open('bookmark','r') > last = bkmk.readline() > bkmk.close() > except: > pass > for outputdata in fileinput.input('./testfile.tuxlog'): > #sourcelist.sort() > #print outputdata > if fileinput.filelineno() < int(last): > continue > else: > info = re.search('(?<=GET )([a-zA-Z0-9\-\.]+)', outputdata) > try: > namecheck = info.group(0) > except AttributeError: > continue > try: > namecheck=namecheck.replace('www.','') > check = re.search('(\.[a-z]+$)',namecheck) > if check == None: > domain = 'Errors' > else: > res = re.search('(\ (301|404|403|302)\ 0)',outputdata) > if res == None: > domain = namecheck > else: > domain = '404_301errors' > outputdata=outputdata.replace(' '+domain+'/',' /') > if myfiles.has_key(domain): > domhandle = myfiles.get(domain) > else: > > domhandle=open('/var/log/tuxp/'+domain+'-access.log.1','w+') > myfiles[domain] = domhandle > > > domhandle.write(outputdata) > except: > continue > bookmark = fileinput.lineno() #get the last line no handled. could > this instead be run just before closing the handle? > rel = open('./bookmark','w') > rel.write(str(bookmark)) > rel.close() > #print "BOOKMARK: %s"%bookmark, > #print domain+' - ', > #print namecheck, > # line +=1 > #print str(line)+"\n" > #print fileinput.filelineno() > fileinput.close() > > > ############ END CODE############ > From alan.gauld at freenet.co.uk Mon Feb 20 09:22:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 08:22:01 -0000 Subject: [Tutor] Printing the Carriage return character References: <5667508E43F1B740BCFA57FF46E35300036E16F3@nav-akl-exch-c.newton.navman.com> Message-ID: <00ae01c635f6$b9bdf9e0$0b01a8c0@xp> > Not sure if this is a python thing or a Operating system peculiarity, An IDLE thing specifically - or maybe even a Tkinter thing... > Why does the line > print "FirstLine" + "\rSecondLine" > produce different output when run via IDLE and when run in the python > prompt (both under Windows XP)? \r is a carriage return which literally means that the printhead carriage should return to the start of the line. You need a line feed character if you want a new line too. Unfortunately some OS use \r to do both, others need both. The safe way is to use \n (new line) instead. > Output in IDLE (ver 1.1.1, python 2.4.1): > FirstLine > SecondLine > Output at the python prompt (python 2.4.1): > SecondLine So being pedantic XP is correct, IDLE is wrong but in fact because the conventions are so mixed up right and wrong is a bit woolly. Which response were you trying to get? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jhe13586 at bigpond.net.au Mon Feb 20 10:46:28 2006 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Mon, 20 Feb 2006 19:46:28 +1000 Subject: [Tutor] G'day In-Reply-To: References: <002e01c633a9$3279f1e0$0b01a8c0@xp> Message-ID: John Connors wrote: > I'm now using an ebook I found called Dive Into Python. I much prefer using > a book so I can duck back a few pages to refresh my memory and reading on > the monitor is a real pain. It seems an excellent reference though so I'll > get around to printing it out sooner or latter (when the Mrs isn't here so > she won't complain about me wasting ink and paper). > > John Having a book is good when you're beginning, but with python (like most open-source projects), the electronic documents are usually more detailed and up to date. I have the O'Reilly "Programming Python" book, and while the stuff on classes is good, she don' mention things like list comprehensions, new class types, iterators or generators (or as someone has pointed out, string methods). Similar situation with blender. Bought the "Blender 2.3 Guide", nearly outdated now, and that's barely two years later. Joal Heagney From kent37 at tds.net Mon Feb 20 12:03:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Feb 2006 06:03:47 -0500 Subject: [Tutor] First program -- would like comments and criticisms In-Reply-To: References: Message-ID: <43F9A213.1060103@tds.net> benmarkwell at gmail.com wrote: > Here is my first stab at putting together a working program. It is a > glossary that you can add words and definitions to, or look up words and > their definitions. There are a couple of problems here and there, but > it basically does what I set out for it to do. All comments and > criticisms are welcome. I attached the data file that goes with the > script in case anybody wanted to actually run it, so they wouldn't have > to make their own dictionary file to access. See my suggestions below. Kent > > Thanks in advance. > Ben > > > # File gloss.py > # Author Ben Markwell > # Date Feb 2006 > > ''' > This script is a glossary in which you can input definitions > and look up words and their definitions. > ''' > > import cPickle as p > import textwrap as t > > f = file(r'g:\dev\python\data\gloss.data', 'r') > gloss = p.load(f) f.close() should be here, you're done with reading this file now. > > #---Def > Functions---#000000#FFFFFF-------------------------------------------------- > > def findWord(): > words = gloss.keys() > letter = raw_input('That word is not in the glossary. \nWhat is the > first letter of the word? ') > for x in range(len(words)): > if words[x].startswith(letter): > print words[x] To iterate over the elements of a sequence you don't need to use an index, you can iterate the sequence directly: for word in words: if word.startswith(letter): print word Since words isn't used anywhere else I would write this as for word in gloss.keys(): Finally, since you just asked for the word (if I understand correctly the intent), it would be friendlier to figure out the first letter yourself and pass it as a parameter to findWord(), rather than having the user enter it again. > > # Get word and check if it is in the glossary then print the def. > def getWordDef(): > word = raw_input('enter a word: ') > if gloss.has_key(word): > line = gloss.get(word) > lineWrap(word) > else: > findWord() > word = raw_input('Enter the word: ') > line = gloss.get(word) > lineWrap(word) > > # Print a menu of choices to the screen > def printMenu(): > print '1 - Enter a word and definition.' > print '2 - Look up a word.' > print '3 - Quit' > print > > # Wrap the output so it fits the screen nicely > def lineWrap(word): > line = gloss.get(word) > if len(line) < 81: > print line > else: > wrapLines = t.wrap(line, 80) > for line in range(len(wrapLines)): > print wrapLines[line] for wrapped in t.wrap(line, 80): > > # End of Def Functions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx > > num = '0' > printMenu() > while num != '3': > num = raw_input('What do you want to do? ') > if num == '1': # if 1 in choice enter a word to look up > word = raw_input('Enter word: ') > _def = raw_input('Enter definition: ') > gloss[word] = _def > > elif num == '2': # if 2 is the choice enter word and def > getWordDef() > > elif num == '3': # if 3 is the choice, save changes and quit > newGloss = file(r'g:\dev\python\data\gloss.data', 'w') > p.dump(gloss, newGloss) > newGloss.close() > f.close() > print > print 'Goodbye' > break > > else: > printMenu() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lumbricus at gmx.net Mon Feb 20 13:00:35 2006 From: lumbricus at gmx.net (lumbricus at gmx.net) Date: Mon, 20 Feb 2006 13:00:35 +0100 (MET) Subject: [Tutor] Proxy Message-ID: <13431.1140436835@www089.gmx.net> I like this one: "http://home.wtal.de/stampa/httpMonitor/" It provides an interface to set up your own Filters. So you can easily block/modify requests/responses. HTH, J"o! -- Freedom, Freedom, Freedom, Oi! -- Zoidberg Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner From kermit at polaris.net Mon Feb 20 09:19:47 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 20 Feb 2006 03:19:47 -0500 (Eastern Standard Time) Subject: [Tutor] import of source code still not working Message-ID: <43F97BA3.000003.02808@YOUR-4105E587B6> IDLE 1.1.2 >>> import factor30 >>> factor(1000009) Traceback (most recent call last): File "", line 1, in -toplevel- factor(1000009) NameError: name 'factor' is not defined >>> factor0(1000009) Traceback (most recent call last): File "", line 1, in -toplevel- factor0(1000009) NameError: name 'factor0' is not defined >>> From jason.massey at gmail.com Mon Feb 20 18:19:35 2006 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 20 Feb 2006 11:19:35 -0600 Subject: [Tutor] import of source code still not working In-Reply-To: <43F97BA3.000003.02808@YOUR-4105E587B6> References: <43F97BA3.000003.02808@YOUR-4105E587B6> Message-ID: <7e3eab2c0602200919l6119edt8547d28473dee6a8@mail.gmail.com> The problem here is that you need to reference the factor30 namespace to get to your functions: Your calls to your functions would then look like: factor30.factor(1000009) & factor30.factor0(1000009) If you don't want to have to put the factor30 in front of all your function names you can do this: from factor30 import * Which will put all of your functions into the global namespace. Then you can call factor() & factor0() as you would expect to. On 2/20/06, Kermit Rose wrote: > > IDLE 1.1.2 > >>> import factor30 > >>> factor(1000009) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > factor(1000009) > NameError: name 'factor' is not defined > >>> factor0(1000009) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > factor0(1000009) > NameError: name 'factor0' is not defined > >>> > > _______________________________________________ > 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/20060220/6d152256/attachment.htm From hugonz-lists at h-lab.net Mon Feb 20 19:30:20 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 20 Feb 2006 12:30:20 -0600 Subject: [Tutor] pdf syntax In-Reply-To: <20060219050259.56436.qmail@web52514.mail.yahoo.com> References: <20060219050259.56436.qmail@web52514.mail.yahoo.com> Message-ID: <43FA0ABC.9070308@h-lab.net> Hi, Syntax for composing a PDF is ugly PostScript. However, there are a couple of ways to use Python libraries to avoid the details. You can draw a canvas in Tkinter and then print it, then use something linke ps2pdf to do the conversion. http://effbot.org/tkinterbook/canvas.htm You can use ReportLab, which is intended specifically for generating PDF. Docs are very complete: http://www.reportlab.org/ The best language is of course Python, as this is the Python Tutors list ;) Hope that gets you started, Hugo saurabh akshekar wrote: > Hi all > my name is saurabh > i want create n manipulate pdf files. > can anybody tell me what is pdf syntax n how it works? > also best or efficient language in which i should write program > please reply > From kermit at polaris.net Mon Feb 20 19:56:10 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 20 Feb 2006 13:56:10 -0500 (Eastern Standard Time) Subject: [Tutor] import of source code still not working References: <7e3eab2c0602200919l6119edt8547d28473dee6a8@mail.gmail.com> Message-ID: <43FA10CA.000003.03956@YOUR-4105E587B6> From: Jason Massey Date: 02/20/06 12:20:03 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] import of source code still not working If you don't want to have to put the factor30 in front of all your function names you can do this: from factor30 import * Which will put all of your functions into the global namespace. Then you can call factor() & factor0() as you would expect to. ******* Thank you very much Next dilemma is: >>> v = [2, 35715, 17859, -318417088, 8932, 17860, 1000009, 5] >>> v = transfac(v) -1 2 35715 17859 -318417088 8932 17860 Traceback (most recent call last): File "", line 1, in -toplevel- v = transfac(v) File "c:\math\factoring\factor30.py", line 46, in transfac a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n AttributeError: 'int' object has no attribute 'c' >>> v [2, 35715, 17859, -318417088, 8932, 17860, 1000009, 5] Listing of transfac function is def transfac(v): # import random # begin level 0 a = v[0] b = v[1] c = v[2] d = v[3] m = v[4] n = v[5] z = v[6] # line 10 k = v[7] k = k + 1 a2 = a%2 b2 = b%2 c2 = c%2 d2 = d%2 # ma = ((d - n * c)/(a*m + b))/4 # ma = random.randint(1,min(abs(ma),abs(m))+1) # na = ((d - m * b)/(a * n +c) )/4 # na = random.randint(1,min(abs(na),abs(n))+1) # line 20 # if v[3]<0: # na=-na # ma=-ma # ma = ma * random.randint(0,1) # if ma=0: # pass # else # na = na * random.randint(0,1) j = 8 * a2 + 4 * b2 + 2 * c2 + d2 if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n # line 30 if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 if j == 4: a,b,c,d,m,n = a,b,c/2,d/2,2*m,n if j == 5: a,b,c,d,m,n = a,b,(a+c)/2,(d-b)/2,2*m+1,n if j == 6: # begin if level 1 if b>c: # begin if level 2 t=(d-b*m)/(a+c*m) # line 40 t=t/4 print t if t==0: t=1 print a,b,c,d,m,n a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n # end if level 2 # line 46 else: # begin if level 2 t=(d-c*n)/(b+a*m) t=t/4 # line 50 if t==0: t=1 a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t # end if level 2 # end if level 1 # a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma,n+na if j == 7: # begin if level 1 if b>c: # begin if level 2 t=(d - b * m)/(c + a*m) t=t/4 if t == 0: t=1 a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n else: # continue if level 2 t=(d - c * n)/(b+a*n) t=t/4 if t == 0: t=1 a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t # end if level 2 # end if level 1 if j == 8: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 9: a,b,c,d,m,n = 2*a,a+b,a+c,(d-a-b-c)/2,2*m+1,2*n+1 if j == 10: # begin if level 1 if b>c: # begin if level 2 t=(d - b * m)/(c + a * m) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n # end if level 2 else: # continue if level 1 t=(d - c * n)/(c + a * n) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t # end if level 2 # end if level 1 if j == 11: a,b,c,d,m,n = 2*a,a+b,c,(d-c)/2 if j == 12: # begin if level 1 if b>c: # begin if level 2 t=(d - b * m)/(c + a * m) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n else: # continue if level 2 t=(d - c * n)/(b + a * n) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t # end if level 2 # end if level 1 if j == 13: a,b,c,d,m,n = 2*a,b,a+c,(d-b)/2,m,2*n+1 if j == 14: a,b,c,d,m,n = 2*a,b,c,d/2,2 *m,2*n if j == 15: # begin if level 1 if b>c: # begin if level 2 t=(d - b * m)/(c + a * m) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n else: # continue if level 2 t=(d - c * n)/(b + a * n) t=t/4 if t==0: t=1 a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t # end if level 2 # end if level 1 z = a * d + b * c v = [a,b,c,d,m,n,z,k] return v # end routine level 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/b24c2aa3/attachment-0001.htm From adam.jtm30 at gmail.com Mon Feb 20 20:04:48 2006 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 20 Feb 2006 19:04:48 +0000 Subject: [Tutor] import of source code still not working In-Reply-To: <43FA10CA.000003.03956@YOUR-4105E587B6> References: <7e3eab2c0602200919l6119edt8547d28473dee6a8@mail.gmail.com> <43FA10CA.000003.03956@YOUR-4105E587B6> Message-ID: On 20/02/06, Kermit Rose wrote: > > > > *From:* Jason Massey > *Date:* 02/20/06 12:20:03 > *To:* Kermit Rose > *Cc:* tutor at python.org > *Subject:* Re: [Tutor] import of source code still not working > > > If you don't want to have to put the factor30 in front of all your > function names you can do this: > > from factor30 import * > > Which will put all of your functions into the global namespace. > > Then you can call factor() & factor0() as you would expect to. > > > ******* > > Thank you very much > > Next dilemma is: > > > >>> v = [2, 35715, 17859, -318417088, 8932, 17860, 1000009, 5] > >>> v = transfac(v) > -1 > 2 35715 17859 -318417088 8932 17860 > > Traceback (most recent call last): > File "", line 1, in -toplevel- > v = transfac(v) > File "c:\math\factoring\factor30.py", line 46, in transfac > a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n > AttributeError: 'int' object has no attribute 'c' > >>> v > [2, 35715, 17859, -318417088, 8932, 17860, 1000009, 5] > > > Listing of transfac function is > > > def transfac(v): > # import random > # begin level 0 > a = v[0] > b = v[1] > c = v[2] > d = v[3] > m = v[4] > n = v[5] > z = > v[6] > # line 10 > k = v[7] > k = k + 1 > a2 = a%2 > b2 = b%2 > c2 = c%2 > d2 = d%2 > # ma = ((d - n * c)/(a*m + b))/4 > # ma = random.randint(1,min(abs(ma),abs(m))+1) > # na = ((d - m * b)/(a * n +c) )/4 > # na = random.randint(1,min(abs(na),abs(n))+1) > # line 20 > # if v[3]<0: > # na=-na > # ma=-ma > # ma = ma * random.randint(0,1) > # if ma=0: > # pass > # else > # na = na * random.randint(0,1) > j = 8 * a2 + 4 * b2 + 2 * c2 + d2 > if j == 0: a,b,c,d,m,n = > a/2,b/2,c/2,d/2,m,n # line 30 > if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 > if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n > if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 > if j == 4: a,b,c,d,m,n = a,b,c/2,d/2,2*m,n > if j == 5: a,b,c,d,m,n = a,b,(a+c)/2,(d-b)/2,2*m+1,n > if j == 6: > # begin if level 1 > if b>c: > # begin if level 2 > > t=(d-b*m)/(a+c*m) > # line 40 > > t=t/4 > print t > if t==0: t=1 > print a,b,c,d,m,n > a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n > # end if level > 2 > # line 46 > else: > # begin if level 2 > t=(d-c*n)/(b+a*m) > > t=t/4 > # line 50 > if t==0: t=1 > a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t > # end if level 2 > # end if level 1 > # a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma,n+na > if j == 7: > # begin if level 1 > if b>c: > # begin if level 2 > t=(d - b * m)/(c + a*m) > t=t/4 > if t == 0: t=1 > a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n > else: > # continue if level 2 > t=(d - c * n)/(b+a*n) > t=t/4 > if t == 0: t=1 > a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t > # end if level 2 > # end if level 1 > if j == 8: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 > if j == 9: a,b,c,d,m,n = 2*a,a+b,a+c,(d-a-b-c)/2,2*m+1,2*n+1 > if j == 10: > # begin if level 1 > if b>c: > # begin if level 2 > t=(d - b * m)/(c + a * m) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n > # end if level 2 > else: > # continue if level 1 > t=(d - c * n)/(c + a * n) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t > # end if level 2 > # end if level 1 > if j == 11: a,b,c,d,m,n = 2*a,a+b,c,(d-c)/2 > if j == 12: > # begin if level 1 > if b>c: > # begin if level 2 > t=(d - b * m)/(c + a * m) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n > else: > # continue if level 2 > t=(d - c * n)/(b + a * n) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t > # end if level 2 > # end if level 1 > if j == 13: a,b,c,d,m,n = 2*a,b,a+c,(d-b)/2,m,2*n+1 > if j == 14: a,b,c,d,m,n = 2*a,b,c,d/2,2 *m,2*n > if j == 15: > # begin if level 1 > if b>c: > # begin if level 2 > t=(d - b * m)/(c + a * m) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b,c+a*t,d-b*t,m+t,n > else: > # continue if level 2 > t=(d - c * n)/(b + a * n) > t=t/4 > if t==0: t=1 > a,b,c,d,m,n = a,b+a*t,c,d-c*t,m,n+t > # end if level 2 > # end if level 1 > z = a * d + b * c > v = [a,b,c,d,m,n,z,k] > return v > # end routine level > Kermit have you actually bothered going through any tutorials? You just seem to be asking every time you get an error, I know the list is here for people to ask questions but you really should try and work some things out for yourself. Traceback (most recent call last): File "", line 1, in -toplevel- v = transfac(v) File "c:\math\factoring\factor30.py", line 46, in transfac a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n AttributeError: 'int' object has no attribute 'c' Your problem here is that you have b.c instead of what I presume should be a comma. b.c means that it's trying to find the method c of the integer b which doesn't exist. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/25e0c1f7/attachment.html From kermit at polaris.net Mon Feb 20 20:25:47 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 20 Feb 2006 14:25:47 -0500 (Eastern Standard Time) Subject: [Tutor] Debugging method References: Message-ID: <43FA17BB.000003.03660@YOUR-4105E587B6> Kermit have you actually bothered going through any tutorials? You just seem to be asking every time you get an error, I know the list is here for people to ask questions but you really should try and work some things out for yourself. Traceback (most recent call last): File "", line 1, in -toplevel- v = transfac(v) File "c:\math\factoring\factor30.py", line 46, in transfac a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n AttributeError: 'int' object has no attribute 'c' Your problem here is that you have b.c instead of what I presume should be a comma. b.c means that it's trying to find the method c of the integer b which doesn't exist. Thank you very much. Actually, I have been working things out myself. The many questions I've sent you are only a fraction of the problems I've encountered while developing this program. The tutorials are helpful only if I know what to look for. For this particular error message, I had no clue that "has no attribute" is a hint that a period is typed where it should not be. Now I know how to interpret that particular error message should it occur in the future. I had looked the code over. I knew to look on that line, but was totally baffled because I could not distinguish the comma from the period. Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/33cbb7e7/attachment.html From Hans.Dushanthakumar at navman.com Mon Feb 20 21:32:17 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 21 Feb 2006 09:32:17 +1300 Subject: [Tutor] Printing the Carriage return character Message-ID: <5667508E43F1B740BCFA57FF46E35300036E1BEE@nav-akl-exch-c.newton.navman.com> Thanks Alan for clearing that up...I was trying to see why my "\r\n" does not print 2 empty lines when I stumbled across this 'gotcha'. -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Monday, 20 February 2006 9:22 p.m. To: Hans Dushanthakumar; tutor at python.org Subject: Re: [Tutor] Printing the Carriage return character > Not sure if this is a python thing or a Operating system > peculiarity, An IDLE thing specifically - or maybe even a Tkinter thing... > Why does the line > print "FirstLine" + "\rSecondLine" > produce different output when run via IDLE and when run in the python > prompt (both under Windows XP)? \r is a carriage return which literally means that the printhead carriage should return to the start of the line. You need a line feed character if you want a new line too. Unfortunately some OS use \r to do both, others need both. The safe way is to use \n (new line) instead. > Output in IDLE (ver 1.1.1, python 2.4.1): > FirstLine > SecondLine > Output at the python prompt (python 2.4.1): > SecondLine So being pedantic XP is correct, IDLE is wrong but in fact because the conventions are so mixed up right and wrong is a bit woolly. Which response were you trying to get? 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 Feb 20 21:53:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 20:53:43 -0000 Subject: [Tutor] import of source code still not working References: <7e3eab2c0602200919l6119edt8547d28473dee6a8@mail.gmail.com> <43FA10CA.000003.03956@YOUR-4105E587B6> Message-ID: <003701c6365f$bc649820$0b01a8c0@xp> >>If you don't want to have to put the factor30 in front of all your >>function >> names you can do this: >> >> from factor30 import * But this is generally considered bad practice since the same function name can appear in many modules so the last module imported will hide all the others. The small increase in typing is a small price to pay for much more reliable code. You can control visibility by doing from factor30 import factor, someOtherFunc, andAnother ie list the names you need to use explicitly. That way you can see potential name clashes more easily. > Next dilemma is: >>> v = [2, 35715, 17859, -318417088, 8932, 17860, 1000009, 5] >>> v = transfac(v) -1 2 35715 17859 -318417088 8932 17860 Traceback (most recent call last): File "", line 1, in -toplevel- v = transfac(v) File "c:\math\factoring\factor30.py", line 46, in transfac a,b,c,d,m,n = a,b.c+a*t,d-b*t,m+t,n AttributeError: 'int' object has no attribute 'c' ############# Read the error message carefully then look at the code. int object with nom attribute c. where does c appear? You have a dot between b and c which I assume should be a comma. Dot notation is how you access attributes of an object - like the functions in a module for example. Sop Python is looki8ng for the c attribute of b but b is a number... 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 Feb 20 21:57:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Feb 2006 20:57:11 -0000 Subject: [Tutor] Debugging method References: <43FA17BB.000003.03660@YOUR-4105E587B6> Message-ID: <004601c63660$3861c650$0b01a8c0@xp> > I had looked the code over. I knew to look on that line, but was > totally > baffled because I could not distinguish the > comma from the period. You are using IDLE right? It sounds like you might need to change the font if the difference is not clear because that's a pretty important difference! Try the Options dialogue. Alan G. From ghashsnaga at gmail.com Mon Feb 20 23:44:23 2006 From: ghashsnaga at gmail.com (Ara Kooser) Date: Mon, 20 Feb 2006 15:44:23 -0700 Subject: [Tutor] simple list question Message-ID: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> Hello all, First off thank you to all the folks that gave input on a smallpox percolation model my students were working on last year. They won first place in the computation division at the science fair and took home the Intel Programming award. I can post or e-mail the code if anyone wants it. This should be simple but I've haven't programmed in python since I started my new job. I am running Python 2.4 on a Windows XP machine (my linux laptop crashed). Editing is done in Idle. # # Test of a room as list # room.py # room = [' ', ' ', ' ', ' ', '############', '#.................#', '#.................#', '#.................#', '#.................#', '#####.######'] print room, When the program runs my output is this: >>> [' ', ' ', ' ', ' ', '############', '#..........#', '#..........#', '############'] Why is that? I thought that adding , after the print command would allow the format to stay the same. Is there a better way of doing this (I like lists because I can edit them easily)? Thanks. Ara -- Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante Alighieri You were not made to live like brutes, but to pursue virtue and knowledge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/8fd7e6c5/attachment.html From john at fouhy.net Mon Feb 20 23:58:05 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 21 Feb 2006 11:58:05 +1300 Subject: [Tutor] simple list question In-Reply-To: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> Message-ID: <5e58f2e40602201458v46bf3b23t@mail.gmail.com> On 21/02/06, Ara Kooser wrote: > Why is that? I thought that adding , after the print command would allow > the format to stay the same. Is there a better way of doing this (I like > lists because I can edit them easily)? Thanks. A comma after a print statement basically replaces the newline with a space. Originally, I guess, this was just so that you could say 'print x, y, z'. >>> print 'foo', 'bar', 'baz' foo bar baz But it means you can also use a trailing comma to suppress the final newline. eg: >>> def p(): ... print 'foo' ... print 'bar' ... print 'baz' ... >>> def q(): ... print 'foo', ... print 'bar', ... print 'baz' ... >>> p() foo bar baz >>> q() foo bar baz As to formatting your list --- what exactly are you trying to achieve? -- John. From j1wise at yahoo.com Mon Feb 20 18:33:10 2006 From: j1wise at yahoo.com (Jason Wise) Date: Mon, 20 Feb 2006 09:33:10 -0800 (PST) Subject: [Tutor] C++ tutor Message-ID: <20060220173310.9982.qmail@web80514.mail.scd.yahoo.com> I am a grad student at Berkeley looking for a C++ tutor. Might you offer any suggestions? Thank you, jason wise From sjw28 at sussex.ac.uk Mon Feb 20 16:59:43 2006 From: sjw28 at sussex.ac.uk (Samantha Warbey) Date: Mon, 20 Feb 2006 15:59:43 +0000 Subject: [Tutor] question... Message-ID: <785D932781FC6A7849A40479@cs154052.pws.uscs.susx.ac.uk> I have blocks of text (in notebook files currently) that I need to read 3 and analyse 3 characters at a time. [This is because I'm studying genes and codons are three characters in length]. How do I do this using python? I've currently only been able to find ways of analysing text line by line, but as I read, this text is all in one long string. Thanks for your help, Sam. From dyoo at hkn.eecs.berkeley.edu Tue Feb 21 01:06:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Feb 2006 16:06:33 -0800 (PST) Subject: [Tutor] C++ tutor In-Reply-To: <20060220173310.9982.qmail@web80514.mail.scd.yahoo.com> Message-ID: On Mon, 20 Feb 2006, Jason Wise wrote: > I am a grad student at Berkeley looking for a C++ tutor. Might you offer > any suggestions? Thank you, jason wise Hi Jason. I think you may want to ask on a C++ oriented forum rather than Python-tutor, as you'll probably get better help there. Because you're going to my alma mater, I'd feel very bad if I didn't say something useful and localized. Check the Self-Paced Center: http://www-inst.eecs.berkeley.edu/~selfpace/ I used to be a tutor there. It's a great place because you'll pretty much get one-on-one tutoring on C++ if you invest the time. There are also several CS student societies at Berkeley that you may want to contact, including: Computer Science Undergraduate Association (CSUA) http://www.csua.berkeley.edu/ Eta Kappa Nu (HKN) http://hkn.eecs.berkeley.edu/ They will have people who should be competent, and they should be able to point you toward folks who can help you learn C++ personally. Otherwise, your best bet really should be to try to contact C++ forums, and not Python forums. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Feb 21 01:13:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Feb 2006 16:13:49 -0800 (PST) Subject: [Tutor] question... In-Reply-To: <785D932781FC6A7849A40479@cs154052.pws.uscs.susx.ac.uk> Message-ID: On Mon, 20 Feb 2006, Samantha Warbey wrote: > I have blocks of text (in notebook files currently) that I need to read > 3 and analyse 3 characters at a time. [This is because I'm studying > genes and codons are three characters in length]. How do I do this using > python? I've currently only been able to find ways of analysing text > line by line, but as I read, this text is all in one long string. Hi Samantha, Let's try to break the problem down to smaller easier pieces, and see where you're getting stuck. Consider the smaller problem of taking a single string, say: "ATGATC" Would you know how to write a function called firstCodon() that grabs the first three residues from an given input string? So, for example, if we had firstCodon, we might expect: firstCodon("ATGATC") ==> "ATG" Is writing something like firstCodon() something you'd be able to do? We're just trying to get a better sense at where you're getting stuck. You may be interested in: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers which is a list of beginner tutorials for Python. If you have more questions, please feel free to ask. Good luck to you! From kent37 at tds.net Tue Feb 21 01:19:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Feb 2006 19:19:41 -0500 Subject: [Tutor] simple list question In-Reply-To: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> Message-ID: <43FA5C9D.3020706@tds.net> Ara Kooser wrote: > Hello all, > > First off thank you to all the folks that gave input on a smallpox > percolation model my students were working on last year. They won first > place in the computation division at the science fair and took home the > Intel Programming award. I can post or e-mail the code if anyone wants it. > > This should be simple but I've haven't programmed in python since I > started my new job. > > I am running Python 2.4 on a Windows XP machine (my linux laptop > crashed). Editing is done in Idle. > > # > # Test of a room as list > # room.py > # > > room = [' ', ' ', ' ', ' ', > '############', > '#.................#', > '#.................#', > '#.................#', > '#.................#', > '#####.######'] > > print room, > > When the program runs my output is this: > >>> > [' ', ' ', ' ', ' ', '############', '#..........#', '#..........#', > '############'] > > Why is that? I thought that adding , after the print command would allow > the format to stay the same. Is there a better way of doing this (I like > lists because I can edit them easily)? Thanks. When you print a list, Python uses a standard format, not the format of the source code. For example, >>> lst= [ 1, 2, ... 3, ... 4,5] >>> lst [1, 2, 3, 4, 5] The original formatting is not preserved. You can use a loop to print each element on its own line: >>> for i in lst: ... print i ... 1 2 3 4 5 For anything fancier than that you have to write a fancier (OK, uglier) program: >>> def printRoom(room): ... print 'room = [%s,' % ''.join(repr(r)+', ' for r in room[:4]) ... for r in room[4:-1]: ... print ' ' + repr(r) + ',' ... print ' ' + repr(room[-1] + ']') ... >>> printRoom(room) room = [' ', ' ', ' ', ' ', , '############', '#.................#', '#.................#', '#.................#', '#.................#', '#####.######]' But really, what are you trying to do? Kent From dyoo at hkn.eecs.berkeley.edu Tue Feb 21 01:22:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Feb 2006 16:22:11 -0800 (PST) Subject: [Tutor] Generating small random integer In-Reply-To: <43F90A4C.00000D.03488@YOUR-4105E587B6> Message-ID: > I did try to read it from "cover to cover", but too quickly got into > places where I did not know what it talked about. Mind if we talk about some of those places? *grin* We might be able to help explain what the tutorial is trying to say, but you need to give us an opportunity. > So I am falling back on the tactic of using it as a reference to look > things up as I develope my program, and if I can't find the answer there > to ask you guys. The thing I'm slightly worried about is that the questions you're asking seem answered directly by the tutorials we're pointing you to. If there is something in the tutorials that's inscrutable, please talk about those. Perhaps we can improve the documentation if we can get an idea why it's not working for you. From dyoo at hkn.eecs.berkeley.edu Tue Feb 21 01:31:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 20 Feb 2006 16:31:29 -0800 (PST) Subject: [Tutor] MySQLdb : I finally got it to work. In-Reply-To: <43F7CC56.7060404@gmail.com> Message-ID: > 1. With my configuration, I need quotes around the values that are to be > placed into the database, otherwise an error is raised example: ( n= > blue --> Error 1054:n Unknown column 'blue' in 'field list' ) > n = raw_input("Please enter a Name: ") > c =raw_input("Please enter a Color: ") > cursor.execute("INSERT INTO horses(name,color) > VALUES('%s','%s')"%(n,c)) Hi Servando, This works. Be aware that cursor.execute() is a little smarter than you might think. The email I pointed to earlier covers what might go wrong, and how to avoid it going wrong. Here's the link again: http://mail.python.org/pipermail/tutor/2003-April/022010.html I'm just trying to make sure you understand the possibility of an "SQL injection attack" by bugging you about this. *grin* Good luck! From ghashsnaga at gmail.com Tue Feb 21 02:54:57 2006 From: ghashsnaga at gmail.com (Ara Kooser) Date: Mon, 20 Feb 2006 18:54:57 -0700 Subject: [Tutor] simple list question In-Reply-To: <43FA5C9D.3020706@tds.net> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> <43FA5C9D.3020706@tds.net> Message-ID: <2107481c0602201754q5f7dada8m38ddd272fe0341dc@mail.gmail.com> > > But really, what are you trying to do? > > Kent > > I am trying to create rooms/tiles for a roguelike game in python. I have some of the game coded out but I am having trouble with the map and character movement. Ara -- Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante Alighieri You were not made to live like brutes, but to pursue virtue and knowledge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/b841cc77/attachment.html From john at fouhy.net Tue Feb 21 03:01:41 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 21 Feb 2006 15:01:41 +1300 Subject: [Tutor] simple list question In-Reply-To: <2107481c0602201754q5f7dada8m38ddd272fe0341dc@mail.gmail.com> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> <43FA5C9D.3020706@tds.net> <2107481c0602201754q5f7dada8m38ddd272fe0341dc@mail.gmail.com> Message-ID: <5e58f2e40602201801p6e61af90p@mail.gmail.com> On 21/02/06, Ara Kooser wrote: > I am trying to create rooms/tiles for a roguelike game in python. I have > some of the game coded out but I am having trouble with the map and > character movement. Have you looked at QHack? It's a set of C sources for a minimal roguelike, intended to show how to get started. Written by Thomas Biskup (of ADOM fame). It might give you an idea of the kind of data structures you might be able to use to represent the map. -- John. From john at fouhy.net Tue Feb 21 03:02:04 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 21 Feb 2006 15:02:04 +1300 Subject: [Tutor] simple list question In-Reply-To: <5e58f2e40602201801p6e61af90p@mail.gmail.com> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> <43FA5C9D.3020706@tds.net> <2107481c0602201754q5f7dada8m38ddd272fe0341dc@mail.gmail.com> <5e58f2e40602201801p6e61af90p@mail.gmail.com> Message-ID: <5e58f2e40602201802v12f3b683q@mail.gmail.com> On 21/02/06, John Fouhy wrote: > Have you looked at QHack? Oops, I forgot the link: http://adom.de/misc/qhack.php3 -- John. From ghashsnaga at gmail.com Tue Feb 21 04:47:19 2006 From: ghashsnaga at gmail.com (Ara Kooser) Date: Mon, 20 Feb 2006 20:47:19 -0700 Subject: [Tutor] simple list question In-Reply-To: <43FA8C5E.2030606@tds.net> References: <2107481c0602201444h479208acpa989fdd9663d8298@mail.gmail.com> <43FA5C9D.3020706@tds.net> <2107481c0602201754q5f7dada8m38ddd272fe0341dc@mail.gmail.com> <43FA8C5E.2030606@tds.net> Message-ID: <2107481c0602201947g46b87563ub77979107a918bd0@mail.gmail.com> Thanks Kent for your help. Right now I am trying to get one room working with just a character and movement. Then on to creatures, multiple rooms and tracking. Ara On 2/20/06, Kent Johnson wrote: > > Ara Kooser wrote: > > > > > > But really, what are you trying to do? > > > > Kent > > > > > > I am trying to create rooms/tiles for a roguelike game in python. I have > > some of the game coded out but I am having trouble with the map and > > character movement. > > OK, so maybe you want something like this (I don't know what the initial > row of spaces is for in your post): > > >>> room = ['############', > ... '#.................#', > ... '#.................#', > ... '#.................#', > ... '#.................#', > ... '#####.######'] > >>> > >>> for line in room: > ... print line > ... > ############ > #.................# > #.................# > #.................# > #.................# > #####.###### > > Well, not quite like that. It looks like your original post is formatted > for a proportional font; you will probably have better luck sticking to > a fixed width font: > > >>> room = ['############', > ... '#..........#', > ... '#..........#', > ... '#..........#', > ... '#..........#', > ... '#####.######'] > >>> > >>> for line in room: print line > ... > ############ > #..........# > #..........# > #..........# > #..........# > #####.###### > > That looks more like a room. You will have to figure out how to organize > and print multiple rooms but maybe this will get you started on the > right track... > > Kent > > -- Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante Alighieri You were not made to live like brutes, but to pursue virtue and knowledge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060220/ec61e6aa/attachment.htm From oztriking at hotmail.com Tue Feb 21 07:19:52 2006 From: oztriking at hotmail.com (John Connors) Date: Tue, 21 Feb 2006 17:19:52 +1100 Subject: [Tutor] First Try 1.1 Message-ID: G'day, Thanks for the input on my lotto number selector program, very much appreciated and I learnt a lot. I've (hopefully) cleaned it up a little, and expanded it to write the numbers to a text file. I'm sure there must be a better way of doing it then the way I have. I understand that the "else" is not neccessary for the program to work but should I include it to show the end of the loop? I guess it's not important in a program like this that has only 1 loop but maybe it makes reading more complcated programs easier or is the indentation sufficient? import random # create or replace lotto.txt in my home directory file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n') # user input for number of games to choose how_many_games = int(raw_input('Enter how many games you would like generated : ')) print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # generate 6 random numbers between 1 and 45 inclusive lotto_numbers = random.sample(xrange(1,46), 6) # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # append the numbers to lotto.txt file('/home/mutt/lotto.txt','a').write('Game: ') file('/home/mutt/lotto.txt','a').write(str(game)) file('/home/mutt/lotto.txt','a').write(' ') file('/home/mutt/lotto.txt','a').write(str(lotto_numbers)) file('/home/mutt/lotto.txt','a').write('\n') print '\nHope you win!' file('/home/mutt/lotto.txt','a').write('\n\nHope you win!') John _________________________________________________________________ New year, new job – there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT From alan.gauld at freenet.co.uk Tue Feb 21 09:18:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 21 Feb 2006 08:18:58 -0000 Subject: [Tutor] C++ tutor References: <20060220173310.9982.qmail@web80514.mail.scd.yahoo.com> Message-ID: <006e01c636bf$76f7e9d0$0b01a8c0@xp> >I am a grad student at Berkeley looking for a C++ > tutor. Might you offer any suggestions? Thank you, Thinking in C++ by Bruce Eckel. A paper book also available online, very good. That having been said, C++ is a very tricky language to learn. There are a myriad of gotchas hiding in every nook and cranny Normally I don't recommend formal training for programming languages but C++ is one of the exceptions, try to get on a class if you can. (OTOH I still prefer C++ to Java!) Alan G. From kent37 at tds.net Tue Feb 21 11:53:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Feb 2006 05:53:00 -0500 Subject: [Tutor] First Try 1.1 In-Reply-To: References: Message-ID: <43FAF10B.3080604@tds.net> John Connors wrote: > I understand that the "else" is not neccessary for the program to work > but should I include it to show the end of the loop? I guess it's not > important in a program like this that has only 1 loop but maybe it makes > reading more complcated programs easier or is the indentation sufficient? 'else' in a for loop has a very specific meaning and usage - the else clause is executed only if the for loop completes normally, without executing a break statement. This is useful when you have a loop that is searching for some condition, and you want to execute some default code if the condition is never met. For example, a simple loop to search a list for a value and print a result could look like this (note: this is NOT the best way to solve this problem, it is just a simple example of for / else): >>> def search(value, lst): ... for item in lst: ... if value == item: ... print 'Found', value ... break ... else: ... print value, 'not found' ... >>> lst = range(10) >>> search(3, lst) Found 3 >>> search(11, lst) 11 not found for / else is very handy in this situation and should not be used just to show that the loop is over. Kent From oztriking at hotmail.com Tue Feb 21 12:02:50 2006 From: oztriking at hotmail.com (John Connors) Date: Tue, 21 Feb 2006 22:02:50 +1100 Subject: [Tutor] First Try 1.2 Message-ID: G'day :) I've added a little more to the program. It now sorts the game numbers from lowest to highest which makes filling out the tickets a lot easier, I've been putting off doing this because I wasn't sure how to go about it but once I started looking I found python does it all for me with .sort() Also added some extra user input so different types of lotto games can be played. Found a glaring bug...the program didn't pick the winning numbers for me and I'm now $6 poorer!!!!! Next on the to do list is add an option for a power ball, I actually did this tonight but I had 'if' statements all over the place. Which made the code unreadable so I'm going to work on a different way of doing it. I hope posting my efforts in here is ok. I learnt a lot after posting the first version of it but if I'm doing the wrong thing please tell me and I'll desist. import random # create or replace lotto.txt in my home directory file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n') # user input for number of games to generate how_many_games = int(raw_input('How many games you would like generated? ')) # user input for number of balls (to allow different lotto games) number_of_balls = int(raw_input('\nHow many balls are in the lotto you wish to play? ')) # user input for how many numbers per game (to allow systems entries) how_many_numbers = int(raw_input('\nHow many numbers you would like per game? ')) print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # generate 6 random numbers between 1 and 45 inclusive lotto_numbers = random.sample(xrange(1,number_of_balls + 1), how_many_numbers) lotto_numbers.sort() # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # append the numbers to lotto.txt file('/home/mutt/lotto.txt','a').write('Game: ') file('/home/mutt/lotto.txt','a').write(str(game)) file('/home/mutt/lotto.txt','a').write(' ') file('/home/mutt/lotto.txt','a').write(str(lotto_numbers)) file('/home/mutt/lotto.txt','a').write('\n') print '\nHope you win!' file('/home/mutt/lotto.txt','a').write('\n\nHope you win!') John _________________________________________________________________ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT From wescpy at gmail.com Tue Feb 21 12:50:09 2006 From: wescpy at gmail.com (w chun) Date: Tue, 21 Feb 2006 03:50:09 -0800 Subject: [Tutor] Generating small random integer In-Reply-To: <5e58f2e40602191600k39e81e75m@mail.gmail.com> References: <43F90436.000005.03488@YOUR-4105E587B6> <5e58f2e40602191600k39e81e75m@mail.gmail.com> Message-ID: <78b3a9580602210350k7d0dac59sef72714b142e7c77@mail.gmail.com> > You need to tell python that randint is in the random module. > ie, instead of calling randint(), call random.randint(). now this reminds me of something... and i think i need the help of the tutors here! :-) a long time ago, i recall that randint() was deprecated in favor of randrange(). then in 2.2.2, it was "rehabilitated." does anyone recall exactly what happened and why? thanks, -wesley From kent37 at tds.net Tue Feb 21 13:49:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Feb 2006 07:49:42 -0500 Subject: [Tutor] Generating small random integer In-Reply-To: <78b3a9580602210350k7d0dac59sef72714b142e7c77@mail.gmail.com> References: <43F90436.000005.03488@YOUR-4105E587B6> <5e58f2e40602191600k39e81e75m@mail.gmail.com> <78b3a9580602210350k7d0dac59sef72714b142e7c77@mail.gmail.com> Message-ID: <43FB0C66.1000808@tds.net> w chun wrote: >>You need to tell python that randint is in the random module. >>ie, instead of calling randint(), call random.randint(). > > > > now this reminds me of something... and i think i need the help of the > tutors here! :-) > > a long time ago, i recall that randint() was deprecated in favor of > randrange(). then in 2.2.2, it was "rehabilitated." does anyone > recall exactly what happened and why? This page in the 2.0 lib reference says, "Deprecated since release 2.0. Use randrange() instead.": http://www.python.org/doc/2.0/lib/rng-objects.html In 2.2.2 it is rehabilitated as you say: http://www.python.org/doc/2.2.2/lib/module-random.html http://www.python.org/2.2.2/NEWS.txt but no note in the What's New doc indicating why... Kent From Senthil_OR at Dell.com Tue Feb 21 17:38:31 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Tue, 21 Feb 2006 10:38:31 -0600 Subject: [Tutor] C++ tutor Message-ID: >I am a grad student at Berkeley looking for a C++ tutor. Might you >offer any suggestions? Thank you, http://groups.google.com/group/alt.comp.lang.learn.c-c++?lnk=li Is a list fot c,c++ similar to what this list serves for python. So, there u go. Senthil From alan.gauld at freenet.co.uk Tue Feb 21 18:53:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 21 Feb 2006 17:53:30 -0000 Subject: [Tutor] First Try 1.1 References: Message-ID: <009401c6370f$ba16c790$0b01a8c0@xp> > I understand that the "else" is not neccessary for the program to work but > should I include it to show the end of the loop? I guess it's not > important in a program like this that has only 1 loop but maybe it makes > reading more complcated programs easier or is the indentation sufficient? The indentation is fine, thats what its there for! :-) > # create or replace lotto.txt in my home directory > file('/home/mutt/lotto.txt','w').write('Here are your numbers:\n\n') opening and closing(implicitly) the file each time is both slow and expensive on computer resources. Just store the open file in a variable like this: output = file('/home/mutt/lotto.txt','w') output.write('a first string\n') output.write('a second string\n') output.write('a final string\n') output.close() Note that you need to explicitly add the newline (\n) at the end of each string. And explicitly closing the file is considered good practice. > lotto_numbers = random.sample(xrange(1,46), 6) You don't really need xrange, a simple range will suffice, but it does no harm. > # append the numbers to lotto.txt > file('/home/mutt/lotto.txt','a').write('Game: ') > file('/home/mutt/lotto.txt','a').write(str(game)) > file('/home/mutt/lotto.txt','a').write(' ') > file('/home/mutt/lotto.txt','a').write(str(lotto_numbers)) > file('/home/mutt/lotto.txt','a').write('\n') And you can use string forematting to create the string before writing: info = "Game: %3d\t%3d\n" % (game, lotto_numbers) output.write(info) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Tue Feb 21 20:38:23 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 21 Feb 2006 14:38:23 -0500 (Eastern Standard Time) Subject: [Tutor] Understanding the tutorial References: Message-ID: <43FB6C2F.000017.03824@YOUR-4105E587B6> From: Danny Yoo Date: 02/20/06 19:22:23 To: Kermit Rose Cc: Tutor; John Fouhy Subject: Re: [Tutor] Generating small random integer > The thing I'm slightly worried about is that the questions you're asking seem answered directly by the tutorials we're pointing you to. If there is something in the tutorials that's inscrutable, please talk about those. Perhaps we can improve the documentation if we can get an idea why it's not working for you. ***************** You do make a fair request. I'll make some comments about the primary tutorial. ***** Python Tutorial Guido van Rossum Python Software Foundation Email: docs at python.org Fred L. Drake, Jr., editor Release 2.4.2 28 September 2005 ******* Having the table of contents as hyperlinks is very good for using it as reference text. Thanks for that. **** 2.1 Invoking the Interpreter ******* is written with the unix programmer in mind. I do understand some unix, since I used to work on a unix system. But now the only system I have available is Microsoft windows. In windows I invoke the interpreter by clicking on the Python icon, or by selecting from the program list menu. ****** 2.1.1 Argument Passing ******* Since I do have some unix experience, I understand the idea of a script file but even so, it's not clear what should be in a Python script file. Having some sample scripts in hyperlinks would be very useful. The sample scripts could illustrate the different options and several simple Python commands by doing trivial programming tasks like Calculating powers of 3, Calculating square and square root table Sorting list by bubble sort method, etc. Then these sample scripts could be referenced throughout the tutorial at the relevant places. ******** 2.1.2 Interactive Mode ******* I understand this section. And I know how to do experiments in interactive mode to see what Phython does. So far, the interactive mode has been more useful to me than the tutorial. Perhaps as I gradually learn the Python philosophy and vocabulary, I'll more easily read the current tutorial. ******* 2.2.1 Error Handling ***** I skipped over this paragraph since I had not yet encountered any errors because I had not yet written any programs. ******** When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output. ******** I observed this when my program caused errors. ****** Typing the interrupt character (usually Control-C or DEL) to the primary or secondary prompt cancels the input and returns to the primary prompt.2 1Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement. ********* 2.2.2 Executable Python Scripts ******** Is written with unix programmer in mind. I imagine the windows programmer should use the dos prompt for the equivalent. Or perhaps there is some way to invoke the script from the Python shell. Examples should be given. ********* 2.2.3 Source Code Encoding ***** At this point I just about gave up reading from cover to cover. I have no idea what this paragraph is talking about. Perhaps examples would have made the meaning clear. Anyway, I continued scanning the tutorial, pausing when I read a section I already knew something about. So I learned that the Python shell can be used as a calculator, and learned that almost all the arithmetical expressions I'm used to from programming in fortran and C are valid in the shell. I did not find out how to write programs in the shell from reading the tutorial. I needed your on line assistance to find out how to do that. Anyway, these are a few comments about the tutorial. I am willing to continue with my critique of the tutorial if you wish. We could have an ongoing dialogue, taking the tutorial one small piece at a time. For I do wish to understand all of it, for I wish to write other programs in Python, eventually using all the capabilities of Python. Sincerly, Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060221/5742997b/attachment-0001.html From alan.gauld at freenet.co.uk Tue Feb 21 22:01:57 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 21 Feb 2006 21:01:57 -0000 Subject: [Tutor] Understanding the tutorial References: <43FB6C2F.000017.03824@YOUR-4105E587B6> Message-ID: <00b201c6372a$0d946160$0b01a8c0@xp> > 2.1 Invoking the Interpreter > is written with the unix programmer in mind. Thats true. Most early web tools were based around Unix and many still are. Unix is the best programmers OS without doubt. Therefore many programmers use Unix systems even when delivering on another one. (We developed the largest Windows NT system in our company by building initially on Unix and then porting the code to MS VC++, it wasn't until XP came out we finally moved the project to Windows) > In windows I invoke the interpreter by clicking on the Python icon But you can also start a DOS command prompt and type Pyton there. > 2.1.1 Argument Passing > Since I do have some unix experience, I understand the idea of a script > file > but even so, it's not clear what should be in a Python script file. The official tutorial is unambiguously aimed at experienced programmers. It does asume that concepts like scripting etc are well understood. Anyone who is less experienced shouyld try one of the gentler beginners tutors first. > Having some sample scripts in hyperlinks would be very useful. I do agree the official tutor is short on longer examples. One liners are all well and good but they don;t always give enough context. > So far, the interactive mode has been more useful to me than the tutorial. The >>> prompt is one of the insanely great features of Python. Only Smalltalk beats it as a productive environment IMHO... > 2.2.1 Error Handling > I skipped over this paragraph since I had not yet encountered any errors Now there's optimism for you! :-) > 2.2.2 Executable Python Scripts > Is written with unix programmer in mind. I imagine the windows > programmer > should use the dos prompt Or just double click the file in explorer > 2.2.3 Source Code Encoding > At this point I just about gave up reading from cover to cover. > I have no idea what this paragraph is talking about. I had to go look it up! I couldn't remember what it was. > an ongoing dialogue, taking the tutorial one small piece at a time. It might be useful, but many of your comments come down to 1) The Tutorial is Unix biased - no argument there 2) The tutorial is aimed at experienced programmers so assumes a lot of past experience/knowledge. There are other tutorials that take things from a less Unix/Professional angle(my own included!) and you might find those easier to deal with. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Tue Feb 21 22:37:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Feb 2006 13:37:37 -0800 (PST) Subject: [Tutor] Understanding the tutorial In-Reply-To: <43FB6C2F.000017.03824@YOUR-4105E587B6> Message-ID: > 2.1 Invoking the Interpreter > > ******* > is written with the unix programmer in mind. > I do understand some unix, since I used to work on a unix system. But now > the only system > I have available is Microsoft windows. > In windows I invoke the interpreter by clicking on the Python icon, or by > selecting from the program list menu. By the way, if your Windows installation is set up properly, it should also be possible to invoke Python from the command line by entering in 'python'. > ****** > 2.1.1 Argument Passing > ******* > Since I do have some unix experience, I understand the idea of a script > file but even so, it's not clear what should be in a Python script file. > Having some sample scripts in hyperlinks would be very useful. > The sample scripts could illustrate the different options and several simple > Python commands by > doing trivial programming tasks like > Calculating powers of 3, > Calculating square and square root table > Sorting list by bubble sort method, etc. > Then these sample scripts could be referenced throughout the tutorial at the > relevant places. Yes. The tutorial does have examples, but the examples could be a bit more polished. I'm not exactly sure if it's worth it to hyperlink the examples as separate pages, but I can see it of being of use. > mode to see what Phython does. > So far, the interactive mode has been more useful to me than the tutorial. > Perhaps as I gradually learn the Python philosophy and vocabulary, I'll more > easily read > the current tutorial. > ******* > 2.2.1 Error Handling > ***** > I skipped over this paragraph since I had not yet encountered any errors > because I had not yet > written any programs. Yes. I think that section on the bottom needs a concrete example of an error message, at least to give a taste of what is being talked about. The tutorial talks about errors in more detail in Section 8, so perhaps a note about this might be appropriate there. > 2.2.2 Executable Python Scripts > > ******** > Is written with unix programmer in mind. I imagine the windows programmer > should use the dos prompt > for the equivalent. Or perhaps there is some way to invoke the script from > the Python shell. > Examples should be given. Agreed. > ********* > 2.2.3 Source Code Encoding > > ***** > At this point I just about gave up reading from cover to cover. Ah! Skip that for now. The issue it's addressing is one of textual encoding: because Python lives in a world with different languages, it is no longer valid to always assume that a text file's in ASCII all the time. Some programs might be written using the Unicode character set, for example. Because files don't have metadata associated to them in general, Python resorts to allowing the first few lines to contain some self-describing "source encoding" to tell Python what the proper interpretation should be. These issues are similar to the ones that HTML pages have to deal with too, so there is some assumed knowledge here in the tutorial. If you are interested, see: http://www.joelonsoftware.com/articles/Unicode.html > Anyway, these are a few comments about the tutorial. I am willing to > continue with my critique of the tutorial if you wish. This would be fine; that's what this Python-Tutor list is for, to allow us programmers to support and teach each other. > We could have an ongoing dialogue, taking the tutorial one small piece > at a time. For I do wish to understand all of it, for I wish to write > other programs in Python, eventually using all the capabilities of > Python. I treat the official tutorial as a quick way of seeing many of the important features in Python, but I don't treat it as comprehensive. It does gloss over a lot. But here is a more satisfying tutorial that is also available for free: http://diveintopython.org/ >From our conversation, I think you will enjoy Dive Into Python a lot more than the official tutorial; try it out! From srini_iyyer_bio at yahoo.com Tue Feb 21 23:04:42 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 21 Feb 2006 14:04:42 -0800 (PST) Subject: [Tutor] Substitution problem In-Reply-To: Message-ID: <20060221220442.16662.qmail@web34506.mail.mud.yahoo.com> Dear group, I am trying to automate a process in statistical language R. There for 1 operation 50 lines of code is written. This process query postgres database and does some processing on the resulting data and writes back a file. I want to replicate the 50 line code, 90 times, by substituting with postgres.table_id and file name at 2 places. File_A: 1 \t molA 2 \t molB 3 \t molC ........ 90 \t molABC File_B: (R-code) (50 lines) library(Rdbi) library(RdbiPgSQL) library(Biobase) library(multtest) conn <- dbConnect(PgSQL(),dbname = 'mol-test') mq = "SELECT DISTINCT target.target_name, go_term from target, comb, moltab,gos,sequence,go_seq where target.target_id = comb.target_id AND comb.mol_id = $MOL_ID AND target.target_name = sequence.seq_name AND sequence.seq_id = go_seq.seq_id AND go_seq.gos_id = gos.gos_id AND gos.go_cat = 'F';" ........... ........... write.table(mol_towrite,"$MOL_NAME_adj_pval",sep='t',quote=F,col.names=F) ### Here there are two varialbes, $MOL_ID and $MOL_NAME in select statement and write.table statement respectively. I want to read File_A, loop through it and substitute $MOL_ID = 1 and $MOL_NAME = A I want to reproduce 50 lines * 90 times substituting ID and NAME by looping through File_A. I tried using re module, I do not know if this correct or wrong. for m in file_A: cols = m.split('\t') molid = cols[0].strip() molname = cols[1].strip() for k in file_B: pat1 = '$MOL_ID' pat2 = '$MOL_NAME' if re.search(pat1,k): s = Template(k) s.substitute($MOL_ID,molid) if re.search(pat2,k): t = Template(k) t.substitute($MOL_NAME,molname) However, this is not working, somehow. Can any one help me please. If more simple methods are available please show a new way. Thanks Sri __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Tue Feb 21 23:30:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Feb 2006 17:30:24 -0500 Subject: [Tutor] Substitution problem In-Reply-To: <20060221220442.16662.qmail@web34506.mail.mud.yahoo.com> References: <20060221220442.16662.qmail@web34506.mail.mud.yahoo.com> Message-ID: <43FB9480.8090209@tds.net> Srinivas Iyyer wrote: > Dear group, > I am trying to automate a process in statistical > language R. > > There for 1 operation 50 lines of code is written. > This process query postgres database and does some > processing on the resulting data and writes back a > file. > > I want to replicate the 50 line code, 90 times, by > substituting with postgres.table_id and file name at 2 > places. > I want to read File_A, loop through it and substitute > $MOL_ID = 1 and $MOL_NAME = A > > I want to reproduce 50 lines * 90 times substituting > ID and NAME by looping through File_A. > > > I tried using re module, I do not know if this correct > or wrong. > > > for m in file_A: > cols = m.split('\t') > molid = cols[0].strip() > molname = cols[1].strip() > for k in file_B: > pat1 = '$MOL_ID' > pat2 = '$MOL_NAME' > if re.search(pat1,k): > s = Template(k) > s.substitute($MOL_ID,molid) > if re.search(pat2,k): > t = Template(k) > t.substitute($MOL_NAME,molname) > > > However, this is not working, somehow. You don't need regexes for this, string replace will do what you want. >>> s = '''write.table(mol_towrite,"$MOL_NAME_adj_pval",sep='t',quote=F,col.names=F)''' >>> s2 = s.replace('$MOL_NAME', 'my data') >>> s2 'write.table(mol_towrite,"my data_adj_pval",sep=\'t\',quote=F,col.names=F)' Your program could - read all of file B with open('file_B').read() - for each line of file A - split the line - substitute for '$MOL_ID' and '$MOL_NAME' - write the modified string to your output file BTW $ is a special character in a regex, you need to escape it as \$ > > Can any one help me please. If more simple methods are > available please show a new way. You might take a look at RPy, it would probably let you do all the work in a Python program instead of writing an R code generator. Kent From dyoo at hkn.eecs.berkeley.edu Wed Feb 22 00:00:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Feb 2006 15:00:25 -0800 (PST) Subject: [Tutor] Understanding the tutorial (fwd) Message-ID: [Keeping tutor in CC] ---------- Forwarded message ---------- Date: Tue, 21 Feb 2006 17:49:34 -0500 (Eastern Standard Time) From: Kermit Rose To: Danny Yoo Subject: Re: [Tutor] Understanding the tutorial From: Danny Yoo Date: 02/21/06 16:38:27 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] Understanding the tutorial http://www.joelonsoftware.com/articles/Unicode.html ************ Hello Danny! Thanks very much. I found the unicode articles very interesting. I had known nothing about unicode before. ****** But here is a more satisfying tutorial that is also available for free: http://diveintopython.org/ >From our conversation, I think you will enjoy Dive Into Python a lot more than the official tutorial; try it out! *************** Yes. Thanks very much. I've downloaded the PDF version of the tutorial. The table of contents makes it look exactly what I need. I remember now that I had been pointed to this tutorial before, but did not investigate properly. Thanks Kermit < kermit at polaris.net > From dafydd61 at sideshowmedia.ca Wed Feb 22 01:20:07 2006 From: dafydd61 at sideshowmedia.ca (dafydd hughes) Date: Tue, 21 Feb 2006 19:20:07 -0500 Subject: [Tutor] pyPortMidi channel Message-ID: <4C5AA2E2-6E98-4725-A386-AE7E9879DE22@sideshowmedia.ca> Hi folks I'm more or less brand new to Python and having a great time learning it. I'm trying to get Python to send MIDI data using pyPortMidi, but I can't figure out how to specify MIDI channels. Is this possible and if so, can anybody tell me how's it done? thanks for any help cheers dafydd From ryan_gm at sbcglobal.net Wed Feb 22 03:08:58 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Tue, 21 Feb 2006 18:08:58 -0800 (PST) Subject: [Tutor] Translator Message-ID: <20060222020858.12096.qmail@web80830.mail.yahoo.com> Hello, this is just a simple things for a random person im tryin to help out but it seems i got in alittle over my head =P, What i need is a program that translates english in-to this completly made up language this person has. The only way i can think of doin this seems...well like a very bad way of doin it. get the input from user then do alot of if input == "a": print "blah" for example ect I know there has to be a easier way, Any help? thanks From john at fouhy.net Wed Feb 22 03:37:00 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 22 Feb 2006 15:37:00 +1300 Subject: [Tutor] Translator In-Reply-To: <20060222020858.12096.qmail@web80830.mail.yahoo.com> References: <20060222020858.12096.qmail@web80830.mail.yahoo.com> Message-ID: <5e58f2e40602211837g3a61e954m@mail.gmail.com> On 22/02/06, ryan luna wrote: > What i need is a program that translates english in-to > this completly made up language this person has. Well, it depends how sophisticated your made-up language is. If you're just replacing one word by another, you can use (appropriately enough) a dictionary. You can read about dictionaries in the tutorial here: http://docs.python.org/tut/node7.html#SECTION007500000000000000000 If you want to do genuine translation, like English to French or something, then, well, ask someone who works at Google :-) -- John. From oasf2004 at yahoo.com Wed Feb 22 03:36:33 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 21 Feb 2006 18:36:33 -0800 (PST) Subject: [Tutor] Python & XEmacs Message-ID: <20060222023633.34700.qmail@web60018.mail.yahoo.com> Hello: Could anyone, please, suggest a "tutorial" about Python Mode for XEmacs? I would like to use XEmacs, but unfortunately, I didn't find any good documentation about using it for programming in Python Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From hugonz-lists at h-lab.net Wed Feb 22 03:48:10 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 21 Feb 2006 20:48:10 -0600 Subject: [Tutor] Bug in python In-Reply-To: <43F8B965.000003.01932@YOUR-4105E587B6> References: <43F8B965.000003.01932@YOUR-4105E587B6> Message-ID: <43FBD0EA.2040505@h-lab.net> Hi, just a recommendation: try not to assume a bug beforehand, that's a quick way to get flames or just get plain ignored, especially in a list for beginners. > The * is being given equal priority to %. > > Why isn't % given higher priority than *? Why should it? Doesn't it make sense that as '/' and * have the same precedence, '%' should have the same? Check the precedence for python operators here: http://www.byteofpython.info/read/operator-precedence.html http://docs.python.org/ref/summary.html Check the precedence for C operators here: http://publications.gbdirect.co.uk/c_book/chapter2/expressions_and_arithmetic.html So everything alright, also, left to right, as expected. > Also, why am I getting a syntax error in the following? > To get more informative messages, save all those statements to a file, and then try and run the file. It is extremely easy to mess up indentantion and make mistakes in the interactive prompt. Aslo you'll be getting information about the line number and such. Hugo From ryan_gm at sbcglobal.net Wed Feb 22 04:43:11 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Tue, 21 Feb 2006 19:43:11 -0800 (PST) Subject: [Tutor] Translator Message-ID: <20060222034311.63788.qmail@web80827.mail.yahoo.com> Well yeah its pretty basic, Just *Example* a = ba just having a little trouble working out the code, Still pretty new to python From wescpy at gmail.com Wed Feb 22 06:16:51 2006 From: wescpy at gmail.com (w chun) Date: Tue, 21 Feb 2006 21:16:51 -0800 Subject: [Tutor] Python & XEmacs In-Reply-To: <20060222023633.34700.qmail@web60018.mail.yahoo.com> References: <20060222023633.34700.qmail@web60018.mail.yahoo.com> Message-ID: <78b3a9580602212116k79f2084epf47bfa107cb107bd@mail.gmail.com> > Could anyone, please, suggest a "tutorial" about > Python Mode for XEmacs? I would like to use XEmacs, > but unfortunately, I didn't find any good > documentation about using it for programming in Python i don't know if there really is a 'tutorial'. i assume you've already found these websites: http://sourceforge.net/projects/python-mode/ http://www.python.org/emacs/ http://www.emacswiki.org/cgi-bin/wiki/PythonMode are you trying to learn Python, learn (X)Emacs, both, or neither? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at freenet.co.uk Wed Feb 22 06:59:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Feb 2006 05:59:44 -0000 Subject: [Tutor] Translator References: <20060222020858.12096.qmail@web80830.mail.yahoo.com> Message-ID: <00da01c63775$2dedac50$0b01a8c0@xp> > What i need is a program that translates english in-to > this completly made up language this person has. Language translation isone of those topics that sounds like it should be straightforward but is actually very hard. Illustration: A translator was built (back in the 70s?) to translate between English and Russian. To tet it they fed in the phrase "Out of sight, out of mind" and then fed the result back in again to see what came back out. The result was "Invisible, idiot"... I'm not sure how true that story is but it illustrates the point well. If you do want a basic approach you can base it around a set of dictionaries, but the tricky bit is handling word endings and context/grammar etc. HTH, Alan G. From alan.gauld at freenet.co.uk Wed Feb 22 07:02:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Feb 2006 06:02:51 -0000 Subject: [Tutor] Python & XEmacs References: <20060222023633.34700.qmail@web60018.mail.yahoo.com> Message-ID: <00e201c63775$9d8b2100$0b01a8c0@xp> > Could anyone, please, suggest a "tutorial" about > Python Mode for XEmacs? I would like to use XEmacs, > but unfortunately, I didn't find any good > documentation about using it for programming in Python I'm not sure how much you are looking for but Python mode should be similar to other programming modes so maybe cheking the info system for c-mode will give you the bits you need. Presumabnly ther is an info page for Python-mode too, but as I don't use it I've never looked! Alan G. From oztriking at hotmail.com Wed Feb 22 09:57:30 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 22 Feb 2006 19:57:30 +1100 Subject: [Tutor] First Try 1.2 In-Reply-To: Message-ID: G'day, Added a power ball option to the lotto program today. The program does way more then I ever intended when I started it so I'll try a new project. Maybe I'll come back to it when I try out Tkinter and try to give it a GUI. Anyway....here's my latest effort. import random # store the /home/mutt/lotto.txt in f f = file('/home/mutt/lotto.txt','w') # create or replace lotto.txt in my home directory f.write('Here are your numbers:\n\n') # user input for number of games to generate how_many_games = int(raw_input('How many games you would like generated? ')) # user input for number of balls (to allow different lotto games) number_of_balls = int(raw_input('\nHow many balls are in the lotto you wish to play? ')) # user input for how many numbers per game (to allow systems entries) how_many_numbers = int(raw_input('\nHow many numbers you would like per game? ')) # check if there is a power ball chk_pwrball = raw_input('Is there a power ball? (y/n) ') print '\n\nHere are your numbers : \n' # loop for the number of games selected by user for game in range(1, how_many_games + 1): # generate 6 random numbers between 1 and 45 inclusive then sort them lotto_numbers = random.sample(range(1,number_of_balls + 1), how_many_numbers) lotto_numbers.sort() if chk_pwrball == 'n': # Right justified in 3 character width then a tab (\t) then a blank line (\n) print '%3s\t%s\n' % (game, lotto_numbers) # write the numbers to lotto.txt save_numbers = 'Game: %3s\t%3s\n' % (game, lotto_numbers) f.write(save_numbers) if chk_pwrball == 'y': pwrball = random.sample(range(1,number_of_balls +1), 1) print '%3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) save_numbers = 'Game: %3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, pwrball) f.write(save_numbers) print '\nHope you win!' f.write('\nHope you win!') f.close() John _________________________________________________________________ Shopping made easy @ tradingpost.com.au http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fwww%2Etradingpost%2Ecom%2Eau%2F%3Freferrer%3DnmsnHMetagv1&_t=753082530&_r=emailtagline&_m=EXT From kent37 at tds.net Wed Feb 22 12:00:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Feb 2006 06:00:06 -0500 Subject: [Tutor] First Try 1.2 In-Reply-To: References: Message-ID: <43FC4436.9010503@tds.net> John Connors wrote: > import random > > # store the /home/mutt/lotto.txt in f > f = file('/home/mutt/lotto.txt','w') > # create or replace lotto.txt in my home directory > f.write('Here are your numbers:\n\n') > The comments don't really add anything to the program. Comments that restate exactly what the code is doing are not that helpful. The code should be clear by itself. As a beginner they may seem like a helpful crutch but you will get better at reading the code. For example, how_many_games = int(raw_input('How many games you would like generated? ')) is well-written and expressive. With the helpful variable name and the input prompt it's pretty easy to figure out what it does. Adding the comment # user input for number of games to generate actually obscures the code without adding to its comprehensibility. A better choice might be to have one comment for the whole block of user input code, something like # Get required user input Good comments describe the code at a higher level than the code itself, or explain tricky bits. Comments that give a blow-by-blow account of the code just get in the way. I will often break my code into small chunks with a comment before each chunk that says what it does. Then it is very easy to skim the code and skip sections I'm not interested in. > # user input for number of games to generate > how_many_games = int(raw_input('How many games you would like generated? ')) > # user input for number of balls (to allow different lotto games) > number_of_balls = int(raw_input('\nHow many balls are in the lotto you wish > to play? ')) > # user input for how many numbers per game (to allow systems entries) > how_many_numbers = int(raw_input('\nHow many numbers you would like per > game? ')) > # check if there is a power ball > chk_pwrball = raw_input('Is there a power ball? (y/n) ') Here is another reason why it is a bad idea to just describe the code in the comments - often the code changes and the comment doesn't. Now you have an inaccurate comment which is worse than no comment at all. > # generate 6 random numbers between 1 and 45 inclusive then sort them > lotto_numbers = random.sample(range(1,number_of_balls + 1), > how_many_numbers) > print '\nHope you win!' Good luck! Kent From rakesh.mishra at gmail.com Wed Feb 22 12:29:47 2006 From: rakesh.mishra at gmail.com (Rakesh Mishra) Date: Wed, 22 Feb 2006 16:59:47 +0530 Subject: [Tutor] Unable to take input as a module Message-ID: <39ce20e10602220329p13d6969dn68eb31ac5202c14f@mail.gmail.com> hi I am trying to write a program, which ask for user input for a name then determines it wither that is module or not, if module then it will tell all its attributes, methods, function etc my code: .......... . import sys, types, string, inspect input= sys.argv[1] print inspect.ismodule(input) ................ here it always give false. as what ever input i take it is string . my problem is i am not able to take input as a module help me out ! thanks in advance. rakesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/25c5efaa/attachment.html From oztriking at hotmail.com Wed Feb 22 12:43:52 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 22 Feb 2006 22:43:52 +1100 Subject: [Tutor] Repeating a routine Message-ID: G'day, With my only programming experience being C-64 Basic I'm finding that I struggle a bit understanding some of the concepts of Python, I wish I could block basic right out of my brain. One of the things I can't get a grasp of is how to repeat a routine many times. For example a simple dice game where 6 dice are rolled, any that come up as 1 are kept, you keep rolling the dice until a 1 is not rolled. A program to do that would need to generate a random number between 1 and 6 many times. In basic I would have made a sub routine for the random number. Only way I can think of to do it in python is to have a seperate script. And at the end of the game I might want to play again and it would be nice to have something like - Play dice game again (y/n). I'm not sure how to run the program again other then re-loading it. I know goto and gosub are evil, bad habits but I'm starting to miss them. John _________________________________________________________________ New year, new job – there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT From oztriking at hotmail.com Wed Feb 22 12:50:02 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 22 Feb 2006 22:50:02 +1100 Subject: [Tutor] First Try 1.2 In-Reply-To: <43FC4436.9010503@tds.net> Message-ID: G'day Kent, Thanks for the input. >The comments don't really add anything to the program. Comments that >restate exactly what the code is doing are not that helpful. The code >should be clear by itself. As a beginner they may seem like a helpful >crutch but you will get better at reading the code. Very good point. I have to go away for 3 weeks in a couple of days and I was trying to leave helpful hints to myself in the code so I won't forget what I have learnt. But you are right, I got carried away and most were just getting in the way. John _________________________________________________________________ Shopping made easy @ tradingpost.com.au http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fwww%2Etradingpost%2Ecom%2Eau%2F%3Freferrer%3DnmsnHMetagv1&_t=753082530&_r=emailtagline&_m=EXT From khp at pflaesterer.de Wed Feb 22 13:06:13 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Wed, 22 Feb 2006 13:06:13 +0100 Subject: [Tutor] Unable to take input as a module In-Reply-To: <39ce20e10602220329p13d6969dn68eb31ac5202c14f@mail.gmail.com> (Rakesh Mishra's message of "Wed, 22 Feb 2006 16:59:47 +0530") References: <39ce20e10602220329p13d6969dn68eb31ac5202c14f@mail.gmail.com> Message-ID: On 22 Feb 2006, rakesh.mishra at gmail.com wrote: > my code: > .......... > . > import sys, types, string, inspect > > input= sys.argv[1] > print inspect.ismodule(input) > ................ > > here it always give false. as what ever input i take it is string . > > my problem is i am not able to take input as a module > help me out ! Go the other way. Every module has an atribute called `__name__'. And this is a string. So compare the user input with e.g `sys.__name__' (which is 'sys'). Karl -- Please do *not* send copies of replies to me. I read the list From burge.kurt at gmail.com Wed Feb 22 14:36:59 2006 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 22 Feb 2006 14:36:59 +0100 Subject: [Tutor] twisted Message-ID: Hi, I could not get a reply from twisted-web mailing list so I want to try my chance here.. I want to create an httpserver behind a twisted-server. Actually I have got a twisted server which is running(i did not code it!) and also some samples of simple httpserver codes but don't know how to integrate the httpserver into twisted :( I hope to get a reply (: thanks in advance! Burge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/9f6f618d/attachment.htm From broek at cc.umanitoba.ca Wed Feb 22 15:58:24 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 22 Feb 2006 08:58:24 -0600 Subject: [Tutor] Repeating a routine In-Reply-To: References: Message-ID: <43FC7C10.3040508@cc.umanitoba.ca> John Connors said unto the world upon 22/02/06 05:43 AM: > G'day, > > With my only programming experience being C-64 Basic I'm finding that I > struggle a bit understanding some of the concepts of Python, I wish I > could block basic right out of my brain. > > One of the things I can't get a grasp of is how to repeat a routine many > times. For example a simple dice game where 6 dice are rolled, any that > come up as 1 are kept, you keep rolling the dice until a 1 is not rolled. > > A program to do that would need to generate a random number between 1 > and 6 many times. In basic I would have made a sub routine for the > random number. Only way I can think of to do it in python is to have a > seperate script. > > And at the end of the game I might want to play again and it would be > nice to have something like - Play dice game again (y/n). I'm not sure > how to run the program again other then re-loading it. > > I know goto and gosub are evil, bad habits but I'm starting to miss them. > > John Hi John, I came to python with only some ill-recalled BASIC, and I also (initially) missed goto, etc. You'll get over it :-) See if the examples below give you a push. (I've purposely chosen ones silent on the die-rolling logic.) >>> def doit(): print "Working!" >>> for i in range(6): doit() Working! Working! Working! Working! Working! Working! >>> That is a minimal way to define some action and do it repeatedly. You will also need to return some value for your use case. So consider: >>> def getit(): val = raw_input("Gimme!\n") return val >>> vals = [] >>> for i in range(3): vals.append(getit()) Gimme! righty'oh Gimme! I did Gimme! OK >>> vals ["righty'oh", 'I did', 'OK'] >>> HTH, Brian vdB From oasf2004 at yahoo.com Wed Feb 22 16:26:39 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 22 Feb 2006 07:26:39 -0800 (PST) Subject: [Tutor] Python & XEmacs In-Reply-To: <78b3a9580602212116k79f2084epf47bfa107cb107bd@mail.gmail.com> Message-ID: <20060222152639.36939.qmail@web60016.mail.yahoo.com> --- w chun wrote: > > Could anyone, please, suggest a "tutorial" about > > Python Mode for XEmacs? I would like to use > XEmacs, > > but unfortunately, I didn't find any good > > documentation about using it for programming in > Python > > > i don't know if there really is a 'tutorial'. i > assume you've already > found these websites: > > http://sourceforge.net/projects/python-mode/ > http://www.python.org/emacs/ > http://www.emacswiki.org/cgi-bin/wiki/PythonMode > > are you trying to learn Python, learn (X)Emacs, > both, or neither? > > -- wesley > Hello W Chun: Thanks for the websites. However, I DIDN'T like your last question, when you say "...neither?" That WAS NOT gentle! If you didn't like to answer a post, it is much better not to say anything. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ewald.ertl at hartter.com Wed Feb 22 16:40:31 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 22 Feb 2006 16:40:31 +0100 Subject: [Tutor] Unable to take input as a module In-Reply-To: <39ce20e10602220329p13d6969dn68eb31ac5202c14f@mail.gmail.com> References: <39ce20e10602220329p13d6969dn68eb31ac5202c14f@mail.gmail.com> Message-ID: <43FC85EF.80002@hartter.com> Hello rakesh, Perhaps this could take you further: [GCC 3.3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> a=__import__("inspect") >>> a >>> a.ismodule(a) True HTH Ewald Rakesh Mishra wrote: > hi > > I am trying to write a program, which ask for user input for a name > then determines it wither that is module or not, if module then it will > tell all its > attributes, methods, function etc > > my code: > .......... > . > import sys, types, string, inspect > > input= sys.argv[1] > print inspect.ismodule(input) > ................ > > here it always give false. as what ever input i take it is string . > > my problem is i am not able to take input as a module > help me out ! > thanks in advance. > rakesh > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From broek at cc.umanitoba.ca Wed Feb 22 16:53:39 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 22 Feb 2006 09:53:39 -0600 Subject: [Tutor] Python & XEmacs In-Reply-To: <20060222152639.36939.qmail@web60016.mail.yahoo.com> References: <20060222152639.36939.qmail@web60016.mail.yahoo.com> Message-ID: <43FC8903.6090305@cc.umanitoba.ca> Hoffmann said unto the world upon 22/02/06 09:26 AM: > --- w chun wrote: > > >>>Could anyone, please, suggest a "tutorial" about >>>Python Mode for XEmacs? I would like to use >>are you trying to learn Python, learn (X)Emacs, >>both, or neither? >> >>-- wesley >> > > > Hello W Chun: > > Thanks for the websites. However, I DIDN'T like your > last question, when you say "...neither?" > That WAS NOT gentle! > If you didn't like to answer a post, it is much better > not to say anything. > > Hoffmann Hoffmann, not to speak for Wesley, but: dial it down a notch. Breath. In. Then out. In: >>are you trying to learn Python, learn (X)Emacs, >>both, or neither? on one read of "neither" it is marking the possibility that you know Python, you know (X)Emacs and you merely need to learn how to make the two work together. (Thus, neither is such that you are trying to learn it.) Bet a 1$ that reading was the intended one. Brian vdB From ryan_gm at sbcglobal.net Wed Feb 22 17:11:16 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Wed, 22 Feb 2006 08:11:16 -0800 (PST) Subject: [Tutor] Translator Message-ID: <20060222161116.93052.qmail@web80832.mail.yahoo.com> Well see, its not a complex language at all, Here is basicly what it is a = ba. b = ga. somthing like that, my only problem is getting it to translate muiltpul letters at a time say the user types a it prints ba like it should, but if the user types in ab it prints ab not baga From kent37 at tds.net Wed Feb 22 17:32:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Feb 2006 11:32:20 -0500 Subject: [Tutor] Translator In-Reply-To: <20060222161116.93052.qmail@web80832.mail.yahoo.com> References: <20060222161116.93052.qmail@web80832.mail.yahoo.com> Message-ID: <43FC9214.3070206@tds.net> ryan luna wrote: > Well see, its not a complex language at all, > Here is basicly what it is > a = ba. > b = ga. > somthing like that, my only problem is getting it to > translate muiltpul letters at a time > say the user types a > it prints > ba like it should, > but if the user types in ab > it prints ab > not baga Check out this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Kent From benmarkwell at gmail.com Wed Feb 22 17:52:59 2006 From: benmarkwell at gmail.com (benmarkwell at gmail.com) Date: Wed, 22 Feb 2006 11:52:59 -0500 Subject: [Tutor] ftplib error Message-ID: I'm trying to write a backup script to put files on a server. --This is how I have begun: from ftplib import FTP f = open(r'g:\dev\python\exercises\aaa.py', 'r') fname = r'g:\dev\python\exercises\aaa.py' ftp = FTP('ftp.xxxx.com') ftp.login() ftp.storlines('STOR ' + fname, f) ftp.retrlines('LIST') f.close() ftp.close() print 'success!' -- And this is what gets returned to the prompt: Traceback (most recent call last): File "G:\Dev\Python\Scripts\backup.py", line 14, in ? ftp.storlines('STOR ' + fname, f) File "F:\Python24\lib\ftplib.py", line 426, in storlines conn = self.transfercmd(cmd) File "F:\Python24\lib\ftplib.py", line 345, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "F:\Python24\lib\ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "F:\Python24\lib\ftplib.py", line 241, in sendcmd return self.getresp() File "F:\Python24\lib\ftplib.py", line 216, in getresp raise error_perm, resp ftplib.error_perm: 550 g:\dev\python\exercises\aaa.py: The filename, directory name, or volume label syntax is incorrect. The filename and directory name is correct. I don't know about the volume label syntax. I've given up trying to find a solution. All help appreciated. Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/77301d1d/attachment.htm From Pawel_Kraszewski at wp.pl Wed Feb 22 17:49:18 2006 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Wed, 22 Feb 2006 17:49:18 +0100 Subject: [Tutor] Repeating a routine In-Reply-To: References: Message-ID: <200602221749.18273.Pawel_Kraszewski@wp.pl> Dnia ?roda, 22 lutego 2006 12:43, John Connors napisa?: > I know goto and gosub are evil, bad habits but I'm starting to miss them. You SHOULD miss them. GOSUB is called a function call in Python (you call a function by its name, rather than by its starting line number) Someone misinformed you: GOSUB is perfectly good. It's GOTO that's evil. From kent37 at tds.net Wed Feb 22 18:08:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Feb 2006 12:08:03 -0500 Subject: [Tutor] ftplib error In-Reply-To: References: Message-ID: <43FC9A73.7030400@tds.net> benmarkwell at gmail.com wrote: > I'm trying to write a backup script to put files on a server. > > --This is how I have begun: > > > from ftplib import FTP > > f = open(r'g:\dev\python\exercises\aaa.py', 'r') > fname = r'g:\dev\python\exercises\aaa.py' > > ftp = FTP('ftp.xxxx.com ') > ftp.login() > > ftp.storlines ('STOR ' + fname, f) fname should be just a bare name, e.g. 'aaa.py'. You have to ftp.cwd() to the correct directory yourself. Here is a module I use for ftp upload, it has a nicer API than the bare ftplib: http://www.nedbatchelder.com/code/modules/ftpupload.html Kent From brian at daviesinc.com Wed Feb 22 18:14:12 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 22 Feb 2006 12:14:12 -0500 Subject: [Tutor] Repeating a routine In-Reply-To: <200602221749.18273.Pawel_Kraszewski@wp.pl> References: <200602221749.18273.Pawel_Kraszewski@wp.pl> Message-ID: <43FC9BE4.7000803@daviesinc.com> yeah GOTO , in basic (I used to write software in Commodore BASIC myself) is similar to a for or while loop - In BASIC, you would write a program, *including* line numbers thus: 10 a=32 20 b="hello" 30 print a 40 print b 50 a=a-1 60 if a > 0 goto 20 70 end (It's probably not 100% syntactically correct, but the general idea is it would print "hello" 33 times and then end..) in python, you would do : a=32 b=hello c=0 while c <= a: print b c = c+1 for the same results- that's what GOTO in BASIC would be used for BASIC also had subroutines, which are GOSUB, which equate to perl's sub, php's function, or python's def Just my 2 cents worth :) Bri! Pawel Kraszewski wrote: > Dnia ?roda, 22 lutego 2006 12:43, John Connors napisa?: > > > >>I know goto and gosub are evil, bad habits but I'm starting to miss them. > > > You SHOULD miss them. GOSUB is called a function call in Python (you call a > function by its name, rather than by its starting line number) > > Someone misinformed you: GOSUB is perfectly good. It's GOTO that's evil. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:43fc986c278471677385699! > > From wpmartin at patm.net Wed Feb 22 18:19:49 2006 From: wpmartin at patm.net (Pat Martin) Date: Wed, 22 Feb 2006 09:19:49 -0800 Subject: [Tutor] Locking a file in linux with Python Message-ID: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> Hello, I am trying to find on the web how to lock a file with python in Linux. I am trying to process a group of files that are continually being written to and when I am working on one file I would like to be able to lock it. Can anyone point me in the right direction for that. Thanks -- Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/796a8712/attachment.htm From faq at lanl.gov Tue Feb 21 02:40:18 2006 From: faq at lanl.gov (Francesco A. Queirolo) Date: Mon, 20 Feb 2006 18:40:18 -0700 (MST) Subject: [Tutor] Interpackage access help Message-ID: <49807.128.165.0.81.1140486018.squirrel@webmail.lanl.gov> >Francesco A. Queirolo wrote: >> Sorry about the double post but the first one was sent before I was >> completed with my question. >> >> I have the following directory structure on Windows XP running python >> 2.4.2 final: >> >> JavaInheritancePoly\ >> HierarchicalInheritancePoly.py >> Animals\ >> __init__.py >> Modules\ >> __init__.py >> Animal.py >> Test\ >> __init__.py >> AnimalTest.py >> >> When in AnimalTest.py I would like to access animal. I have tried: >> >> from JavaInheritancePoly.Animals.Modules import Animal >For the above to work you need __init__.py in JavaInheritancePoly\ and >the dir containing JavaInheritancePoly\ must be in sys.path either >because it is in the working directory or some other means. >Kent Kent, Thanks for the speedy reply. I have successfully been able to append my sys.path through the command: sys.path.append('pathToJavaInheritancePoly\Animals\Modules') so that I could run my AnimalTest.py from the Test directory. However, I would like to be able to use a .pth file (due to its unobtrusiveness and the fact that I don't have to type in 'sys.path.append()' every time I want to run the test) located in the Test directory so that I can import Animals.Module.Animals from AnimalTest while AnimalTest lies in the Test directory. I have already tried an absolute path to: 'pathToJavaInheritancePoly\Animals\Modules' I have also tried relative paths: '..' and '../../' neither of which have been successful. Thanks, Francesco -- Francesco Queirolo Safeguards Systems Group(N-4) Los Alamos National Laboratory TA 35-2 A156 +1 505 606 1960 faq at lanl.gov From dyoo at hkn.eecs.berkeley.edu Wed Feb 22 19:44:10 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Feb 2006 10:44:10 -0800 (PST) Subject: [Tutor] Locking a file in linux with Python In-Reply-To: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> Message-ID: On Wed, 22 Feb 2006, Pat Martin wrote: > I am trying to find on the web how to lock a file with python in Linux. > I am trying to process a group of files that are continually being > written to and when I am working on one file I would like to be able to > lock it. Can anyone point me in the right direction for that. Hi Pat, Take a look at the 'portalocker' recipe in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 Does this address your question? Good luck to you! From edgar.antonio.rv at gmail.com Wed Feb 22 19:44:34 2006 From: edgar.antonio.rv at gmail.com (Edgar Antonio Rodriguez Velazco) Date: Wed, 22 Feb 2006 18:44:34 +0000 Subject: [Tutor] Does casting exist in Python? Message-ID: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> Does it? Thanks, -- Edgar A. Rodriguez V. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/b081ee48/attachment.htm From carroll at tjc.com Wed Feb 22 20:04:57 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 22 Feb 2006 11:04:57 -0800 (PST) Subject: [Tutor] Python & XEmacs In-Reply-To: <43FC8903.6090305@cc.umanitoba.ca> Message-ID: On Wed, 22 Feb 2006, Brian van den Broek wrote: > on one read of "neither" it is marking the possibility that you know > Python, you know (X)Emacs and you merely need to learn how to make the > two work together. (Thus, neither is such that you are trying to learn > it.) > > Bet a 1$ that reading was the intended one. Having been on this list long enough to see that Wesley is one of the most helpful of contributors (I'm not going to mention any other names (Hi, Alan! Hi, Kent) for fear of leaving anyone out), I'd feel comfortable raising that bet to $5. I'd go higher, but I need to keep somemoney for lunch. From wpmartin at gmail.com Wed Feb 22 20:14:21 2006 From: wpmartin at gmail.com (Pat Martin) Date: Wed, 22 Feb 2006 11:14:21 -0800 Subject: [Tutor] Locking a file in linux with Python In-Reply-To: References: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> Message-ID: <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> > > > I am trying to find on the web how to lock a file with python in Linux. > > I am trying to process a group of files that are continually being > > written to and when I am working on one file I would like to be able to > > lock it. Can anyone point me in the right direction for that. > > Hi Pat, > > Take a look at the 'portalocker' recipe in the Python Cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > > Does this address your question? > > > > Good luck to you! > I had actually looked at that site, but when I do the commands testfile = open('testlock', 'a+') fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX) in the interpreter and then try to access the file in another terminal (I leave the interpreter open) I can write to the file just fine with vi. So I am not thinking it is working. Unless I am missing something... Thanks again. Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/f9c2fbb5/attachment.html From shaleh at speakeasy.net Wed Feb 22 20:19:17 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Wed, 22 Feb 2006 11:19:17 -0800 Subject: [Tutor] Does casting exist in Python? In-Reply-To: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> References: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> Message-ID: <43FCB935.2050706@speakeasy.net> Edgar Antonio Rodriguez Velazco wrote: > Does it? > Thanks, > not exactly. new_list = list(my_tuple) In general Python works without having to nudge the type system. For char -> int style conversions there is a builtin function called 'ord'. From wpmartin at gmail.com Wed Feb 22 20:18:26 2006 From: wpmartin at gmail.com (Pat Martin) Date: Wed, 22 Feb 2006 11:18:26 -0800 Subject: [Tutor] Locking a file in linux with Python In-Reply-To: <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> References: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> Message-ID: <44db03850602221118u3c9d8421s3c39e4a569c49360@mail.gmail.com> On 2/22/06, Pat Martin wrote: > > > I am trying to find on the web how to lock a file with python in Linux. > > > I am trying to process a group of files that are continually being > > > written to and when I am working on one file I would like to be able > > to > > > lock it. Can anyone point me in the right direction for that. > > > > Hi Pat, > > > > Take a look at the 'portalocker' recipe in the Python Cookbook: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > > > > Does this address your question? > > > > > > > > Good luck to you! > > > > I had actually looked at that site, but when I do the commands > > testfile = open('testlock', 'a+') > fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX) > > in the interpreter and then try to access the file in another terminal (I > leave the interpreter open) I can write to the file just fine with vi. So I > am not thinking it is working. Unless I am missing something... > > Thanks again. > > Pat Martin Ooops the commands I am running are actually mboxfile = open('testlock', 'a+') fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX) and it is not working. The two filenames do match, sorry for that typo earlier. -- Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/6a8bd085/attachment.htm From kent37 at tds.net Wed Feb 22 20:22:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Feb 2006 14:22:17 -0500 Subject: [Tutor] Does casting exist in Python? In-Reply-To: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> References: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> Message-ID: <43FCB9E9.3060503@tds.net> Edgar Antonio Rodriguez Velazco wrote: > Does it? No, because variables are untyped in Python there is no need for casting. In Python values have types, variables are just names. You just use the value and if it has the correct type it will work. There are some functions that transform values from one type to another. These are not really casts, they create new values of a different type. Some examples are int(), str(), float(). For example: >>> i=3 >>> type(i) >>> f=float(i) >>> f 3.0 >>> type(f) Kent From dyoo at hkn.eecs.berkeley.edu Wed Feb 22 23:01:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Feb 2006 14:01:11 -0800 (PST) Subject: [Tutor] Locking a file in linux with Python In-Reply-To: <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> Message-ID: On Wed, 22 Feb 2006, Pat Martin wrote: > I had actually looked at that site, but when I do the commands > > testfile = open('testlock', 'a+') > fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX) > > in the interpreter and then try to access the file in another terminal > (I leave the interpreter open) I can write to the file just fine with > vi. So I am not thinking it is working. Unless I am missing something... Hi Pat, Oh! Ok, what's happening is that the code places an "advisory" lock. Any other program that tries to get a lock will wait as expected. But a noncooperating program that doesn't look at locks won't care. It's possible that 'vi' is not cooperating: it may not be doing an flock() call. There is a line item in the vim TODO documentation about this: """ 8 Add file locking. Lock a file when starting to edit it with flock() or fcntl(). This patch has advisory file locking while reading/writing the file: ~/vim/patches/kahn_file_locking. """ (http://www.vim.org/htmldoc/todo.html) For more information on this situation, see: http://en.wikipedia.org/wiki/File_locking You might be able to put wrappers to force a common access point to the file you're trying to lock; an example of this approach is in the 'visudo' program that tries to provide exclusive access to /etc/sudoers. I have to admit that I don't know much more about this or how people work around exclusive access to files; does anyone else on the Tutor list have suggestions? Good luck to you! From adam.jtm30 at gmail.com Thu Feb 23 00:23:35 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 22 Feb 2006 23:23:35 +0000 Subject: [Tutor] Locking a file in linux with Python In-Reply-To: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> References: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> Message-ID: You could try setting up a seperate user and then changing permissions on the file so that only that user can access it then change it back when you've finished. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/3fd7c669/attachment.htm From adam.jtm30 at gmail.com Thu Feb 23 00:56:01 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 22 Feb 2006 23:56:01 +0000 Subject: [Tutor] Translator In-Reply-To: <5e58f2e40602211837g3a61e954m@mail.gmail.com> References: <20060222020858.12096.qmail@web80830.mail.yahoo.com> <5e58f2e40602211837g3a61e954m@mail.gmail.com> Message-ID: > > If you want to do genuine translation, like English to French or > something, then, well, ask someone who works at Google :-) Guido? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060222/48ead405/attachment.htm From broek at cc.umanitoba.ca Thu Feb 23 01:47:44 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 22 Feb 2006 18:47:44 -0600 Subject: [Tutor] Python & XEmacs In-Reply-To: References: Message-ID: <43FD0630.9050603@cc.umanitoba.ca> Terry Carroll said unto the world upon 22/02/06 01:04 PM: > On Wed, 22 Feb 2006, Brian van den Broek wrote: > > >>on one read of "neither" it is marking the possibility that you know >>Python, you know (X)Emacs and you merely need to learn how to make the >>two work together. (Thus, neither is such that you are trying to learn >>it.) >> >>Bet a 1$ that reading was the intended one. > > > Having been on this list long enough to see that Wesley is one of the most > helpful of contributors (I'm not going to mention any other names (Hi, > Alan! Hi, Kent) for fear of leaving anyone out), I'd feel comfortable > raising that bet to $5. I'd go higher, but I need to keep somemoney for > lunch. Ah, but you've overlooked the significance of my last name -- a 1$ bet is a big deal! (How was copper wire invented? Two Dutchmen fighting over a penny.) ;-) Brian van den Broek From oztriking at hotmail.com Thu Feb 23 02:59:13 2006 From: oztriking at hotmail.com (John Connors) Date: Thu, 23 Feb 2006 12:59:13 +1100 Subject: [Tutor] Repeating a routine In-Reply-To: <43FC7C10.3040508@cc.umanitoba.ca> Message-ID: G'day, I think my peanut sized brain is starting to understand how to do this. I tried with a simple dice game where 4 dice are rolled, if the total of the last 2 dice rolled is 6 you win. It's kinda pointless using 4 dice rolls when only 2 are needed but I wanted to prove to myself I could call the dice function whenever I needed it. This is what I came up with. import random def dice(): return random.randint(1,6) playagain = 'y' while playagain == 'y': die1 = dice() die2 = dice() print '1st dice is ',die1,'\n','2nd dice is ',die2 die3 = dice() die4 = dice() winnum = die3 + die4 print'combined total for the next 2 dice is ',winnum if winnum == 6: print 'you win' else: print 'you lose' playagain = raw_input('play again? (y/n) ') print 'goodbye' _________________________________________________________________ Make your dream car a reality http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fcarpoint%2Eninemsn%2Ecom%2Eau&_t=12345&_r=emailtagline&_m=EXT From shaleh at speakeasy.net Thu Feb 23 03:30:41 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Wed, 22 Feb 2006 18:30:41 -0800 Subject: [Tutor] Repeating a routine In-Reply-To: References: Message-ID: <43FD1E51.2050505@speakeasy.net> Jumping to the middle of a book or movie will lead to similar confusion. Give a look at Dive Into Python. Available as either a book or online. http://www.diveintopython.org/ From oztriking at hotmail.com Thu Feb 23 03:59:58 2006 From: oztriking at hotmail.com (John Connors) Date: Thu, 23 Feb 2006 13:59:58 +1100 Subject: [Tutor] Repeating a routine In-Reply-To: <43FD1E51.2050505@speakeasy.net> Message-ID: G'day Sean, >Jumping to the middle of a book or movie will lead to similar confusion. > >Give a look at Dive Into Python. Available as either a book or online. I have it and it's a great book, and I have worked my way through a lot of it unfortunately my brain can't take something in unless I do it myself. I learnt more by trying a couple of simple programs and posting them in here then I did by several weeks of reading books and tutorials. It's not the books fault it's just the way my brain works. I certainly appreciate the time and effort of those who assist in here. Sorry if I've done the wrong thing. John _________________________________________________________________ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT From edgar.antonio.rv at gmail.com Thu Feb 23 04:02:36 2006 From: edgar.antonio.rv at gmail.com (Edgar Antonio Rodriguez Velazco) Date: Thu, 23 Feb 2006 03:02:36 +0000 Subject: [Tutor] Does casting exist in Python? Message-ID: <9378d12c0602221902x6af8818i58d5e67e4d493df3@mail.gmail.com> > No, because variables are untyped in Python there is no need for > casting. In Python values have types, variables are just names. You just > use the value and if it has the correct type it will work. > > There are some functions that transform values from one type to another. > These are not really casts, they create new values of a different type. > Some examples are int(), str(), float(). For example: > > >>> i=3 > >>> type(i) > > >>> f=float(i) > >>> f > 3.0 > >>> type(f) > > > Kent I realize now that. Thank you ;-) PD: I think python is better than I thought before. xD PD2: Apologize for my English. -- Edgar A. Rodriguez V. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060223/ae052428/attachment.htm From broek at cc.umanitoba.ca Thu Feb 23 05:09:23 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 22 Feb 2006 22:09:23 -0600 Subject: [Tutor] Repeating a routine In-Reply-To: References: Message-ID: <43FD3573.1060208@cc.umanitoba.ca> John Connors said unto the world upon 22/02/06 07:59 PM: > G'day, > > I think my peanut sized brain is starting to understand how to do this. Glad you're making progress :-) It's normal it takes a while to learn to adjust your thinking to a rigid and precise system. I've made some pretty big changes and explained in comments. There are a couple of bumps up in level of Python-fu, so ask if it puzzles. Also, watch for the likely improvements on mine, too :-) (I'm no expert, either.) Also, I tend to have longer names than most people do. But I think it is important for understanding longer programs (even your own) that the names are well chosen. > import random > > def dice(): > return random.randint(1,6) > > playagain = 'y' > > while playagain == 'y': > > die1 = dice() > die2 = dice() > > print '1st dice is ',die1,'\n','2nd dice is ',die2 > > die3 = dice() > die4 = dice() > winnum = die3 + die4 > > print'combined total for the next 2 dice is ',winnum > > if winnum == 6: > print 'you win' > else: > print 'you lose' > > playagain = raw_input('play again? (y/n) ') > > print 'goodbye' import random def die_roll(): return random.randint(1,6) # The while True / break construct avoids the dummy 'y' value # in your version. while True: # This assigns all the dice at once and makes a tuple from the # list comprehension. A tuple to make the string formatting happy. rolls = tuple([die_roll() for x in range(4)]) # uses string formatting, a very powerful tool print '1st die is %s\n2nd die is %s' %(rolls[:2]) turn_score = sum(rolls[2:]) print 'combined total for the next 2 dice is %s' %turn_score if turn_score == 6: print 'you win' else: print 'you lose' playagain = raw_input('play again? (y/n) ') # .lower() to accommodate 'Y'. You might think about how to # handle 'yes' and the like. if playagain.lower() != 'y': break print 'goodbye' HTH, Brian vdB From hugonz-lists at h-lab.net Thu Feb 23 18:26:44 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 23 Feb 2006 11:26:44 -0600 Subject: [Tutor] Tkinter, Frame and Canvas question. Message-ID: <43FDF054.4070708@h-lab.net> Hi all, I'm running into trouble displaying some Tkinter Canvases, they keep a border between themselves and there's no way I can have them display without a grey gap between them. I've narrowed the problem to the following example. I've tried all kind of padding and border parameter to the Frame's pack() method and the Canvas' pack() method. Is there something I'm missing or plainly not understanding? I'd like to display canvases one next to the other without some kind of background showing throug. Thanks for taking a look, here's the example: ======================= import Tkinter from Tkconstants import * class App(Tkinter.Frame): def __init__(self, master=None): Tkinter.Frame.__init__(self, master) self.pack(pady=0, ipady=0) canvas1 = Tkinter.Canvas(self, background='#000000', borderwidth=0) canvas2 = Tkinter.Canvas(self, background='#000000', borderwidth=0) canvas1.pack(pady=0) canvas2.pack(pady=0) if __name__ == '__main__': myapp = App() myapp.mainloop() From hugonz-lists at h-lab.net Thu Feb 23 18:46:30 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 23 Feb 2006 11:46:30 -0600 Subject: [Tutor] Locking a file in linux with Python In-Reply-To: <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> References: <44db03850602220919g41e147e4m52a1f8a934c60305@mail.gmail.com> <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> Message-ID: <43FDF4F6.6020104@h-lab.net> Hi Pat, > testfile = open('testlock', 'a+') > fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX) > > in the interpreter and then try to access the file in another terminal > (I leave the interpreter open) I can write to the file just fine with > vi. So I am not thinking it is working. Unless I am missing something... Actually yes, all these locks are advisory, that is, you need to have all applications using the file use the protocol. In your case, vi does not honor the file lock. Granted, this is not very useful for dealing with 3rd applications, as the operating system does not provide hard locks, and basically flock() is a mechanism for not having your own programs trample on files. Try getting a lock in another terminal, for the same file, and check that it will not be granted and the other application will block until you release the lock in the first python interpreter... Hope that clarifies things a bit, Hugo From patriciap.gu at gmail.com Thu Feb 23 20:58:02 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 23 Feb 2006 19:58:02 +0000 (UTC) Subject: [Tutor] =?utf-8?q?mod=5Fpython_=26_mysqldb_problem?= Message-ID: Hi! I'm new to python and MySQl and have problems trying to figure out what is wrong with my code. I have two files: ***control.py*** #!/usr/bin/python import MySQLdb def addpercent(mp, lp): conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "",db ="my_db") cursor = conn.cursor() cursor.execute (""" UPDATE targets SET mario_percent = %d, lizard_percent = %d WHERE target_name = 'anyname' """, (mp, lp)) db.commit() cursor.close() db.close() *******controlcenter.html****** Ants Control Center
mario: lizard:
********************************** This is what i found in error_log [Thu Feb 23 13:08:07 2006] [notice] mod_python: (Re)importing module 'mod_python.publisher' [Thu Feb 23 13:08:07 2006] [notice] mod_python: (Re)importing module 'control' with path set to '['/var/www/html/mptest']' [Thu Feb 23 13:08:08 2006] [notice] child pid 6405 exit signal Segmentation fault (11) **************************************** There is no reference to php in the httpd.conf file. Someone had told me that that could be the problem. I'd appreciate your help. From dyoo at hkn.eecs.berkeley.edu Thu Feb 23 22:04:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Feb 2006 13:04:43 -0800 (PST) Subject: [Tutor] =?utf-8?q?mod=5Fpython_=26_mysqldb_problem?= In-Reply-To: Message-ID: On Thu, 23 Feb 2006, Patty wrote: > def addpercent(mp, lp): > conn = MySQLdb.connect(host = "localhost", user = "root", passwd = > "",db ="my_db") > cursor = conn.cursor() > cursor.execute (""" > UPDATE targets > SET mario_percent = %d, lizard_percent = %d > WHERE target_name = 'anyname' > """, (mp, lp)) > db.commit() > cursor.close() > db.close() Hi Patty, Does this code work outside of the context of mod_python? There's something slightly suspicious here in the use of the '%d' format string: I'm not sure MySQLdb will accept it. Let me check... According to the DB API on parameter styles: """ paramstyle String constant stating the type of parameter marker formatting expected by the interface. Possible values are [2]: 'qmark' Question mark style, e.g. '...WHERE name=?' 'numeric' Numeric, positional style, e.g. '...WHERE name=:1' 'named' Named style, e.g. '...WHERE name=:name' 'format' ANSI C printf format codes, e.g. '...WHERE name=%s' 'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s' """ (http://www.python.org/peps/pep-0249.html) So '%s' acts as a placeholder --- a parameter marker --- where MySQLdb will later substitute parameters into. So I'm not certain that '%d' will work properly. In any case, you should never get a segfault in Python code, so something strange is happening. Try seeing if your code works outside of mod_python first; that'll give us at least a little more assurance that it isn't MySQLdb that's doing funny things. You might also want to talk with the mod_python folks, since they'll probably be able to give you ideas on how to get better debugging output here. Good luck to you! From alan.gauld at freenet.co.uk Thu Feb 23 22:44:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Feb 2006 21:44:31 -0000 Subject: [Tutor] First Try 1.2 References: Message-ID: <002601c638c2$566aab80$0b01a8c0@xp> Hi John, Its developing nicely so I'll add some more style issue comments :-) > import random > > # store the /home/mutt/lotto.txt in f > f = file('/home/mutt/lotto.txt','w') > # create or replace lotto.txt in my home directory > f.write('Here are your numbers:\n\n') I'd move the middle comment up with the one above. Think of a block of comments commenting on a paragraph of code, rather than dealing in single lines: > # store the /home/mutt/lotto.txt in f > # create or replace lotto.txt in my home directory > f = file('/home/mutt/lotto.txt','w') > f.write('Here are your numbers:\n\n') Now the code is easier sepsarated from the comment. BUT, is the comment really needed, after all the explicit pathname shows whgere it is going and the variable tells us where we are storing it. How much of: > f = file('/home/mutt/lotto.txt','w') > f.write('Here are your numbers:\n\n') will be hard to understand if you come back in a few months? Comments are best used to explain the *why* of code and let good variable names and structure describe the how. A concept often called "Self documenting code" > # user input for number of games to generate > how_many_games = int(raw_input('How many games you would like generated? > ')) > # user input for number of balls (to allow different lotto games) > number_of_balls = int(raw_input('\nHow many balls are in the lotto you > wish to play? ')) > # user input for how many numbers per game (to allow systems entries) > how_many_numbers = int(raw_input('\nHow many numbers you would like per > game? ')) > # check if there is a power ball > chk_pwrball = raw_input('Is there a power ball? (y/n) ') > how_many_games = int(raw_input('How many games you would like generated? > ')) > number_of_balls = int(raw_input('\nHow many balls are in the lotto you > wish to play? ')) > how_many_numbers = int(raw_input('\nHow many numbers you would like per > game? ')) > chk_pwrball = raw_input('Is there a power ball? (y/n) ') Again comparing these two do the comments add much more information than the variable names do? And by removing them the code itself becomesa much more obvious and readable. > print '\n\nHere are your numbers : \n' > > # loop for the number of games selected by user > for game in range(1, how_many_games + 1): > > # generate 6 random numbers between 1 and 45 inclusive then sort them > lotto_numbers = random.sample(range(1,number_of_balls + 1), > how_many_numbers) > lotto_numbers.sort() > > if chk_pwrball == 'n': > > # Right justified in 3 character width then a tab (\t) then a blank > line (\n) > print '%3s\t%s\n' % (game, lotto_numbers) > > # write the numbers to lotto.txt > save_numbers = 'Game: %3s\t%3s\n' % (game, lotto_numbers) > f.write(save_numbers) The commenting in this section is better spaced but again mostly just says what the code does. The comment explaining the string format is probably the most valid comment in the program, it describes what the format is trying to accomplish which is valid since format strings are not self evident. > if chk_pwrball == 'y': > pwrball = random.sample(range(1,number_of_balls +1), 1) > print '%3s\t%s \tPower Ball: %s\n' % (game, lotto_numbers, > pwrball) > save_numbers = 'Game: %3s\t%s \tPower Ball: %s\n' % (game, > lotto_numbers, pwrball) > f.write(save_numbers) > > print '\nHope you win!' > f.write('\nHope you win!') > f.close() And interesting that you (coprrectly) chose not to comment this sectoon at all Don't take these comments too personally but it is just a classic case of how you have improved the code clarity to the point where the comments, which were originally necessary, are now superfluous! This is a common mistake for beginners so I thought I'd take the opportunity to highlight the issue: Comments are useful but clearly written code is much better Alan G From alan.gauld at freenet.co.uk Thu Feb 23 22:56:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Feb 2006 21:56:53 -0000 Subject: [Tutor] Does casting exist in Python? References: <9378d12c0602221044t2590ed96s469439e709fd69e@mail.gmail.com> Message-ID: <007101c638c4$0eb61fc0$0b01a8c0@xp> > Subject: [Tutor] Does casting exist in Python? > Does it? That depends on what you mean by casting. A cast in C literally telly the compiler to treat one piece of data as if it were another type of data. For example char c = 'a'; float f = (float)c; Tells C to take the character stored in c and treat it as a floating point number. It does not change the type of c it merely treats the data as if it were another type. However in practice many people use casting as a type conversion operation and think of it in that light - which often leads to strange and subtle bugs! Python does do type conversion by applying conversion functions such as str(), int(), float() list() etc [Actually I believe these are now callable types which is subtly different but I'll ignore that for now!] If you do want to do a cast (ie. re-interpret data) the only way that I know of is to use the struct module. That allows you to take a piece of data and write it as a byte string, you can then reinterpret the byte string using a different format set and effectively the same byte sequence that started as a char will be read as a float! (there might be issues if the buyte string lengths don;t match....) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From glingl at aon.at Thu Feb 23 23:14:53 2006 From: glingl at aon.at (Gregor Lingl) Date: Thu, 23 Feb 2006 23:14:53 +0100 Subject: [Tutor] Tkinter, Frame and Canvas question. In-Reply-To: <43FDF054.4070708@h-lab.net> References: <43FDF054.4070708@h-lab.net> Message-ID: <43FE33DD.1010807@aon.at> Hi Hugo, some experiments showed, that the following code - using borderwidth=-2 - works as you desired, at least on my windows machine: import Tkinter from Tkconstants import * class App(Tkinter.Frame): def __init__(self, master=None): Tkinter.Frame.__init__(self, master) self.pack() canvas1 = Tkinter.Canvas(self, background='#000000', borderwidth=-2) canvas2 = Tkinter.Canvas(self, background='#000000', borderwidth=-2) canvas1.pack(pady=0) canvas2.pack(pady=0) if __name__ == '__main__': myapp = App() myapp.mainloop() -------- Alas, there is some strange anomaly: it only does so (i. e. doesn't display that gray bar between the canvases) when run from IDLE or by double-clicking the renamed file test.pyw or run from the command window with the command: python test.py. Double-clicking test.py performs differently(!) and still shows the border between the two canvases. Who understands? (Or do you think my python installation is in a corrupted state?) Regards, Gregor Hugo Gonz?lez Monteverde schrieb: > Hi all, > > I'm running into trouble displaying some Tkinter Canvases, they keep a > border between themselves and there's no way I can have them display > without a grey gap between them. > > I've narrowed the problem to the following example. I've tried all kind > of padding and border parameter to the Frame's pack() method and the > Canvas' pack() method. > > Is there something I'm missing or plainly not understanding? I'd like to > display canvases one next to the other without some kind of background > showing throug. > > Thanks for taking a look, here's the example: > > ======================= > > import Tkinter > from Tkconstants import * > > class App(Tkinter.Frame): > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master) > self.pack(pady=0, ipady=0) > canvas1 = Tkinter.Canvas(self, background='#000000', borderwidth=0) > canvas2 = Tkinter.Canvas(self, background='#000000', borderwidth=0) > > canvas1.pack(pady=0) > canvas2.pack(pady=0) > > if __name__ == '__main__': > myapp = App() > myapp.mainloop() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From patriciap.gu at gmail.com Fri Feb 24 02:22:23 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 24 Feb 2006 01:22:23 +0000 (UTC) Subject: [Tutor] =?utf-8?q?mod=5Fpython_=26_mysqldb_problem?= References: Message-ID: Hi Danny, I downloaded the latest version of mysqldb and my code worked. btw, I changed it to %s instead of %d. Thanks! Patty From hugonz-lists at h-lab.net Fri Feb 24 02:43:26 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 23 Feb 2006 19:43:26 -0600 Subject: [Tutor] Tkinter, Frame and Canvas question. In-Reply-To: <43FE33DD.1010807@aon.at> References: <43FDF054.4070708@h-lab.net> <43FE33DD.1010807@aon.at> Message-ID: <43FE64BE.1080702@h-lab.net> > -------- > Alas, there is some strange anomaly: it only does so (i. e. doesn't > display that gray bar between the canvases) when run from IDLE or > by double-clicking the renamed file test.pyw or run from the > command window with the command: python test.py. > Double-clicking test.py performs differently(!) and still shows the > border between the two canvases. Who understands? (Or do you think my > python installation is in a corrupted state?) No, it does the same on my 2.3 installation in windows. I will test on Linux. Actually, it displays the grey border, but if you scroll any window in front of it, everything except those borders are redrawn... (!) I'll check what it does on Linux and then report back... Thanks, Hugo From dyoo at hkn.eecs.berkeley.edu Fri Feb 24 02:45:12 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Feb 2006 17:45:12 -0800 (PST) Subject: [Tutor] =?utf-8?q?mod=5Fpython_=26_mysqldb_problem?= In-Reply-To: Message-ID: > I downloaded the latest version of mysqldb and my code worked. btw, I > changed it to %s instead of %d. Hi Patty, That's great news! Does the whole thing work now, including the integration with mod_python? I'm following up and making sure that the problem was simply the stale copy of MySQLdb. Best of wishes! From wpmartin at gmail.com Fri Feb 24 03:16:41 2006 From: wpmartin at gmail.com (Pat Martin) Date: Thu, 23 Feb 2006 18:16:41 -0800 Subject: [Tutor] Locking a file in linux with Python In-Reply-To: References: <44db03850602221114u6e2d6f6as4cd47b5ab9df77c6@mail.gmail.com> Message-ID: <44db03850602231816w5e66da20h83a3a07f6b2f69ad@mail.gmail.com> Danny and Hugo, Thanks that really explains it better on what was going on. I may try renaming the file to see if I can get around it that way. -- Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060223/7b6b5597/attachment.htm From patriciap.gu at gmail.com Fri Feb 24 03:18:23 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 24 Feb 2006 02:18:23 +0000 (UTC) Subject: [Tutor] =?utf-8?q?mod=5Fpython_=26_mysqldb_problem?= References: Message-ID: > > That's great news! Does the whole thing work now, including the > integration with mod_python? Hi Danny, Yes, everything works now. The problem was the mysqldb copy I had. I also noticed that i had made a mistake by writting > db.commit() > db.close() instead of: conn.commit() and conn.close() Thanks again! Patty From klappnase at freenet.de Fri Feb 24 12:05:21 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 24 Feb 2006 12:05:21 +0100 Subject: [Tutor] Tkinter, Frame and Canvas question. In-Reply-To: <43FDF054.4070708@h-lab.net> References: <43FDF054.4070708@h-lab.net> Message-ID: <20060224120521.3e6cabc7.klappnase@freenet.de> On Thu, 23 Feb 2006 11:26:44 -0600 Hugo Gonz?lez Monteverde wrote: > Hi all, > > I'm running into trouble displaying some Tkinter Canvases, they keep a > border between themselves and there's no way I can have them display > without a grey gap between them. > > I've narrowed the problem to the following example. I've tried all kind > of padding and border parameter to the Frame's pack() method and the > Canvas' pack() method. > > Is there something I'm missing or plainly not understanding? I'd like to > display canvases one next to the other without some kind of background > showing throug. > > Thanks for taking a look, here's the example: > > ======================= > > import Tkinter > from Tkconstants import * > > class App(Tkinter.Frame): > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master) > self.pack(pady=0, ipady=0) > canvas1 = Tkinter.Canvas(self, background='#000000', borderwidth=0) > canvas2 = Tkinter.Canvas(self, background='#000000', borderwidth=0) > > canvas1.pack(pady=0) > canvas2.pack(pady=0) > > if __name__ == '__main__': > myapp = App() > myapp.mainloop() Hi Hugo, try passing highlightthickness=0 to the Canvas constructor. The hightlightthickness is the width of the border around the widget that becomes black when the widget has keyboard focus and it probably defaults to 1. If you set highlightthickness to 0 you should probably also set takefocus to False (if this is an option for you). I hope this helps Michael From Emily_Patek at umit.maine.edu Fri Feb 24 14:42:11 2006 From: Emily_Patek at umit.maine.edu (Emily Patek) Date: Fri, 24 Feb 2006 08:42:11 -0500 Subject: [Tutor] Finding items in a list Message-ID: Hi - I am trying to break apart a list into several smaller lists based on repeating nearly identical entries. For example, every so often there is the word CLUSTER with a number after it, like CLUSTER 1. I can find them one by one, but would like to do a while loop for while item in list = CLUSTER X. Is there a key that I can put in that means "any text that comes after" that would go from cluster to cluster without my typing in each cluster and number? I am a very beginner programmer and am trying to parse a file of gene-related information that is in a not-so-easy format. I put it into a list based on lines through the splitlines() method. I also thought about splitting the text by CLUSTER and then making each item of the list into a string that I could then split, but couldn't get that to work either... Thanks! Emily From dyoo at hkn.eecs.berkeley.edu Fri Feb 24 20:03:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Feb 2006 11:03:41 -0800 (PST) Subject: [Tutor] Finding items in a list In-Reply-To: Message-ID: On Fri, 24 Feb 2006, Emily Patek wrote: > I am trying to break apart a list into several smaller lists based on > repeating nearly identical entries. For example, every so often there > is the word CLUSTER with a number after it, like CLUSTER 1. I can find > them one by one, but would like to do a while loop for while item in > list = CLUSTER X. Hi Emily, Can you give a concrete example of the kind of input you're getting, and what you'd like to get out? Try constructing a small example so that we on the tutor list can try to propose ways of getting the desired output. From jmpurser at gmail.com Fri Feb 24 20:18:06 2006 From: jmpurser at gmail.com (John Purser) Date: Fri, 24 Feb 2006 11:18:06 -0800 Subject: [Tutor] Grepping a file for words in a list Message-ID: <20060224111806.0ae87b8b.jmpurser@gmail.com> Hello, I'm writing a system admin script in python that checks recently accessed files for keywords like "failed, denied, error,..." etc. I'm using popen to call grep -F but it's VERY slow. Can anyone suggest a faster method to do this? Thanks, John Purser Ubuntu Linux Python 2.4 -- Courage is your greatest present need. From bgailer at alum.rpi.edu Fri Feb 24 20:27:25 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 24 Feb 2006 11:27:25 -0800 Subject: [Tutor] Grepping a file for words in a list In-Reply-To: <20060224111806.0ae87b8b.jmpurser@gmail.com> References: <20060224111806.0ae87b8b.jmpurser@gmail.com> Message-ID: <43FF5E1D.2090701@alum.rpi.edu> John Purser wrote: > Hello, > > I'm writing a system admin script in python that checks recently > accessed files for keywords like "failed, denied, error,..." etc. I'm > using popen to call grep -F but it's VERY slow. Can > anyone suggest a faster method to do this? > I don't know whether it'd be faster, but you could read the file into a Python string, then use re to find the keywords. What do you do after finding them? From dyoo at hkn.eecs.berkeley.edu Fri Feb 24 21:23:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Feb 2006 12:23:22 -0800 (PST) Subject: [Tutor] Grepping a file for words in a list In-Reply-To: <20060224111806.0ae87b8b.jmpurser@gmail.com> Message-ID: On Fri, 24 Feb 2006, John Purser wrote: > I'm writing a system admin script in python that checks recently > accessed files for keywords like "failed, denied, error,..." etc. I'm > using popen to call grep -F but it's VERY slow. Can > anyone suggest a faster method to do this? Hi John, This should not be slow, but we have to see what exactly is going on here. Can you give us more details? How many keywords are you typically passing in ? How large is the ? What do you mean by "slow"? From jmpurser at gmail.com Fri Feb 24 21:54:43 2006 From: jmpurser at gmail.com (John Purser) Date: Fri, 24 Feb 2006 12:54:43 -0800 Subject: [Tutor] Grepping a file for words in a list In-Reply-To: References: <20060224111806.0ae87b8b.jmpurser@gmail.com> Message-ID: <20060224125443.80a7945c.jmpurser@gmail.com> On Fri, 24 Feb 2006 12:23:22 -0800 (PST) Danny Yoo wrote: > > > On Fri, 24 Feb 2006, John Purser wrote: > > > I'm writing a system admin script in python that checks recently > > accessed files for keywords like "failed, denied, error,..." etc. > > I'm using popen to call grep -F but it's VERY > > slow. Can anyone suggest a faster method to do this? > > Hi John, > > This should not be slow, but we have to see what exactly is going on > here. Can you give us more details? How many keywords are you > typically passing in ? How large is the ? What do > you mean by "slow"? > -- What good is an obscenity trial except to popularize literature? -- Nero Wolfe, "The League of Frightened Men" Danny, "what exactly is going on" is that I'm a doofus who will spend hours figuring out exactly what command string will get grep to work but then won't bother to put it in his code!!! DOH!!! John From kent37 at tds.net Fri Feb 24 22:59:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Feb 2006 16:59:52 -0500 Subject: [Tutor] Finding items in a list In-Reply-To: References: Message-ID: <43FF81D8.70506@tds.net> Emily, As Danny suggests, a concrete example of your input and output would be very helpful. It sounds like you have some data that looks like CLUSTER 1 SOMETHING ELSE CLUSTER 5 MORE STUFF ETC and you would like to make a list of [1, 5] - the data after 'CLUSTER'. Is that right? Here is something to help you get started. You can easily iterate through the lines in your data and select the ones that start with 'CLUSTER': >>> for line in data: ... if line.startswith('CLUSTER'): ... print line ... CLUSTER 1 CLUSTER 5 Do you know enough string manipulation to know how to split up the line and get the data you want? Once you have that you can add it to a list. Kent Emily Patek wrote: > Hi - > I am trying to break apart a list into several smaller lists based on repeating nearly identical entries. For example, every so often there is the word CLUSTER with a number after it, like CLUSTER 1. I can find them one by one, but would like to > do a while loop for while item in list = CLUSTER X. Is there a key that I can put in that means "any text that comes after" that would go from cluster to cluster without my typing in each cluster and number? I am a very beginner programmer and am > trying to parse a file of gene-related information that is in a not-so-easy format. I put it into a list based on lines through the splitlines() method. I also thought about splitting the text by CLUSTER and then making each item of the list into > a string that I could then split, but couldn't get that to work either... > > Thanks! > Emily > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dacohen at gmail.com Sat Feb 25 08:15:33 2006 From: dacohen at gmail.com (David Cohen) Date: Sat, 25 Feb 2006 03:15:33 -0400 Subject: [Tutor] Problem with threads Message-ID: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> Hi all, I have a problem trying to use thread on python. I import the threading module and execute this: def func_thread(): something... new_thread = threading.Thread(target = func_thread) new_thread.start() But the thread never really starts, just when I call the new_thread.join() method. Does anybody could help me? Regards, David From ukc802591034 at btconnect.com Sat Feb 25 12:47:39 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 25 Feb 2006 11:47:39 -0000 Subject: [Tutor] Grepping a file for words in a list References: <20060224111806.0ae87b8b.jmpurser@gmail.com> Message-ID: "John Purser" wrote in message > I'm writing a system admin script in python that checks recently > accessed files for keywords like "failed, denied, error,..." etc. I'm > using popen to call grep -F but it's VERY slow. Can > anyone suggest a faster method to do this? are you trying to locate the actual strings in the files or only testing to see if the strings occur? If the latter then you could use something like files = [f for f in glob(pattern) if mystring in open(f).read()] or for multiple patterns construct a single regex: files = [f for f in glob(pattern) if regex.search(open(f).read())] That might be slightly faster than spawning sub processes with popen. But it won't be a radical difference and if you actually want the line numbers of the patterns I suspect grep will be at least as fast as using python. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From vagemulo at yahoo.es Sat Feb 25 20:42:43 2006 From: vagemulo at yahoo.es (rio) Date: Sat, 25 Feb 2006 19:42:43 +0000 (GMT) Subject: [Tutor] software carpentry Message-ID: <20060225194243.30390.qmail@web26604.mail.ukl.yahoo.com> I set out to learn programming with a single practical task in mind, a cross-platform literal translation tool. I've included more detail below for those who are curious. Not terribly fond of programming, I initially hoped for an easy out, that I could find some existing code to modify to my needs without really becoming a "real" programmer. So I set about learning Java, but in my search for source code, I came across the Natural Language Toolkit: nltk.sourceforge.net/lite/doc/en/ which led me to the tutorials often cited on this list: www.diveintopython.org www.byteofpython.info/read www.freenetpages.co.uk/hp/alan.gauld which thoroughly convinced me that Python was the way to go. But I couldn't find tools in the NLTKit or elsewhere specific to the task. I installed IDLE and began coding in order to learn more. I got more confidence and realised I could probably write it from scratch and slowly began to see satisfying results. I think I was quite lucky to find Python, it is great! After several trips back to the drawing board, I'm not completely cured of the sensation of reinventing the wheel, and I have trouble reading my own code. I realized I needed to know more about program design.... The style guide was useful: www.python.org/doc/essays/styleguide.html But the Software Carpentry Workshop was a revelation. It gives a great deal of advice based on empirical studies on effective programming practices. I?m partway through - it's a multiweek course. University lecturer Greg Wilson offers thorough notes to accompany the .mp3 lectures, all of which is downloadable: www.third-bit.com/swc/ Throughout this process, I've been coming to terms with the fact that in order to really get the most out of my code, and to save myself time in the long run, I should learn to become a good programmer, and master the language (which compared to natural languages is easy!) Wilson convincingly argues that certain things which require more time up front save a great deal of time down the road. He stresses using a version control system, a debugger, test-driven development, and reading lots of code. 1) Is subversion really a good tool for the beginning programmmer, or a single programmer? If not which version control system would you recommend? what about tortoiseSVN? Up til now i've just been saving multiple filenames of my code. 2) Which debugger should I use if I do most of my work in XP with IDLE? Up til now I've just been using print statements. who knew? 3) Before setting out to write in Spanish, for example, I?d of course read many dozens of books, while I'm setting out to write Python without having read anything more than a few tutorial examples. How and where do I look for (well-written) code? Is it a good idea to look in the standard libraries for ideas, or code to modify? How are large applications usually organized, and how do you find a specific part of it? How can you find code specific to certain tasks? Thanks so much, brian russell (barcelona) ************************************************************** The cross-platform open source natural language application i hope to create would be a literal translation tool for txt and html, to help automate the creation of language instruction materials. For example, the tool could take english text and convert it into phonetic english, or butchered spanish: "President Z. lies like a rug." "Prezidint Z. liez>/b> liek u rug." (in truespel) "Presidente Z. miente como a alfombra." (in spanglish) Untranslatables (not found in the dictionary) like Z would be left untranslated, and - here's the real use of the tool - markup code can be added to the dictionaries. much of the application would automate the creation of missing dictionary entries .... ___________________________________________________________ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Sat Feb 25 20:54:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Feb 2006 11:54:49 -0800 (PST) Subject: [Tutor] Problem with threads In-Reply-To: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> Message-ID: On Sat, 25 Feb 2006, David Cohen wrote: > I have a problem trying to use thread on python. I import the threading > module and execute this: > > def func_thread(): > something... > > new_thread = threading.Thread(target = func_thread) > new_thread.start() > > But the thread never really starts, just when I call the > new_thread.join() method. Hmmm... that's odd. Can you show us how you're determining this? Here's an example interactive session: ################################################### >>> import threading >>> def sayHelloOverAndOver(): ... while True: ... print "hello" ... time.sleep(10) ... >>> import time >>> t = threading.Thread(target=sayHelloOverAndOver) >>> t.start() hello >>> hello #################################################### Now every ten seconds, the word hello punctuates the prompt... and I can't make it stop! *grin* Oh well. Do you see the same kind of behavior on your end? Good luck! From kent37 at tds.net Sat Feb 25 21:09:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Feb 2006 15:09:45 -0500 Subject: [Tutor] Problem with threads In-Reply-To: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> References: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> Message-ID: <4400B989.2080403@tds.net> David Cohen wrote: > Hi all, > > I have a problem trying to use thread on python. > I import the threading module and execute this: > > def func_thread(): > something... > > new_thread = threading.Thread(target = func_thread) > new_thread.start() > > But the thread never really starts, just when I call the > new_thread.join() method. > Does anybody could help me? More code would help. What you have shown looks fine. What does func_thread() do? How do you know it isn't doing it? Here is a very simple, working example based on your code: import threading, time def func_thread(): while True: print 'threading' time.sleep(1) new_thread = threading.Thread(target = func_thread) new_thread.start() print "main thread going away now" Kent From kent37 at tds.net Sat Feb 25 21:19:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Feb 2006 15:19:04 -0500 Subject: [Tutor] software carpentry In-Reply-To: <20060225194243.30390.qmail@web26604.mail.ukl.yahoo.com> References: <20060225194243.30390.qmail@web26604.mail.ukl.yahoo.com> Message-ID: <4400BBB8.3040204@tds.net> rio wrote: > 2) Which debugger should I use if I do most of my work in XP with IDLE? Up > til now I've just been using print statements. who knew? I rarely use a debugger for Python. I write most code in very small increments with lots of tests, so problems are generally very localized and found by inspection or with a few print statements. There is a simple debugger in IDLE. Winpdb is pretty nice for a full-featured Python debugger. http://www.digitalpeers.com/pythondebugger/ > > 3) Before setting out to write in Spanish, for example, I?d of course read > many dozens of books, while I'm setting out to write Python without having > read anything more than a few tutorial examples. How and where do I look > for (well-written) code? Is it a good idea to look in the standard > libraries for ideas, or code to modify? Yes, the standard library is a good place to look. I found the printed Python Cookbook to be a valuable source of real-world examples and common idioms. > How are large applications usually > organized, and how do you find a specific part of it? Organize your code into packages, with each package responsible for a cohesive part of the app. I use search a lot to find things :-) I actually do most of my Python development in TextPad, a Windows text editor. Python is so simple and streamlined that I don't feel the need for a lot of tool support, as opposed to Java, for example, where Eclipse or something like it seems essential. > How can you find > code specific to certain tasks? google 'python xxx' Kent From dyoo at hkn.eecs.berkeley.edu Sun Feb 26 02:28:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Feb 2006 17:28:18 -0800 (PST) Subject: [Tutor] software carpentry In-Reply-To: <20060225194243.30390.qmail@web26604.mail.ukl.yahoo.com> Message-ID: > 1) Is subversion really a good tool for the beginning programmmer, or a > single programmer? If not which version control system would you > recommend? what about tortoiseSVN? Up til now i've just been saving > multiple filenames of my code. Hi Brian, Yes, learning to use a revision control system is a Very Good Idea. The Subversion system is very popular these days; you can get some background on how it works by browsing the Subversion book: http://svnbook.red-bean.com/ These revision control systems are invaluable, even when one is working in a solitary setting. As a conceptual example, I sometimes have to "break" a fairly large bit of code while making significant code changes. But at the same time, I want to make sure that I can still make simple code fixes that aren't related to the code restructuring. A revision control system can help accomodate this situation with good "branch" support. > How and where do I look for (well-written) code? Is it a good idea to > look in the standard libraries for ideas, or code to modify? How are > large applications usually organized, and how do you find a specific > part of it? How can you find code specific to certain tasks? We can look at large applications; we may not even have to look too far. Python's Standard Library, for example, is written mostly in Python. Because of the sheer amount of work that's gone into those libraries, the code there is most likely of high quality. We can even view it directly from the SVN repository: http://svn.python.org/projects/python/trunk/Lib/ For example, we can look at code like the 'textwrap' module: http://svn.python.org/projects/python/trunk/Lib/textwrap.py or the source code to IDLE: http://svn.python.org/projects/python/trunk/Lib/idlelib/ Best of wishes! From kent at kentsjohnson.com Sat Feb 25 15:03:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 25 Feb 2006 09:03:56 -0500 Subject: [Tutor] Problem with threads In-Reply-To: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> References: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> Message-ID: <440063CC.2030206@kentsjohnson.com> David Cohen wrote: > Hi all, > > I have a problem trying to use thread on python. > I import the threading module and execute this: > > def func_thread(): > something... > > new_thread = threading.Thread(target = func_thread) > new_thread.start() > > But the thread never really starts, just when I call the > new_thread.join() method. > Does anybody could help me? More code would help. What you have shown looks fine. What does func_thread() do? How do you know it isn't doing it? Here is a very simple, working example based on your code: import threading, time def func_thread(): while True: print 'threading' time.sleep(1) new_thread = threading.Thread(target = func_thread) new_thread.start() print "main thread going away now" Kent From ukc802591034 at btconnect.com Sat Feb 25 12:47:39 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 25 Feb 2006 11:47:39 -0000 Subject: [Tutor] Grepping a file for words in a list Message-ID: <00df01c63a01$48c70a60$0b01a8c0@xp> "John Purser" wrote in message > I'm writing a system admin script in python that checks recently > accessed files for keywords like "failed, denied, error,..." etc. I'm > using popen to call grep -F but it's VERY slow. Can > anyone suggest a faster method to do this? are you trying to locate the actual strings in the files or only testing to see if the strings occur? If the latter then you could use something like files = [f for f in glob(pattern) if mystring in open(f).read()] or for multiple patterns construct a single regex: files = [f for f in glob(pattern) if regex.search(open(f).read())] That might be slightly faster than spawning sub processes with popen. But it won't be a radical difference and if you actually want the line numbers of the patterns I suspect grep will be at least as fast as using python. 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 Sun Feb 26 16:46:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 26 Feb 2006 15:46:09 -0000 Subject: [Tutor] software carpentry References: <20060225194243.30390.qmail@web26604.mail.ukl.yahoo.com> Message-ID: <012a01c63aeb$c3a39100$0b01a8c0@xp> > But the Software Carpentry Workshop was a revelation. It gives a great > deal of advice based on empirical studies on effective programming > practices. I?m partway through - it's a multiweek course. University > lecturer Greg Wilson offers thorough notes to accompany the .mp3 lectures, > all of which is downloadable: > > www.third-bit.com/swc/ I haven't come across this befoire, thanks for the link. > convincingly argues that certain things which require more time up front > save a great deal of time down the road. He stresses using a version > control system, a debugger, test-driven development, and reading lots of > code. I'd agree with all of those, although for the debugger I'd substitute the interactive prompt in Pythons case. I certaimly find it to be a very powerful tool for finding out exactly what a library function does for example. > 1) Is subversion really a good tool for the beginning programmmer, or a > single programmer? If not which version control system would you > recommend? I haven't used SV but it gets good crits. For solo use I tend to use the ancient but simple RCS. For group projects I often use CVS but I'm less keen on it. Professionally I've used lots of tools and the best by far is ClearCase, with almost magical version management capability, but unless you have very deep pockets or, nore realistically, access to a corporately purchased version, its probably unnattainable. > 2) Which debugger should I use if I do most of my work in XP with IDLE? Up > til now I've just been using print statements. who knew? The IDLE debugger is good enough because in Python you rarely need to dive that deep. Coupled to the interactive prompt and a few print statements you shouldn't need anything more. > for (well-written) code? Is it a good idea to look in the standard > libraries for ideas, or code to modify? Thats a tougher one. The code in the libraries is good quality but it is library code and as such is not necessarily representative of how you should write application code. Libraries are designed to be both highly efficient and quite generic. These are normally mutually exclusive qualities To achieve both requires some fairly clever programming tricks and some compromises. If you were to write your own code the wayt libraries get written you would probably wind up writiong a lot more code than was necessary and possibly implementing premature efficiencies which compromise maintainability. So in summary: by all means read the library cpode but don;t necesarily use it as a model for your own. Build the code you need, taking account of good library practice around exception handing etc, but do not over optimise it nor over genericise it. Do the simplest things first, add complexity as you need it. If it becomes a frequent source of change thats the time to consider revisiting the design and adding more generic capability or fine tuning the time critical parts. > How are large applications usually organized, and how do you find > a specific part of it? Using component or subsystyems or modules - different terms that all encpompass the same concept of divide and conquer. Python has very good support for modules at the file level and packages at the next level up. And finally you can create whole collaborations of processes as happens in Web Application Frameworks. Component Diagrams combined with Deployment diagrams in UML are a good way of documenting these relationships should you need to. A basic example can be seen here: http://www.smartdraw.com/examples/software-uml/package_diagram_encapsulation.htm And for an 8 page short intro to UML: http://www-128.ibm.com/developerworks/rational/library/769.html#N1014C And in full detail in the UML specification (PDF format) here: http://www.omg.org/cgi-bin/doc?ptc/2004-10-14 ++++++++ REQUEST FOR FEEDBACK ++++++++ As a general question. I've been toying with the idea of doing a tutorial topic on design & documentation using UML. Focussing on the aspects of UML that I believe are genuinely useful for beginner porogrammers. Is there any demand for that kind of stuff in my tutorial? Feedback is welcomed. ++++++++++++++++++++++++++++++++++++++ > How can you find code specific to certain tasks? Google is your friend... Alan G. From alan.gauld at freenet.co.uk Mon Feb 27 00:25:13 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 26 Feb 2006 23:25:13 -0000 Subject: [Tutor] New Tutorial topic available Message-ID: <013201c63b2b$e5054c40$0b01a8c0@xp> I've just uploaded the latest tutorial topic covering inter-process communications. It covers pipes and the use of fork(). Enjoy, as ever feedback is welcomed. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dacohen at gmail.com Mon Feb 27 00:42:13 2006 From: dacohen at gmail.com (David Cohen) Date: Sun, 26 Feb 2006 19:42:13 -0400 Subject: [Tutor] Problem with threads In-Reply-To: <4400B989.2080403@tds.net> References: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> <4400B989.2080403@tds.net> Message-ID: <4b70acb90602261542m1301ac31v7ecc376686b8f882@mail.gmail.com> Hi, Here is the code attached. It is a simple test program that open a gtk window and connect to a server (might be an irc or telnet server). When the button "Connect" is clicked, the thread (should) starts and read what is coming from the server. But it never happens... just when I click on the "Disconnect" button and the join() function is called. Did you get any problem like that? BR, David On 2/25/06, Kent Johnson wrote: > David Cohen wrote: > > Hi all, > > > > I have a problem trying to use thread on python. > > I import the threading module and execute this: > > > > def func_thread(): > > something... > > > > new_thread = threading.Thread(target = func_thread) > > new_thread.start() > > > > But the thread never really starts, just when I call the > > new_thread.join() method. > > Does anybody could help me? > > More code would help. What you have shown looks fine. What does > func_thread() do? How do you know it isn't doing it? Here is a very > simple, working example based on your code: > > import threading, time > > def func_thread(): > while True: > print 'threading' > time.sleep(1) > > new_thread = threading.Thread(target = func_thread) > new_thread.start() > > print "main thread going away now" > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: test_socket.py Type: text/x-python Size: 3205 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060226/53641114/attachment.py From kent37 at tds.net Mon Feb 27 01:04:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Feb 2006 19:04:35 -0500 Subject: [Tutor] Problem with threads In-Reply-To: <4b70acb90602261542m1301ac31v7ecc376686b8f882@mail.gmail.com> References: <4b70acb90602242315q57c0bf00o3ff7c234e6429fc9@mail.gmail.com> <4400B989.2080403@tds.net> <4b70acb90602261542m1301ac31v7ecc376686b8f882@mail.gmail.com> Message-ID: <44024213.6080808@tds.net> David Cohen wrote: > Hi, > > Here is the code attached. It is a simple test program that open a gtk > window and connect to a server (might be an irc or telnet server). > When the button "Connect" is clicked, the thread (should) starts and > read what is coming from the server. But it never happens... just when > I click on the "Disconnect" button and the join() function is called. > Did you get any problem like that? Ok. I've never worked with gtk, but in GUI frameworks it can be a bad idea to change the gui from a thread other than the event thread, which is what you are doing. My guess is that the socket thread is running but the gui is not updating until you click disconnect and change the gui from the event thread. The first thing I would try is, put a print in GetSockData.run() to see if it is doing anything (my guess is you will see the print). If that works, then you need to learn how to make threads and gtk play together. Here is a tutorial that might help - the first example is pretty close to what you are doing: http://www.pardon-sleeuwaegen.be/antoon/python/page0.html This FAQ entry (from Google's cache, the main site is not responding) shows another way: http://64.233.179.104/search?q=cache:fVAyfmzgtFoJ:www.async.com.br/faq/pygtk/index.py%3Freq%3Dshow%26file%3Dfaq20.006.htp+pygtk+thread&hl=en&gl=us&ct=clnk&cd=7&client=firefox-a HTH, Kent From thomas.s.mark at gmail.com Mon Feb 27 03:04:34 2006 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Sun, 26 Feb 2006 21:04:34 -0500 Subject: [Tutor] New Tutorial topic available In-Reply-To: <013201c63b2b$e5054c40$0b01a8c0@xp> References: <013201c63b2b$e5054c40$0b01a8c0@xp> Message-ID: <7b9699030602261804j328db1c6n1a1d4ea132d05b22@mail.gmail.com> On 2/26/06, Alan Gauld wrote: > I've just uploaded the latest tutorial topic covering inter-process > communications. It covers pipes and the use of fork(). > > Enjoy, as ever feedback is welcomed. Thanks Alan, your pages are a great source of information for us newbies. -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From kp8 at mac.com Mon Feb 27 05:01:13 2006 From: kp8 at mac.com (kevin parks) Date: Sun, 26 Feb 2006 23:01:13 -0500 Subject: [Tutor] list packing In-Reply-To: References: Message-ID: <10ffc3ac7445ec683d6eed1f0db007bc@mac.com> howdy, I am using the os module to do some of my heavy lifting for me. I am tried of building lists by hand so i decided that i would get python to look in a bunch of directories and stuff all the things it find there into a list depending on it's extension. Works great ... one problem sometimes i need just the filenames and that is fine, but more often i need to feed the full path to my other functions.... yet i don't see *any* documentation on os.listdir() at all. I don't know how to give me the full path ... snd = [f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] cheers, kevin From john at fouhy.net Mon Feb 27 05:14:54 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Feb 2006 17:14:54 +1300 Subject: [Tutor] list packing In-Reply-To: <10ffc3ac7445ec683d6eed1f0db007bc@mac.com> References: <10ffc3ac7445ec683d6eed1f0db007bc@mac.com> Message-ID: <5e58f2e40602262014g3dd67731v@mail.gmail.com> On 27/02/06, kevin parks wrote: > snd = [f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] If this is all you need, then you could do something like: snd = ['/Users/kevin/snd/%s' % f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] Or, slightly more robustly (?), snd = [os.path.join('/Users/kevin/snd', f) for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] -- John. From shaleh at speakeasy.net Mon Feb 27 08:34:06 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Sun, 26 Feb 2006 23:34:06 -0800 Subject: [Tutor] list packing In-Reply-To: <5e58f2e40602262014g3dd67731v@mail.gmail.com> References: <10ffc3ac7445ec683d6eed1f0db007bc@mac.com> <5e58f2e40602262014g3dd67731v@mail.gmail.com> Message-ID: <4402AB6E.7020708@speakeasy.net> John Fouhy wrote: > On 27/02/06, kevin parks wrote: > >>snd = [f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] > > > If this is all you need, then you could do something like: > > snd = ['/Users/kevin/snd/%s' % f for f in > os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] > > Or, slightly more robustly (?), > > snd = [os.path.join('/Users/kevin/snd', f) for f in > os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] > os.path.join() is self-documenting. I find this to be a better reason to use it than anything else. But then my code only ever runs on Unix of some flavor. From kp8 at mac.com Mon Feb 27 09:27:02 2006 From: kp8 at mac.com (kevin parks) Date: Mon, 27 Feb 2006 03:27:02 -0500 Subject: [Tutor] list packing In-Reply-To: References: Message-ID: John, Thanks... i am liking this variation a tad more since it means i only have to type the path in one place .... but it is akin to your second one... i was (still am really) having a hard time understanding how to apply path.join _and_ listdir .... sometimes list comprehensions twist my brain but this one is worth studying ... nice! two little lines that do a boatload of work! hee hee ---- pth = '/Users/kpp9c/snd/01' samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith ('.aif')] ---- i could even add: samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith ('.aif' & f.startswith('t')] to make sublists in guess.... What i like about this is that i can chance my directory structure (add/delete/rename/etc) and shape it any way that i want and then Python reflects all my restructuring... lovely... Exactly the type of tedious thing i want Python to do for me *^-^* cheers, kevin From kent37 at tds.net Mon Feb 27 12:25:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Feb 2006 06:25:50 -0500 Subject: [Tutor] list packing In-Reply-To: References: Message-ID: <4402E1BE.9000607@tds.net> kevin parks wrote: > John, > > Thanks... i am liking this variation a tad more since it means i only > have to type the path in one place .... but it is akin to your second > one... i was (still am really) having a hard time understanding > how to apply path.join _and_ listdir .... sometimes list comprehensions > twist my brain but this one is worth studying ... > > nice! two little lines that do a boatload of work! hee hee > > ---- > pth = '/Users/kpp9c/snd/01' > samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith > ('.aif')] > ---- > > i could even add: > samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith > ('.aif' & f.startswith('t')] You might like Jason Orendorff's path module. Using it you can write import path pth = path.path('/Users/kpp9c/snd/01') samples = list(pth.walkfiles('t*.aif')) path.walkfiles() returns an iterator, that is why the list() call is needed. If you are going to loop over the samples you can omit it: for sample in pth.walkfiles('t*.aif'): ... http://www.jorendorff.com/articles/python/path/index.html Kent From kent37 at tds.net Mon Feb 27 13:01:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Feb 2006 07:01:19 -0500 Subject: [Tutor] list packing In-Reply-To: <4402AB6E.7020708@speakeasy.net> References: <10ffc3ac7445ec683d6eed1f0db007bc@mac.com> <5e58f2e40602262014g3dd67731v@mail.gmail.com> <4402AB6E.7020708@speakeasy.net> Message-ID: <4402EA0F.2080707@tds.net> Sean Perry wrote: > os.path.join() is self-documenting. I find this to be a better reason to > use it than anything else. But then my code only ever runs on Unix of > some flavor. I'm not sure why you put in the comment about Unix - os.path.join() is the recommended way of joining paths portably - it will do the right thing on any supported platform. Kent From hugonz-lists at h-lab.net Mon Feb 27 16:24:38 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 27 Feb 2006 09:24:38 -0600 Subject: [Tutor] Finding items in a list In-Reply-To: References: Message-ID: <440319B6.9080901@h-lab.net> As others have said, a concrete example would be great. For the time being, sounds like maybe regular expressions could do it. We don't know if your data is already in a list of small strings, or if it is just a huge string. Take a look here for an intro to RE, though: http://www.amk.ca/python/howto/regex/ Try to send a bit more specifics, we'll be here... Hugo Emily Patek wrote: > Hi - > I am trying to break apart a list into several smaller lists based on repeating nearly identical entries. For example, every so often there is the word CLUSTER with a number after it, like CLUSTER 1. I can find them one by one, but would like to > do a while loop for while item in list = CLUSTER X. Is there a key that I can put in that means "any text that comes after" that would go from cluster to cluster without my typing in each cluster and number? I am a very beginner programmer and am > trying to parse a file of gene-related information that is in a not-so-easy format. I put it into a list based on lines through the splitlines() method. I also thought about splitting the text by CLUSTER and then making each item of the list into > a string that I could then split, but couldn't get that to work either... > > Thanks! > Emily > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sudarshana.ks at gmail.com Mon Feb 27 16:27:44 2006 From: sudarshana.ks at gmail.com (Sudarshana KS) Date: Mon, 27 Feb 2006 20:57:44 +0530 Subject: [Tutor] Converting MAC address . Need Help Message-ID: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> Hi, I am using scapy for writing a dhcp client. The problem i am facing is the mac address i have is in the form 00:11:22:33:44:55 need to convert to '\x00\x11\x22\x33\x44\x55' Please help me out with this problem. The chaddr field in dhcp ( SCAPY) requires '\x00\x11\x22\x33\x44\x55' format. I want this to be assinged through variables. Please let me know if this i doable. Thanks in advance, Sudarshana K S -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060227/397e1461/attachment.html From kent37 at tds.net Mon Feb 27 16:45:32 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Feb 2006 10:45:32 -0500 Subject: [Tutor] Converting MAC address . Need Help In-Reply-To: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> References: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> Message-ID: <44031E9C.8000500@tds.net> Sudarshana KS wrote: > > Hi, > > I am using scapy for writing a dhcp client. > > The problem i am facing is the mac address i have is in the form > 00:11:22:33:44:55 need to convert to '\x00\x11\x22\x33\x44\x55' > Please help me out with this problem. The chaddr field in dhcp ( SCAPY) > requires '\x00\x11\x22\x33\x44\x55' format. If you break this down into smaller pieces it is not so hard. Use the split() method of a string to break it into a list of substrings: >>> mac = '00:11:22:33:44:55' >>> mac.split(':') ['00', '11', '22', '33', '44', '55'] The list elements are still strings, you need to convert them to integers. The strings are in hexadecimal so use the optional base parameter to int(): >>> int('11', 16) 17 Finally you have to convert this number to a byte of a string using chr(): >>> chr(17) '\x11' I'll leave it to you to put all the pieces together. The join() method may be helpful as a last step, it converts a list of strings to a single string: >>> ''.join(['a', 'b', 'c']) 'abc' Kent From janos.juhasz at VELUX.com Mon Feb 27 17:02:50 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 27 Feb 2006 17:02:50 +0100 Subject: [Tutor] RDT server for excel In-Reply-To: Message-ID: Hi All, I would like to make a small RDT Server as COM Server in python that can be called from excel as =RDT("StockBalance.MyServer",,"100007") I'v tried to use google, but with not too much success. I just would like a simple sample. Yours sincerely, ______________________________ J?nos Juh?sz From bgailer at alum.rpi.edu Mon Feb 27 18:08:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 27 Feb 2006 09:08:20 -0800 Subject: [Tutor] RDT server for excel In-Reply-To: References: Message-ID: <44033204.20805@alum.rpi.edu> J?nos Juh?sz wrote: > Hi All, > > I would like to make a small RDT Server as COM Server in python that can be > called from excel as =RDT("StockBalance.MyServer",,"100007") > I for one have no idea what RDT is, so can't help. Maybe someone else has an idea. Or can you give us more information or a link about RDT? [snip] From dyoo at hkn.eecs.berkeley.edu Mon Feb 27 18:40:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Feb 2006 09:40:41 -0800 (PST) Subject: [Tutor] RDT server for excel In-Reply-To: Message-ID: On Mon, 27 Feb 2006, [ISO-8859-1] János Juhász wrote: > I would like to make a small RDT Server as COM Server in python that can > be called from excel as =RDT("StockBalance.MyServer",,"100007") I'v > tried to use google, but with not too much success. I just would like a > simple sample. Hi Janos, Unfortunately, I'm not sure if we can be of much help, since this is very Windows specific. You might want to ask about this on the win32 list; the folks there have more expertise on writing COM servers, and I'm sure they can give a few pointers. Here's a link to their mailing list: http://mail.python.org/mailman/listinfo/python-win32 Best of wishes to you! From travislspencer at gmail.com Tue Feb 28 02:19:24 2006 From: travislspencer at gmail.com (Travis Spencer) Date: Mon, 27 Feb 2006 17:19:24 -0800 Subject: [Tutor] Converting MAC address . Need Help In-Reply-To: <44031E9C.8000500@tds.net> References: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> <44031E9C.8000500@tds.net> Message-ID: On 2/27/06, Kent Johnson wrote: > Sudarshana KS wrote: > > The problem i am facing is the mac address i have is in the form > > 00:11:22:33:44:55 need to convert to '\x00\x11\x22\x33\x44\x55' Perhaps I'm mistaking but it seems that you need to prepend the `\x' escape sequence to the mac address you already have and replace the colons with the same sequence. If it is any harder than that, I'm missing something. If I got what you mean, Sudarshana, you can achieve your goal with this one-liner: >>> macAddress = '00:11:22:33:44:55' >>> reduce(lambda a, b: a + r"\x" + b, macAddress.split(':'), "") '\\x00\\x11\\x22\\x33\\x44\\x55' Perhaps you may prefer this: >>> "\\x" + macAddress.replace(":", "\\x") '\\x00\\x11\\x22\\x33\\x44\\x55' > The list elements are still strings, you need to convert them to > integers. Why is this needed, Kent? Why not just leave them as strings? > The strings are in hexadecimal so use the optional base > parameter to int(): > >>> int('11', 16) > 17 > > Finally you have to convert this number to a byte of a string using chr(): > >>> chr(17) > '\x11' Seems like a lot of extra work to me. -- Regards, Travis Spencer From kent37 at tds.net Tue Feb 28 02:27:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Feb 2006 20:27:03 -0500 Subject: [Tutor] Converting MAC address . Need Help In-Reply-To: References: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> <44031E9C.8000500@tds.net> Message-ID: <4403A6E7.80207@tds.net> Travis Spencer wrote: > On 2/27/06, Kent Johnson wrote: > >>Sudarshana KS wrote: >> >>>The problem i am facing is the mac address i have is in the form >>>00:11:22:33:44:55 need to convert to '\x00\x11\x22\x33\x44\x55' > > > Perhaps I'm mistaking but it seems that you need to prepend the `\x' > escape sequence to the mac address you already have and replace the > colons with the same sequence. If it is any harder than that, I'm > missing something. If I got what you mean, Sudarshana, you can > achieve your goal with this one-liner: > > >>>>macAddress = '00:11:22:33:44:55' >>>>reduce(lambda a, b: a + r"\x" + b, macAddress.split(':'), "") > > '\\x00\\x11\\x22\\x33\\x44\\x55' This is not what Sudarshana asked for - '\\x00' and '\x00' are not the same string - the first is a string of four characters - backslash, letter x, digit 0, digit 0. The second is a string of one character with the character value 0 - a NUL. Sudarshana wants to make a string of byte values, you make a string of character representations of byte values. Very different. >>The list elements are still strings, you need to convert them to >>integers. > > Why is this needed, Kent? Why not just leave them as strings? Because he wants byte values not strings. > > >>The strings are in hexadecimal so use the optional base >>parameter to int(): >> >>> int('11', 16) >>17 >> >>Finally you have to convert this number to a byte of a string using chr(): >> >>> chr(17) >>'\x11' > > Seems like a lot of extra work to me. It all depends on where you want to end up :-) There is actually a one-liner to do this but I didn't want to give it all away. Kent From travislspencer at gmail.com Tue Feb 28 02:35:07 2006 From: travislspencer at gmail.com (Travis Spencer) Date: Mon, 27 Feb 2006 17:35:07 -0800 Subject: [Tutor] Converting MAC address . Need Help In-Reply-To: <4403A6E7.80207@tds.net> References: <8036f2bb0602270727q40d6876aq19fcd8d08231885a@mail.gmail.com> <44031E9C.8000500@tds.net> <4403A6E7.80207@tds.net> Message-ID: On 2/27/06, Kent Johnson wrote: > This is not what Sudarshana asked for - '\\x00' and '\x00' are not the > same string Thanks for clearning that up for me, Kent. -- Regards, Travis Spencer From tvbare at socket.net Tue Feb 28 03:44:02 2006 From: tvbare at socket.net (->Terry<-) Date: Mon, 27 Feb 2006 20:44:02 -0600 (CST) Subject: [Tutor] New Tutorial topic available In-Reply-To: <7b9699030602261804j328db1c6n1a1d4ea132d05b22@mail.gmail.com> References: <013201c63b2b$e5054c40$0b01a8c0@xp> <7b9699030602261804j328db1c6n1a1d4ea132d05b22@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Yesterday (Feb 26, 2006) at 9:04pm, Mark Thomas spoke these wise words: - ->On 2/26/06, Alan Gauld wrote: - ->> I've just uploaded the latest tutorial topic covering inter-process - ->> communications. It covers pipes and the use of fork(). - ->> - ->> Enjoy, as ever feedback is welcomed. - ->Thanks Alan, your pages are a great source of information for us newbies. I agree completely. Thank you Alan! - -- Terry ,-~~-.___. Terry Randall / | ' \ http://members.socket.net/~tvbare/index.html < ) 0 \_/, ,-----' ==== // Linux Counter Project User# 98233 / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware! =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFEA7j2QvSnsfFzkV0RArHtAJ49RVEsvX1fQtcKKdscX7u6dg+mswCfeoNI djWhL1luQtImcmoTloiDNMQ= =25cA -----END PGP SIGNATURE----- From Gideon.STREET at ergon.com.au Tue Feb 28 07:36:05 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Tue, 28 Feb 2006 16:36:05 +1000 Subject: [Tutor] Telnet to cisco device Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC06E356@ebnewem01.ergon> Hi all, I'm trying to get a script together to automate adding a couple of commands across a lot of cisco switches. Thought I'd try to get the script working correctly on one switch first. I've been reading a few online tutorials and have managed to kludge up the following (which fails where commented). Anyone able to advise where I may be going wrong? I'm sitting on a windows box here at work, otherwise I'd see what I could get expect to do. Thanks Gideon -------------------- import getpass import sys import telnetlib HOST = 'switch_name' # this is the hostname for device, to be changed to read from file when figure that out user = raw_input('Username: ') password = getpass.getpass() tn = telnetlib.Telnet(HOST) #make less typing for me tn.read_until('Username: ') #expected prompt after telnetting to the router tn.write(user + '\r\n') #hopefully write username and pass character return raw_input('ENTER to continue') # just to see if it makes this far # this is where the program appears to hang tn.read_until('Password: ') #expected prompt after putting in the username tn.write(password + '\r\n') tn.read_until(HOST + ">") #expected prompt is "hostname>" tn.write('enable \n') # go to exec mode tn.read_until('Password: ') #prompt to go to exec mode tn.write(password + '\n') tn.read_until(HOST + '#') #this should be the prompt after enable "hostname#" tn.write('sh int status' '\r\n') #run this command, read this from file when i figure out how tn.read_until(HOST + '#') #prompt once above command has finished running, useful when reading multiple commands tn.write('exit' '\R\N') #disconnect from the session print tn.read_all() #prints out something, maybe needs to be prior to "exit" command tn.close() This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060228/7d5481b0/attachment.html From hugonz-lists at h-lab.net Tue Feb 28 08:31:08 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 28 Feb 2006 01:31:08 -0600 Subject: [Tutor] Telnet to cisco device In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC06E356@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC06E356@ebnewem01.ergon> Message-ID: <4403FC3C.10805@h-lab.net> Hi Gideon, Seems that you're looking for some prompts, but are you sure they are presented as such from the server? For example, your password prompt has a space after the colon: > tn.read_until('Password: ') #expected prompt after putting in the username Have you tested what you are supposed to be getting with the read_some(1) method??? Try that first, and check that the information you expect is actually the one you should be getting from the server. Hope that gets you on te way to troubleshoot it. Hugo From janos.juhasz at VELUX.com Tue Feb 28 09:34:12 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 28 Feb 2006 09:34:12 +0100 Subject: [Tutor] RDT server for excel In-Reply-To: Message-ID: Hi Danny, Hi Bob, thanks your help. RTD is really very win32 specific. The long name is RealTimeData service, that is implemented as COM service. It retrieves real-time data from a program that supports COM automation. With this service an excel cell can hold the answer of this service called by parameters given in the cell. I just tried to implement it on our network, but it seems to be too handy. Better to not use. I wouldn't like to take care to register com services on every PCs. It shouldn't not simplify but complicate this new possibility. So I just solved the problem in excel with a user defined function. It needn't any extra installation on the PCs. I will use http://mail.python.org/mailman/listinfo/python-win32 next time. I can write a python webserver easier, that can answer on the intranet for this request http:\\www.dataserver.mycompany.com\balance?stockcode=soap&date=today So the webquery seems to be more simple :) Yours sincerely, ______________________________ J?nos Juh?sz Danny Yoo To J?nos Juh?sz cc 2006.02.27 18:40 tutor at python.org Subject Re: [Tutor] RDT server for excel On Mon, 27 Feb 2006, [ISO-8859-1] J?nos Juh?sz wrote: > I would like to make a small RDT Server as COM Server in python that can > be called from excel as =RDT("StockBalance.MyServer",,"100007") I'v > tried to use google, but with not too much success. I just would like a > simple sample. Hi Janos, Unfortunately, I'm not sure if we can be of much help, since this is very Windows specific. You might want to ask about this on the win32 list; the folks there have more expertise on writing COM servers, and I'm sure they can give a few pointers. Here's a link to their mailing list: http://mail.python.org/mailman/listinfo/python-win32 Best of wishes to you! From David.Heiser at intelliden.com Tue Feb 28 09:27:28 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Tue, 28 Feb 2006 01:27:28 -0700 Subject: [Tutor] Telnet to cisco device Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BB88@COSIUM03.intelliden.net> The following works with the Cisco switch that I have available. Cisco 4006 with CatOS 6.2. It may not work with your model/OS or your switch may be configured differently. For instance, the default prompt terminates with "(enable)" so I used "tn.read_until(')')" instead of "tn.read_until(HOST + '#')". ---------------------------------------------- import getpass ##import sys import telnetlib ##HOST = 'switch_name' # this is the hostname for device, to be changed to read from file when figure that out HOST = '10.216.1.223' # this is the hostname for device, to be changed to read from file when figure that out ##user = raw_input('Username: ') """ My switch does not require a username """ ##password = getpass.getpass() print loginpassword = getpass.getpass('Login password: ') """ The login password and enable password may not be the same """ tn = telnetlib.Telnet(HOST) #make less typing for me ##tn.read_until('Username: ') #expected prompt after telnetting to the router ##tn.write(user + '\r\n') #hopefully write username and pass character return ##raw_input('ENTER to continue') # just to see if it makes this far # this is where the program appears to hang ##tn.read_until('Password: ') #expected prompt after putting in the username tn.read_until('password:') """ tn.read_until(':') may also work """ ##tn.write(password + '\r\n') tn.write(loginpassword + '\n') ##tn.read_until(HOST + ">") #expected prompt is "hostname>" tn.read_until(">") """ The prompt may not contain the HOST name """ tn.write('enable \n') # go to exec mode ##tn.read_until('Password: ') #prompt to go to exec mode tn.read_until(':') print enablepassword = getpass.getpass('Enable password: ') ##tn.write(password + '\n') tn.write(enablepassword + '\n') ##tn.read_until(HOST + '#') #this should be the prompt after enable "hostname#" tn.read_until(')') #this should be the prompt after enable "hostname#" ##tn.write('sh int status' '\r\n') #run this command, read this from file when i figure out how tn.write('sh int\n') """ This command works on a Cisco 4006 with CatOS 6.2 """ ##tn.read_until(HOST + '#') #prompt once above command has finished running, useful when reading multiple commands print print tn.read_until(')') ##tn.write('exit' '\R\N') #disconnect from the session tn.write('exit \n') ##print tn.read_all() #prints out something, maybe needs to be prior to "exit" command ##tn.close() """ I don't think you need this """ -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of STREET Gideon (SPARQ) Sent: Monday, February 27, 2006 11:36 PM To: tutor at python.org Subject: [Tutor] Telnet to cisco device Hi all, I'm trying to get a script together to automate adding a couple of commands across a lot of cisco switches. Thought I'd try to get the script working correctly on one switch first. I've been reading a few online tutorials and have managed to kludge up the following (which fails where commented). Anyone able to advise where I may be going wrong? I'm sitting on a windows box here at work, otherwise I'd see what I could get expect to do. Thanks Gideon -------------------- import getpass import sys import telnetlib HOST = 'switch_name' # this is the hostname for device, to be changed to read from file when figure that out user = raw_input('Username: ') password = getpass.getpass() tn = telnetlib.Telnet(HOST) #make less typing for me tn.read_until('Username: ') #expected prompt after telnetting to the router tn.write(user + '\r\n') #hopefully write username and pass character return raw_input('ENTER to continue') # just to see if it makes this far # this is where the program appears to hang tn.read_until('Password: ') #expected prompt after putting in the username tn.write(password + '\r\n') tn.read_until(HOST + ">") #expected prompt is "hostname>" tn.write('enable \n') # go to exec mode tn.read_until('Password: ') #prompt to go to exec mode tn.write(password + '\n') tn.read_until(HOST + '#') #this should be the prompt after enable "hostname#" tn.write('sh int status' '\r\n') #run this command, read this from file when i figure out how tn.read_until(HOST + '#') #prompt once above command has finished running, useful when reading multiple commands tn.write('exit' '\R\N') #disconnect from the session print tn.read_all() #prints out something, maybe needs to be prior to "exit" command tn.close() This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060228/14c3b8e7/attachment-0001.htm From python at venix.com Tue Feb 28 14:04:49 2006 From: python at venix.com (Python) Date: Tue, 28 Feb 2006 08:04:49 -0500 Subject: [Tutor] Telnet to cisco device In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC06E356@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC06E356@ebnewem01.ergon> Message-ID: <1141131889.15743.288.camel@www.venix.com> On Tue, 2006-02-28 at 16:36 +1000, STREET Gideon (SPARQ) wrote: > tn.read_until('Username: ') #expected prompt after telnetting to the > router > tn.write(user + '\r\n') #hopefully write username and pass character > return > Sending both \r and \n may be confusing things. I'd recommend using tcpwatch.py http://hathawaymix.org/Software/TCPWatch to monitor a telnet session that works. That way you will have a collection of exact prompts available to build your script. -- Lloyd Kvam Venix Corp From winglion1 at 163.com Tue Feb 28 14:36:43 2006 From: winglion1 at 163.com (=?gb2312?B?zPrKrw==?=) Date: Tue, 28 Feb 2006 21:36:43 +0800 Subject: [Tutor] switch-case in python Message-ID: <44045587.2376F9.05190> I know this may seem to be stupid. but as I found that there's no switch-case control flow in python, an I just can't remember( or know) any method to make such a control flow. From Barry.Carroll at psc.com Tue Feb 28 21:58:12 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 28 Feb 2006 12:58:12 -0800 Subject: [Tutor] Unexpected Behavior in unittest Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3602@eugsrv400.psc.pscnet.com> Greetings: This is a fairly long-winded question. I beg your indulgence. I am writing unit tests for our bar code scanner test software, and I have encountered some results that I cannot explain nor get around. Here is the scenario. Our program implements a generator class for creating 'label' objects. Leaving out a lot of detail, the generator converts a text string into a list of floats (txtlst), along with other attributes. My unit tests verify that the 'label' has been constructed correctly. One of the generator class's attributes is the character separator (cs), a float which is inserted between the individual character representations in the label's txtlst. This value is set when the generator object is created (default is 1.0), and can be changed by a simple assignment at any time before the label object is generated. One of my tests verifies that, when cs is changed, the new value appears in the txtlst attribute for labels created after the change. To test this, I do the following: 1. create a generator object 2. check the cs value 3. create a label 4. check the cs values in txtlst 5. change the generator's cs value 6. check the new cs value 7. create a new label 8. check the cs values in the new txtlst The first code excerpt implements these steps outside the unittest framework. ########################################### #!/usr/bin/python2.3 from lblgen import * lg = lblgen(t = 'Any string here') print '\n\nlg.cs: %.1f' % lg.cs assert(1.0 == lg.cs) lbl = lg.generate() for x in lbl.txtlst[lbl.chlen::lbl.chlen]: assert(1.0 == x) lg.cs = 2.5 print '\n\nlg.cs: %.1f' % lg.cs assert(2.5 == lg.cs) lbl = lg.generate() for x in lbl.txtlst[lbl.chlen::lbl.chlen]: assert(2.5 == x) ########################################### As the output shows, the assignment to lg.cs succeeded and the proper value was found in txtlst (no exceptions thrown by the assert statements). >>>>>>>>>>>>>>>>>>>>>> lg.cs: 1.0 lg.cs: 2.5 >>>>>>>>>>>>>>>>>>>>>> The next excerpt does the same steps inside the unittest framework. ########################################### #!/usr/bin/python2.3 from lblgen import * import unittest class cs_tryout(unittest.TestCase): def test_cs(self): lg = lblgen(t = 'Any string here') msg = ('Generator cs is incorrect.\nExpected %3.1f; got %3.1f' % (1.0, lg.cs)) self.assertEqual(1.0, lg.cs, msg) lbl = lg.generate() msg = 'txtlst entry %d is incorrect.\nExpected %3.1f; got %3.1f' for ndx, got in enumerate(lbl.txtlst[lbl.chlen::lbl.chlen]): self.assertEqual(1.0, got, msg % (ndx, 1.0, got)) lg.cs = 2.5 msg = ('Generator cs is incorrect.\nExpected %3.1f; got %3.1f' % (2.5, lg.cs)) self.assertEqual(2.5, lg.cs, msg) lbl = lg.generate() msg = 'txtlst entry %d is incorrect.\nExpected %3.1f; got %3.1f' for ndx, got in enumerate(lbl.txtlst[lbl.chlen::lbl.chlen]): self.assertEqual(2.5, got, msg % (ndx, 2.5, got)) if __name__=='__main__': unittest.main( ) ########################################### In this case, the assignment to lg.cs failed. >>>>>>>>>>>>>>>>>>>>>> F ====================================================================== FAIL: test_cs (__main__.cs_tryout) ---------------------------------------------------------------------- Traceback (most recent call last): File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in test_cs self.assertEqual(expect, lg.cs, msg) File "C:\PROGRA~1\Python23\lib\unittest.py", line 302, in failUnlessEqual raise self.failureException, \ AssertionError: Generator cs is incorrect. Expected 2.5; got 1.0 ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1) >>>>>>>>>>>>>>>>>>>>>> Can anyone tell me why it should fail here and succeed when unittest is not involved? I need to be able to verify that this and other attributes can be changed, and I don't want to abandon the unittest framework if I can avoid it. Thanks in advance for your help. ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From dyoo at hkn.eecs.berkeley.edu Tue Feb 28 23:08:11 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Feb 2006 14:08:11 -0800 (PST) Subject: [Tutor] Unexpected Behavior in unittest In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3602@eugsrv400.psc.pscnet.com> Message-ID: > In this case, the assignment to lg.cs failed. > >>>>>>>>>>>>>>>>>>>>>> > F > ====================================================================== > FAIL: test_cs (__main__.cs_tryout) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in test_cs > self.assertEqual(expect, lg.cs, msg) > File "C:\PROGRA~1\Python23\lib\unittest.py", line 302, in failUnlessEqual > raise self.failureException, \ > AssertionError: Generator cs is incorrect. > Expected 2.5; got 1.0 > Hi Barry, I think the bug here is less glamorous than you might expect. I'd recommend rerunning the unit test again, and watch carefully about what exactly you're running. It's strongly possible that you may be running the wrong test program: I see a reference to a 'test3.py' there in the error message that dies on the line: self.assertEqual(expect, lg.cs, msg) But, hunting through the class that you've shown us, I see no such line. *grin* The simplest explanation is that you're not running the test program that you think you're running. Double check that you mean to run 'test3.py', as opposed to some other 'test*' program in your working directory. Good luck! From Barry.Carroll at psc.com Tue Feb 28 23:30:58 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 28 Feb 2006 14:30:58 -0800 Subject: [Tutor] Unexpected Behavior in unittest Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3604@eugsrv400.psc.pscnet.com> Danny: I wish it were that simple. 'test3.py' is the name of the file containing the test case class. I left the invocation out of my output excerpt. It should look like this: >>>>>>>>>>>>>>>>>>>>>>>> J:\My Documents\Projects\Mongoose\symgen\test3.py F ====================================================================== FAIL: test_cs (__main__.cs_tryout) ---------------------------------------------------------------------- Traceback (most recent call last): File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in test_cs <<>> FAILED (failures=1) >>>>>>>>>>>>>>>>>>>>>>>> BTW the other code excerpt was from a file named 'test1.py' in the same directory. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] > Sent: Tuesday, February 28, 2006 2:08 PM > To: Carroll, Barry > Cc: tutor at python.org > Subject: Re: [Tutor] Unexpected Behavior in unittest > > > > In this case, the assignment to lg.cs failed. > > >>>>>>>>>>>>>>>>>>>>>> > > F > > ====================================================================== > > FAIL: test_cs (__main__.cs_tryout) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in > test_cs > > self.assertEqual(expect, lg.cs, msg) > > File "C:\PROGRA~1\Python23\lib\unittest.py", line 302, in > failUnlessEqual > > raise self.failureException, \ > > AssertionError: Generator cs is incorrect. > > Expected 2.5; got 1.0 > > > > Hi Barry, > > I think the bug here is less glamorous than you might expect. I'd > recommend rerunning the unit test again, and watch carefully about what > exactly you're running. > > It's strongly possible that you may be running the wrong test program: I > see a reference to a 'test3.py' there in the error message that dies on > the line: > > self.assertEqual(expect, lg.cs, msg) > > But, hunting through the class that you've shown us, I see no such line. > *grin* > > The simplest explanation is that you're not running the test program that > you think you're running. Double check that you mean to run 'test3.py', > as opposed to some other 'test*' program in your working directory. > > > Good luck! > > > From dyoo at hkn.eecs.berkeley.edu Tue Feb 28 23:56:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Feb 2006 14:56:54 -0800 (PST) Subject: [Tutor] Unexpected Behavior in unittest In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3604@eugsrv400.psc.pscnet.com> Message-ID: > I wish it were that simple. 'test3.py' is the name of the file > containing the test case class. I left the invocation out of my output > excerpt. It should look like this: Hi Barry, Ok. But still go back and make sure you're running the right file. The error message says that: > Traceback (most recent call last): > File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in > test_cs So Python's running a program that has at least 25 lines in it. But the test3.py file you've shown us at the bottom of: http://mail.python.org/pipermail/tutor/2006-February/045423.html just simply doesn't have that many lines. Let's look again at the program you're showing us as 'test3.py': ########################################### #!/usr/bin/python2.3 from lblgen import * import unittest class cs_tryout(unittest.TestCase): def test_cs(self): lg = lblgen(t = 'Any string here') msg = ('Generator cs is incorrect.\nExpected %3.1f; got %3.1f' % (1.0, lg.cs)) self.assertEqual(1.0, lg.cs, msg) lbl = lg.generate() msg = 'txtlst entry %d is incorrect.\nExpected %3.1f; got %3.1f' for ndx, got in enumerate(lbl.txtlst[lbl.chlen::lbl.chlen]): self.assertEqual(1.0, got, msg % (ndx, 1.0, got)) lg.cs = 2.5 msg = ('Generator cs is incorrect.\nExpected %3.1f; got %3.1f' % (2.5, lg.cs)) self.assertEqual(2.5, lg.cs, msg) lbl = lg.generate() msg = 'txtlst entry %d is incorrect.\nExpected %3.1f; got %3.1f' for ndx, got in enumerate(lbl.txtlst[lbl.chlen::lbl.chlen]): self.assertEqual(2.5, got, msg % (ndx, 2.5, got)) if __name__=='__main__': unittest.main( ) ########################################### What you're showing us above --- what you think is test3.py --- and what the error message is saying here: ######################################################################### Traceback (most recent call last): File "J:\My Documents\Projects\Mongoose\symgen\test3.py", line 25, in test_cs self.assertEqual(expect, lg.cs, msg) File "C:\PROGRA~1\Python23\lib\unittest.py", line 302, in failUnlessEqual raise self.failureException, \ ######################################################################### presents two inconsistent views of what should be the same exact program. We can look at this more closely: the error message has a reference to an 'expect' variable name, but this doesn't exist in the program you're showing us. Python isn't magical, so I have to assume that some program, different than the one you've shown us, is being executed. Does this make sense?