Re: [Tutor] Automatic updates for a program?
Lan Rogers lan.rogers.b...@gmail.com wrote So I have a program I want to release, but it's still in early stages without some of its planned functionality. I want to distribute automatic updates. Don't assume this will be easy, and be prepared for it to cramp your style when it comes to designing and developing the app. It will place major restrictions on what you can do. Only do it if its essential. I'm working under the assumption that the easiest way to do this is to just replace the old files with the new ones. A lot depends on which OS you are using. If its Windows thre are a bunch of other things you will probably need to do too, like update registry entries and mess about with COM IDs etc. questions is this: How do I replace a script that is running, with a new version? Again it depends on the OS. It may not be possible, you may have to force a restart. Thats by far the easiest way. On Windows its common to do it on the next reboot by setting up a RunOnce job in the registry. (But that only works well because Windows tends to need rebooting a lot!) You might also want to consider whwether you need a backout strategy to revert to a previous working version. That will complicate things even more. OTOH If your program architecture is very simple, just a few scripts in a single folder and not using the OS features or a database or networking then many of these complexities can be avoided. (But replacing a running process is still tricky. You need to build the functionality into the existing code to replace itself - typically using spawn() or exec() or fork() assuming Linux/MacOS - and then triggger that functionality from your installer) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Just Joined!
Okay I think I understand now. Is there a module i need to import though when defining ?I did a help(module), not sure which module is the correct one to make swapcase.center work properly... On May 12, 2011, at 10:17 AM, Alan Gauld wrote: Alex Smith alexsmith24...@yahoo.com wrote SwapcaseAndCenter('hello', 10) I don't understand how from your example you get an output ...I get the below error: NameError: name 'SwapcaseAndCenter' is not defined Wayne was showing how it should work. As Python says the function is not defined yet. Defining the function so that is does do what Wayne showed is your homework! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Just Joined!
You can ignore last question, was trying to figure out Alex's issue as well, but I got it now. sorry for the spam! On May 13, 2011, at 3:57 AM, Johnson Tran wrote: Okay I think I understand now. Is there a module i need to import though when defining ?I did a help(module), not sure which module is the correct one to make swapcase.center work properly... On May 12, 2011, at 10:17 AM, Alan Gauld wrote: Alex Smith alexsmith24...@yahoo.com wrote SwapcaseAndCenter('hello', 10) I don't understand how from your example you get an output ...I get the below error: NameError: name 'SwapcaseAndCenter' is not defined Wayne was showing how it should work. As Python says the function is not defined yet. Defining the function so that is does do what Wayne showed is your homework! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] python file upload
Hi all, I need a python script to upload a xml file to a web page using python. I have tried using pycurl but I am still getting errors. import urllib2 import pycurl data= ?xml version=1.0 encoding=UTF-8? !DOCTYPE ProvisioningRequest SYSTEM ProvisioningRequest.dtd ProvisioningRequest TransactionId=000332 Version=1.2 TransactionType=Activate ProductType=BlackBerry Header Sender id=349114 name=GTT Logingtt_admin/Login PasswordPassword2011/Password /Sender TimeStamp2001-11-15T13:18:08-08:00/TimeStamp /Header Body ProvisioningEntity name=subscriber ProvisioningDataItem name=BillingId738002000417469/ProvisioningDataItem ProvisioningEntity name=service ProvisioningDataItem name=ServiceNameEnterprise B/ProvisioningDataItem /ProvisioningEntity /ProvisioningEntity /Body /ProvisioningRequest headers = [Content-Type:text/xml] #data = open(d:\\dump\\activation.xml) c = pycurl.Curl() c.setopt(c.URL, https://provisioning.etr.blackberry.net/ari/submitXML;) c.setopt(pycurl.POST,1) c.setopt(pycurl.SSL_VERIFYPEER, 0) c.setopt(pycurl.SSL_VERIFYHOST, 0) c.setopt(pycurl.HTTPHEADER, headers) c.setopt(pycurl.POSTFIELDS, data) c.setopt(c.VERBOSE, 1) c.perform() c.close() this is the error I am getting. * About to connect() to provisioning.etr.blackberry.net port 443 (#0) * Trying 216.9.243.178... * connected * Connected to provisioning.etr.blackberry.net (216.9.243.178) port 443 (#0) * libcurl is now using a weak random seed! * SSL connection using RC4-MD5 * Server certificate: * subject: C=CA; ST=Ontario; L=Waterloo; O=Research In Motion Limited; OU=IT; CN=provisioning.etr.blackberry.net * start date: 2011-03-28 00:00:00 GMT * expire date: 2012-03-27 23:59:59 GMT * issuer: C=US; O=Thawte, Inc.; CN=Thawte SSL CA * SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway. POST /ari/submitXML HTTP/1.1 User-Agent: PycURL/7.19.7 Host: provisioning.etr.blackberry.net Accept: */* Content-Type:text/xml Content-Length: 836 HTTP/1.1 500 Internal Server Error Connection: close Date: Fri, 13 May 2011 18:35:24 GMT Content-Length: 90 Content-Type: text/html X-Powered-By: Servlet/2.5 JSP/2.1 * Closing connection #0 ERROR_ID=PARSEING_ERROR DESCRIPTION=Request parsing failed: Tag in line:2 Ending column:6 Regards Rayon ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] short url processor
Hey folks, I'm rewriting a short url processor for my job. I had originally written it as a multi-threaded Perl script, which works, but has socket problems causing memory leaks. Since I'm rebuilding it to use memcache, and since I was learning Python outside of work anyway, figured I'd rewrite it in Python. I'm using BaseHTTPServer, overriding do_GET and do_POST, and want to set up a custom logging mechanism so I don't have to rewrite a separate log parser, which I'll eventually rewrite in Python as well. The problem I'm having, though, is that the BaseHTTPServer setup is outputting what appears to be an apache-style log to STDOUT, but the logging.debug or logging.info calls I make in the code are also going to STDOUT despite my attempt to use logging.basicConfig() overrides and setting a filename, etc. Here's the basics of what I'm doing. Forgive my code, I've already been told it's ugly, I'm new to Python and come from a background of Perl/PHP. import struct import string,cgi,time import psycopg import logging import re import memcache from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from time import strftime,localtime class clientThread(BaseHTTPRequestHandler): def log_my_request(self,method,request,short_url,http_code,long_url,cached,notes): logging.debug(%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s, self.client_address[0], time.strftime(%Y-%m-%d %H:%M:%S,localtime()), method, # get or post request, # requested entity short_url, # matching short_url based on entity, if any http_code, # 200, 301, 302, 404, etc long_url, # url to redirect to, if there was one cached, # 'hit', 'miss', 'miss-db', 'error' notes # extra notes for the log file only ) return def do_GET(self) # logic goes here for finding a short url form memcache, then writing the appropriate # output data to the socket, then logging happens: self.log_my_request(getpost,orig_short_url,short_url,'302',long_url,'hit','') return def main(): if mc.get('dbcheck'): # memcache already has some data print(memcache already primed with data) else: # nothing in memcache, so load it up from database print('Connecting to PG') cur.execute(SELECT count(*) FROM short_urls) ; mycount = cur.fetchone() ; print(fetching %s entries, mycount) cur.execute(SELECT short_url,long_url FROM short_urls) giant_list = cur.fetchall() # cache a marker that tells us we've already initialized memcache with db data mc.set('dbcheck','databasetest',0) # I'm sure there's a MUCH more efficient way of doing this ... multi-set of some sort? for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) print(finished retrieving %s entries plus set up a new dictionary with all values % mycount) #{{ set up the socket, bind to port, and wait for incoming connections try: server = HTTPServer(('',8083), clientThread) print 'short url processing has begun' # this is where I try to tell Python that I only want my message in my log: # no INFO:username prefix, etc., and also to write it to a file logging.basicConfig(level=logging.DEBUG) logging.basicConfig(format='%(message)s', filename='/tmp/ian.txt') server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() My code runs without any errors, though I have left some code out of this Email that I didn't feel was relevant such as the logic of seeing if a short url exists in memcache, trying to fetch from the db if there was no match, and if the db lookup also fails, force-deleting short urls from memcache based on other instructions, that sort of thing. None of it deals with logging or the BaseHTTPServer code. To recap, the code runs, redirects are working, but ALL output goes to STDOUT. I can understand that print statements would go to STDOUT, but the BaseHTTPServer seems to want to write the Apache-style log to STDOUT, and my logging.info() call also prints to STDOUT instead of my file. I'd love to hear any thoughts from people that have had to deal with this. The logging is the last piece of the puzzle for me. Thanks, Ian ___ Tutor maillist - Tutor@python.org To
[Tutor] Fw: Automatic updates for a program?
Forwarding to list for wider feedback. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ - Forwarded Message From: Lan Rogers lan.rogers.b...@gmail.com To: Alan Gauld alan.ga...@btinternet.com Sent: Friday, 13 May, 2011 22:46:41 Subject: Re: [Tutor] Automatic updates for a program? On Fri, May 13, 2011 at 12:38 AM, Alan Gauld alan.ga...@btinternet.com wrote: So I have a program I want to release, but it's still in early stages without some of its planned functionality. I want to distribute automatic updates. Don't assume this will be easy, and be prepared for it to cramp your style when it comes to designing and developing the app. It will place major restrictions on what you can do. Only do it if its essential. I assume there will be some challenges involved, it's not absolutely critical, but it's something I'd like to understand even if I don't incorporate it into my current project. I'm working under the assumption that the easiest way to do this is to just replace the old files with the new ones. A lot depends on which OS you are using. If its Windows thre are a bunch of other things you will probably need to do too, like update registry entries and mess about with COM IDs etc. questions is this: How do I replace a script that is running, with a new version? Again it depends on the OS. It may not be possible, you may have to force a restart. Thats by far the easiest way. On Windows its common to do it on the next reboot by setting up a RunOnce job in the registry. (But that only works well because Windows tends to need rebooting a lot!) You might also want to consider whwether you need a backout strategy to revert to a previous working version. That will complicate things even more. OTOH If your program architecture is very simple, just a few scripts in a single folder and not using the OS features or a database or networking then many of these complexities can be avoided. (But replacing a running process is still tricky. You need to build the functionality into the existing code to replace itself - typically using spawn() or exec() or fork() assuming Linux/MacOS - and then triggger that functionality from your installer) I'm working on windows, and I distribute a single executable file, made with py2exe. I'm not sure if that simplifies things or complicates them. I'm thinking of writing batch script that will handle deleting and and replacing the old version of my application (via restart and RunOnce job, like you mentioned), then deleting that script on the first execution of the new version of my application. Does that sound reasonable or am I kidding myself? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Overriding a method in a class
I have a pretty basic point of confusion that I'm hoping I can have explained to me. I have a class in which I want to override a method, and have my method defined externally to the class definition invoked instead. But when I do so, my external method is invoked with a different argument signature than the method it overrides. (I'll illustrate with a toy example named toy.py that maintains a list of strings; the actual use case is a wxPython drag-and-drop shell that I find I keep re-using over and over, so I decided to try to turn it into a general-purpose module for my own use.) ### example 1 begin class Thing(object): def __init__(self): self.stuff = [] def addstuff(self, text): self.add_the_stuff(text) def add_the_stuff(self, s1): self.stuff.append(s1) A = Thing() A.addstuff(ABCDEFG) print A.stuff ### example 1 end So far, this works as expected. addstuff invokes add_the_stuff; and the line print A.stuff prints out as ['ABCDEFG'], as expected. Now, here's where I am getting befuddled, with the following additional lines: ### example, continued def addlower(self, s2): self.stuff.append(s2.lower()) # add it as lower case B = Thing() B.add_the_stuff=addlower B.addstuff(WXYZ) print B.stuff ### end My *intent* here is to patch the Thing object named B so that the B's add_the_stuff method is replaced with this additional addlower method that I define external to the object. My expectation would be that, just as add_the_stuff method was called with two arguments (self and the string), the patched-in addlower would also get called the same way. What I *expect* is to see ['abcdefg'] printed. What I get is: Traceback (most recent call last): File E:\Personal\py\DragDrop\toy.py, line 22, in module B.addstuff(WXYZ) File E:\Personal\py\DragDrop\toy.py, line 7, in addstuff self.add_the_stuff(text) TypeError: addlower() takes exactly 2 arguments (1 given) I'm assuming I'm missing some fundamental concept. What is it? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] short url processor
ian douglas ian.doug...@iandouglas.com wrote outputting what appears to be an apache-style log to STDOUT, but the logging.debug or logging.info calls I make in the code are also going to STDOUT despite my attempt to use logging.basicConfig() overrides and setting a filename, etc. I don;t know anything about BaseHTTPServer and not much about the logging modules however some thoughts are... How do you know they are going to stdout? Are you sure they aren't going to stderr and stderrr is not mapped to stdout (usually the default). Have you tried redirecting stderr to a file for example? As I say, just some thoughts, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overriding a method in a class
On Fri, 13 May 2011, Terry Carroll wrote: What I *expect* is to see ['abcdefg'] printed. What I get is: Sorry, mixed multiple examples; What I had expected was ['wxyz']. Still the same question though. BTW, I forgot to mention: Python 2.7.1, under Windows. (Still not used to the Python 2.x/3.x thing) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overriding a method in a class
I think the problem is this bit about overriding an object's internal method with one that is defined externally. My gut feeilng is that you'd now have to explicitly pass the object (i.e., self) as well as the string, i.e.: B.addstuff(B, WXYZ) ...which seems clunky. I'm not familiar with this particular technique. Is it common to do something like this? On Fri, 13 May 2011, Terry Carroll wrote: I have a pretty basic point of confusion that I'm hoping I can have explained to me. I have a class in which I want to override a method, and have my method defined externally to the class definition invoked instead. But when I do so, my external method is invoked with a different argument signature than the method it overrides. (I'll illustrate with a toy example named toy.py that maintains a list of strings; the actual use case is a wxPython drag-and-drop shell that I find I keep re-using over and over, so I decided to try to turn it into a general-purpose module for my own use.) ### example 1 begin class Thing(object): def __init__(self): self.stuff = [] def addstuff(self, text): self.add_the_stuff(text) def add_the_stuff(self, s1): self.stuff.append(s1) A = Thing() A.addstuff(ABCDEFG) print A.stuff ### example 1 end So far, this works as expected. addstuff invokes add_the_stuff; and the line print A.stuff prints out as ['ABCDEFG'], as expected. Now, here's where I am getting befuddled, with the following additional lines: ### example, continued def addlower(self, s2): self.stuff.append(s2.lower()) # add it as lower case B = Thing() B.add_the_stuff=addlower B.addstuff(WXYZ) print B.stuff ### end My *intent* here is to patch the Thing object named B so that the B's add_the_stuff method is replaced with this additional addlower method that I define external to the object. My expectation would be that, just as add_the_stuff method was called with two arguments (self and the string), the patched-in addlower would also get called the same way. What I *expect* is to see ['abcdefg'] printed. What I get is: Traceback (most recent call last): File E:\Personal\py\DragDrop\toy.py, line 22, in module B.addstuff(WXYZ) File E:\Personal\py\DragDrop\toy.py, line 7, in addstuff self.add_the_stuff(text) TypeError: addlower() takes exactly 2 arguments (1 given) I'm assuming I'm missing some fundamental concept. What is it? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] short url processor
On 05/13/2011 05:03 PM, Alan Gauld wrote: How do you know they are going to stdout? Are you sure they aren't going to stderr and stderrr is not mapped to stdout (usually the default). Have you tried redirecting stderr to a file for example? As I say, just some thoughts, Thanks for your thoughts, Alan. I had done some testing with cmdline redirects and forget which is was, I think my debug log was going to stdout and the apache-style log was going to stderr, or the other way around... After a handful of guys in the #python IRC channel very nearly convinced me that all but 3 stdlib libraries are utter worthless crap, and telling me to download and use third-party frameworks just to fix a simple logging issue, I overrode log_request() and log message() as such: class clientThread(BaseHTTPRequestHandler): #[[[ def log_request(code, size): return def log_message(self, format, *args): open(LOGFILE, a).write(%s\n % (format%args)) ... and now the only logging going on is my own, and it's logged to my external file. Overriding log_request means that BaseHTTPServer no longer outputs its apache-style log, and overriding log_message means my other logging.info() and logging.debug() messages go out to my file as expected. -id ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help with exceptions please
Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the 'error that has occurred'. I only want it to do this if someone doesn't enter an number. Could I have some comments on my code for the first program of my assignment if you have some time please. Assignment Question: The Springfork Amateur Golf club has a tournament every weekend. The club president has asked you to write two programs: 1. A program that will read each player's name and golf score as keyboard input and then to save these records in a file named golf.txt. (Each record will have a field name for the player's name and a field for the player's score. 2. A program that reads the records from the golf.txt and displays them. def main(): try: # Get the number of players golf_scores = int(raw_input('How many players playing this weekend? ')) # Open a file to hold player names and scores player_data = open('golf.txt', 'w') # Get the players name and score and write it to the file for count in range(1, golf_scores + 1): # Get the name name and score for player print 'Enter the name and score for player #' + str(count) name = raw_input('Name: ') score = int(raw_input('Score: ')) # Write the data as a record to the file golf.txt player_data.write(name + '\n') player_data.write(score + '\n') # Display a blank line print # Close the file player_data.close() print 'Players and their score have been written to golf.txt.' except IOError: print 'An error occured trying to write information to file.' except ValueError: print 'A numberic value must be entered.' except: print 'An error occured.' # Call the main function main() Thanks in advance. Lea ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] short url processor
On 05/13/2011 05:03 PM, Alan Gauld wrote: As I say, just some thoughts, I *am* curious, Alan, whether you or anyone else on the list are able to help me make this a little more efficient: cur.execute(SELECT short_url,long_url FROM short_urls) giant_list = cur.fetchall() for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) At present, we have about two million short URL's in our database, and I'm guessing there's a much smoother way of iterating through 2M+ rows from a database, and cramming them into memcache. I imagine there's a map function in there that could be much more efficient? v2 of our project will be to join our short_urls table with its 'stats' table counterpart, to where I only fetch the top 10,000 URLs (or some other smaller quantity). Until we get to that point, I need to speed up the restart time if this script ever needs to be restarted. This is partly why v1.5 was to put the database entries into memcache, so we wouldn't need to reload the db into memory on every restart. Thanks, Ian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overriding a method in a class
On Fri, 13 May 2011, David Knupp wrote: I think the problem is this bit about overriding an object's internal method with one that is defined externally. Yes, that describes the phenomenon. My gut feeilng is that you'd now have to explicitly pass the object (i.e., self) as well as the string, i.e.: B.addstuff(B, WXYZ) ...which seems clunky. But worse, it would mean that you couldn't have the default un-overridden method for those cases where you don't need to override it. I'm not familiar with this particular technique. Is it common to do something like this? Certainly the problem is common. For my specific case, I'm going to go with a Plan B of using callbacks; and provide default unbound callbacks present in the module, but not defined in the class itself. But I'd still like to have a better understanding of how the call gets transmuted from a two-argument call to a one-argument call based upon the target. I suspect something along these lines is going on: begin uninformed speculation When a bound method is called, Python inserts a reference to self as an additional first argument, before the other arguments. It does not do this with unbound methods. In my first case, when I created object A, the name add_the_stuff references the bound method add_the_stuff as defined in the Thing class. When add_stuff calls add_the_stuff, because add_the_stuff references a bound method, Python does the automagical insertion of the self argument. In my second case, when I created the object B, the name add_the_stuff *initially* references the bound method add_the_stuff; but then, when I override, I make B.add_the_stuff reference the unbound external method. Now, when addstuff calls add_the_stuff, Python sees that it is referencing an unbound method, and does not insert the self reference into the argument list. end uninformed speculation Now I'll wait for one of the experts to edify me. On Fri, 13 May 2011, Terry Carroll wrote: I have a pretty basic point of confusion that I'm hoping I can have explained to me. I have a class in which I want to override a method, and have my method defined externally to the class definition invoked instead. But when I do so, my external method is invoked with a different argument signature than the method it overrides. (I'll illustrate with a toy example named toy.py that maintains a list of strings; the actual use case is a wxPython drag-and-drop shell that I find I keep re-using over and over, so I decided to try to turn it into a general-purpose module for my own use.) ### example 1 begin class Thing(object): def __init__(self): self.stuff = [] def addstuff(self, text): self.add_the_stuff(text) def add_the_stuff(self, s1): self.stuff.append(s1) A = Thing() A.addstuff(ABCDEFG) print A.stuff ### example 1 end So far, this works as expected. addstuff invokes add_the_stuff; and the line print A.stuff prints out as ['ABCDEFG'], as expected. Now, here's where I am getting befuddled, with the following additional lines: ### example, continued def addlower(self, s2): self.stuff.append(s2.lower()) # add it as lower case B = Thing() B.add_the_stuff=addlower B.addstuff(WXYZ) print B.stuff ### end My *intent* here is to patch the Thing object named B so that the B's add_the_stuff method is replaced with this additional addlower method that I define external to the object. My expectation would be that, just as add_the_stuff method was called with two arguments (self and the string), the patched-in addlower would also get called the same way. What I *expect* is to see ['abcdefg'] printed. What I get is: Traceback (most recent call last): File E:\Personal\py\DragDrop\toy.py, line 22, in module B.addstuff(WXYZ) File E:\Personal\py\DragDrop\toy.py, line 7, in addstuff self.add_the_stuff(text) TypeError: addlower() takes exactly 2 arguments (1 given) I'm assuming I'm missing some fundamental concept. What is it? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with exceptions please
On Fri, May 13, 2011 at 7:48 PM, Lea Parker lea-par...@bigpond.com wrote: Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the ‘error that has occurred’. I only want it to do this if someone doesn’t enter an number. snip I don't have a lot of time to look at it right now, but what happens when you remove the final except? Having a catch-all can hide all sorts of exceptions. If you remove that, then python should tell you what kind of error it got. That traceback will be much more helpful than 'error that has occurred'. If that doesn't help you fix the problem, then remember the three things you need: 1. What did I do? 2. What did I expect would happen? 3. What happened instead? For 3, that also means that you should post all the (relevant) output. That means errors, and usually correct output, especially if there's not a whole lot of it. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overriding a method in a class
On Fri, 13 May 2011, Terry Carroll wrote: For my specific case, I'm going to go with a Plan B of using callbacks; and provide default unbound callbacks present in the module, but not defined in the class itself. Here's a callback-with-default approach, which works: ### Thing.py def add_the_stuff(obj, s1): obj.stuff.append(s1) class Thing(object): def __init__(self, callback=add_the_stuff): self.stuff = [] self.cb=callback def addstuff(self, text): self.cb(self, text) # # toy2.py ### import Thing A = Thing.Thing() A.addstuff(ABCDEFG) print A.stuff def addlower(obj, s2): obj.stuff.append(s2.lower()) B = Thing.Thing(callback=addlower) B.addstuff(WXYZ) print B.stuff Which produces, as expected: toy2.py ['ABCDEFG'] ['wxyz'] But still... But I'd still like to have a better understanding of how the call gets transmuted from a two-argument call to a one-argument call based upon the target. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] short url processor
On 05/14/2011 03:49 AM, ian douglas wrote: for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) Until Alan comes with a more round answer, I'd suggest something along the lines of [mc.set(x, y) for (x, y) in giant_list if x and y] I'm writing this by memory, but check list comprehension in the documentation. Anyway, there are map, reduce and such functions in python, but I think that in python 3.x you have to import them. Now, the real question would be, can you use the cursor as an iterator (but without hitting the database for each new record)? Then you can skip the worst part of loading all the values in giant_list. Just an idea for Alan and the others to answer. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fixed help with exceptions (Lea Parker)
Thank you, Wayne gave me a suggestion which helped me relook at things and correct the problem I presented. This has added other food for thought for me such as not allowing the program to accept negative inputs for the score however, I will have a play to see if I can fix this first and then ask again if I cannot. Thanks again. Lea -Original Message- From: tutor-bounces+lea-parker=bigpond@python.org [mailto:tutor-bounces+lea-parker=bigpond@python.org] On Behalf Of tutor-requ...@python.org Sent: Saturday, 14 May 2011 12:58 PM To: tutor@python.org Subject: Tutor Digest, Vol 87, Issue 44 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than Re: Contents of Tutor digest... Today's Topics: 1. Re: short url processor (ian douglas) 2. Help with exceptions please (Lea Parker) 3. Re: short url processor (ian douglas) 4. Re: Overriding a method in a class (Terry Carroll) -- Message: 1 Date: Fri, 13 May 2011 17:42:31 -0700 From: ian douglas ian.doug...@iandouglas.com To: Alan Gauld alan.ga...@btinternet.com Cc: tutor@python.org Subject: Re: [Tutor] short url processor Message-ID: 4dcdcff7.5010...@iandouglas.com Content-Type: text/plain; charset=iso-8859-1; Format=flowed On 05/13/2011 05:03 PM, Alan Gauld wrote: How do you know they are going to stdout? Are you sure they aren't going to stderr and stderrr is not mapped to stdout (usually the default). Have you tried redirecting stderr to a file for example? As I say, just some thoughts, Thanks for your thoughts, Alan. I had done some testing with cmdline redirects and forget which is was, I think my debug log was going to stdout and the apache-style log was going to stderr, or the other way around... After a handful of guys in the #python IRC channel very nearly convinced me that all but 3 stdlib libraries are utter worthless crap, and telling me to download and use third-party frameworks just to fix a simple logging issue, I overrode log_request() and log message() as such: class clientThread(BaseHTTPRequestHandler): #[[[ def log_request(code, size): return def log_message(self, format, *args): open(LOGFILE, a).write(%s\n % (format%args)) ... and now the only logging going on is my own, and it's logged to my external file. Overriding log_request means that BaseHTTPServer no longer outputs its apache-style log, and overriding log_message means my other logging.info() and logging.debug() messages go out to my file as expected. -id -- next part -- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20110513/b45aa5f8/attach ment-0001.html -- Message: 2 Date: Sat, 14 May 2011 10:48:51 +1000 From: Lea Parker lea-par...@bigpond.com To: tutor@python.org Subject: [Tutor] Help with exceptions please Message-ID: 001201cc11d0$b1912150$14b363f0$@bigpond.com Content-Type: text/plain; charset=us-ascii Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the 'error that has occurred'. I only want it to do this if someone doesn't enter an number. Could I have some comments on my code for the first program of my assignment if you have some time please. Assignment Question: The Springfork Amateur Golf club has a tournament every weekend. The club president has asked you to write two programs: 1. A program that will read each player's name and golf score as keyboard input and then to save these records in a file named golf.txt. (Each record will have a field name for the player's name and a field for the player's score. 2. A program that reads the records from the golf.txt and displays them. def main(): try: # Get the number of players golf_scores = int(raw_input('How many players playing this weekend? ')) # Open a file to hold player names and scores player_data = open('golf.txt', 'w') # Get the players name and score and write it to the file for count in range(1, golf_scores + 1): # Get the name name and score for player print 'Enter the name and score for player #' + str(count) name = raw_input('Name: ') score = int(raw_input('Score: ')) # Write the data as a record to the file golf.txt player_data.write(name + '\n