From doug.shawhan at gmail.com Thu Jun 1 00:16:28 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 31 May 2006 17:16:28 -0500 Subject: [Tutor] XML Parsing Woes. Message-ID: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com> Having been dragged kicking and screaming into the fussy, fussy world of XML, I find myself in a pickle. I keep getting an error complaining of a missing end-tag: : XML Parse error.
XML Error Text: "; nested exception is: org.xml.sax.SAXParseException: The element type "Description" must be terminated by the matching end-tag "".". Now of course, I have saved my output and found the end-tag to be there. I have stripped out everything I can think of that might cause the parser to puke. The string enclosed by the tags varies from a few characters to a couple of thousand: all fail with the same error. I am very new to XML and find it's jargon fairly impenetrable. Is there a handy python module that can one can use to scan XML output for errors? I know the mistake is probably mine ... or perhaps I have actually run on to a bug in the remote application? :-) (Riiiiight!) Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060531/f07d7a06/attachment.html From kent37 at tds.net Thu Jun 1 02:09:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 May 2006 20:09:52 -0400 Subject: [Tutor] XML Parsing Woes. In-Reply-To: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com> References: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com> Message-ID: <447E3050.7040908@tds.net> doug shawhan wrote: > Having been dragged kicking and screaming into the fussy, fussy world of > XML, I find myself in a pickle. > > I keep getting an error complaining of a missing end-tag: > > : XML Parse error. >
XML Error Text: "; nested exception is: > org.xml.sax.SAXParseException: The element type "Description" > must be terminated by the matching end-tag "
".". > > Now of course, I have saved my output and found the end-tag to be there. > I have stripped out everything I can think of that might cause the > parser to puke. The string enclosed by the tags varies > from a few characters to a couple of thousand: all fail with the same error. > > I am very new to XML and find it's jargon fairly impenetrable. Is there > a handy python module that can one can use to scan XML output for > errors? I know the mistake is probably mine ... or perhaps I have > actually run on to a bug in the remote application? :-) (Riiiiight!) Both Internet Explorer and Firefox do a good job of displaying XML and showing any errors. XML tags are case sensitive, make sure the case matches on the start and end tags. And of course spelling counts ;) XML tags must nest properly, both of these will cause an error, one of them possibly the error you are seeing: textmore text textmore text If you are just starting with Python and XML do yourself a favor and use ElementTreee instead of the stuff in the standard lib. http://effbot.org/zone/element.htm HTH Kent From gnulinuxgeek at rochester.rr.com Thu Jun 1 04:01:38 2006 From: gnulinuxgeek at rochester.rr.com (GNULinuxGeek) Date: Wed, 31 May 2006 22:01:38 -0400 Subject: [Tutor] Another fine mess Message-ID: <447E4A82.70401@rochester.rr.com> All, I posted some time back for another task. Have a new task now. You were all so kind with advice that I thought I might check my thoughts on this. Being an old guy and a newbie to Python is the double-whammy, but here goes: I get a CSV file with ~26 fields and ~7000 records. This data needs to be parsed based on specific field values. So, here is my "draft" set of steps that I think need to be performed. 1. Select the "file" of data 2. Clean the data with "strip" to make sure there is no extraneous whitespace 3. Write the file back to a temp file. 4. On the new file, select records based on the value of some of the fields (like a "sort on" in a spreadsheet. 5. Parse to obtain the matching records 6. Do a little math based on how many records and the data in one field (success vs. fail) 7. Output the results of the math so it can be used in a spreadsheet to make cute graphics. We have a PERL guy in the division, but I am trying to use Python only to get this done. My question is "What is a good way to read and process the lines of the CSV file?" Do I pull them in one line at a time and write them to an output file? Do I read the whole shebang, clean the data and write an output file, then re-open the cleaned file? Thanking you all prematurely, Regards, Ralph From kent37 at tds.net Thu Jun 1 04:22:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 May 2006 22:22:49 -0400 Subject: [Tutor] Another fine mess In-Reply-To: <447E4A82.70401@rochester.rr.com> References: <447E4A82.70401@rochester.rr.com> Message-ID: <447E4F79.1060807@tds.net> GNULinuxGeek wrote: > All, > > I posted some time back for another task. > > Have a new task now. You were all so kind with advice that I thought I > might check my thoughts on this. > > Being an old guy and a newbie to Python is the double-whammy, but here goes: > > I get a CSV file with ~26 fields and ~7000 records. This data needs to > be parsed based on specific field values. Do you know about the csv module? It will take care of all the parsing and turn each line into a list of values. You can filter these as you like and make a list of lists of row values. This can be sorted and otherwise processed. I don't think you will need a temp file, it sounds like you can easily fit your data in memory. Kent > > So, here is my "draft" set of steps that I think need to be performed. > > 1. Select the "file" of data > 2. Clean the data with "strip" to make sure there is no extraneous > whitespace > 3. Write the file back to a temp file. > 4. On the new file, select records based on the value of some of the > fields (like a "sort on" in a spreadsheet. > 5. Parse to obtain the matching records > 6. Do a little math based on how many records and the data in one > field (success vs. fail) > 7. Output the results of the math so it can be used in a spreadsheet > to make cute graphics. > > We have a PERL guy in the division, but I am trying to use Python only > to get this done. My question is > > "What is a good way to read and process the lines of the CSV file?" > Do I pull them in one line at a time and write them to an output file? > Do I read the whole shebang, clean the data and write an output file, > then re-open the cleaned file? > > > Thanking you all prematurely, > > Regards, > > Ralph > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From treed at ultraviolet.org Fri Jun 2 03:00:38 2006 From: treed at ultraviolet.org (Tracy R Reed) Date: Thu, 01 Jun 2006 18:00:38 -0700 Subject: [Tutor] implementing config files Message-ID: <447F8DB6.1040409@ultraviolet.org> Hello all! I am writing some code to implement a bunch of passive checks for the nagios network monitoring system. It runs some checks on the local machine and reports the results back to the nagios server using rpc calls via Perspective Broker from the Twisted module. This code and associated config file is distributed to all of the machines in my infrastructure by cfengine. This part all works quite well. Now I need to refactor my code into a more general and flexible infrastructure and provide a way to configure the services being checked instead of hard coding them (as they currently are). I need to implement a config file which will provide hostnames, the names of checks to run on those hosts, and the options to those checks. These things are sets which are nested inside each other which we can think of like nested objects. I could make a dictionary containing the host names each of which is a dictionary containing the services to be checked etc. But rather than just make dictionaries of dictionaries (which could get confusing) I was wondering if I could make it more robust by somehow defining objects nested inside of other objects in the config file with certain attributes. For example I would like to be able to have a check_tcp object which would have two attributes: hostname and port. If you try to assign it anything else you get an error. If port isn't a number between 0 and 2^16 you get an error. Etc. Basically I don't want errors in the config file to propagate all the way to the client machine on which the code is going to be executed and have wrong arguments passed to the program which we os.popen() and read the results from. Anyone have suggestions on how to proceed? I'm sure the problem of parsing config files into useful objects must be a solved one... I will eventually be posting a link to my code for others to use and critique. It has been a neat project so far. -- Tracy R Reed http://ultraviolet.org A: Because we read from top to bottom, left to right Q: Why should I start my reply below the quoted text From clsdaniel at gmail.com Fri Jun 2 08:36:27 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Thu, 1 Jun 2006 23:36:27 -0700 Subject: [Tutor] implementing config files In-Reply-To: <447F8DB6.1040409@ultraviolet.org> References: <447F8DB6.1040409@ultraviolet.org> Message-ID: <4fae7dfa0606012336k1999a7e7w3c5a290b4d413272@mail.gmail.com> Your could try to use XML files to store configuration files, I already coded something like that, using expat parser and loading the XML contents to objects and attributes, this is a sample code of how works my module: Lets supouse we have this file config.xml with the following contents: MySQL localhost 21 username and in our code: from objxml import * fd = file('config.xml', 'r') p = XMLParser(fd) root = p.Root port = str(root.connection.port) user = str(root.connection.username) All nodes are objects, converting them to strings gets you the content, you can also access the atributes as normal object attributes. This code can be useful for what you want, take a look. Regards Carlos Daniel Ruvalcaba Valenzuela On 6/1/06, Tracy R Reed wrote: > Hello all! > > I am writing some code to implement a bunch of passive checks for the > nagios network monitoring system. It runs some checks on the local > machine and reports the results back to the nagios server using rpc > calls via Perspective Broker from the Twisted module. This code and > associated config file is distributed to all of the machines in my > infrastructure by cfengine. This part all works quite well. Now I need > to refactor my code into a more general and flexible infrastructure and > provide a way to configure the services being checked instead of hard > coding them (as they currently are). > > I need to implement a config file which will provide hostnames, the > names of checks to run on those hosts, and the options to those checks. > These things are sets which are nested inside each other which we can > think of like nested objects. I could make a dictionary containing the > host names each of which is a dictionary containing the services to be > checked etc. > > But rather than just make dictionaries of dictionaries (which could get > confusing) I was wondering if I could make it more robust by somehow > defining objects nested inside of other objects in the config file with > certain attributes. For example I would like to be able to have a > check_tcp object which would have two attributes: hostname and port. If > you try to assign it anything else you get an error. If port isn't a > number between 0 and 2^16 you get an error. Etc. Basically I don't want > errors in the config file to propagate all the way to the client machine > on which the code is going to be executed and have wrong arguments > passed to the program which we os.popen() and read the results from. > > Anyone have suggestions on how to proceed? I'm sure the problem of > parsing config files into useful objects must be a solved one... > > I will eventually be posting a link to my code for others to use and > critique. It has been a neat project so far. > > -- > Tracy R Reed http://ultraviolet.org > A: Because we read from top to bottom, left to right > Q: Why should I start my reply below the quoted text > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: objxml.py Type: text/x-python Size: 1989 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060601/6a4b77db/attachment.py From samrobertsmith at gmail.com Fri Jun 2 11:29:32 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 2 Jun 2006 02:29:32 -0700 Subject: [Tutor] a question about symbol In-Reply-To: <447A466A.8040909@alum.rpi.edu> References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com> <447A466A.8040909@alum.rpi.edu> Message-ID: <1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com> On 5/28/06, Bob Gailer wrote: > > linda.s wrote: > When I test the following code, > I got something like (use 80 as argument): > 80?F=27?C > Why '?' appear? > > # code > import string, sys > > # If no arguments were given, print a helpful message > if len(sys.argv)==1: > print 'Usage: celsius temp1 temp2 ...' > sys.exit(0) > > # Loop over the arguments > for i in sys.argv[1:]: > try: > fahrenheit=float(string.atoi(i)) > except string.atoi_error: > print repr(i), "not a numeric value" > else: > celsius=(fahrenheit-32)*5.0/9.0 > print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5)) > > On my computer I get the desired result. I paste it here 80?F = 27?C and I > see degree symbols. > > What operating system / terminal hardware are you using? > -- > Bob Gailer > 510-978-4454 mac and terminal. From kent37 at tds.net Fri Jun 2 11:51:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Jun 2006 05:51:42 -0400 Subject: [Tutor] a question about symbol In-Reply-To: <1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com> References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com> <447A466A.8040909@alum.rpi.edu> <1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com> Message-ID: <44800A2E.1060208@tds.net> linda.s wrote: > On 5/28/06, Bob Gailer wrote: >> linda.s wrote: >> When I test the following code, >> I got something like (use 80 as argument): >> 80?F=27?C >> Why '?' appear? >> >> # code >> print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5)) >> >> On my computer I get the desired result. I paste it here 80?F = 27?C and I >> see degree symbols. >> >> What operating system / terminal hardware are you using? >> -- >> Bob Gailer >> 510-978-4454 > > mac and terminal. \260 represesents the character with octal value 260, hex B0. In Latin-1 and Unicode this is a degree sign. My guess is that your terminal is set to display UTF-8 characters rather than latin-1; in UTF-8 B0 by itself is an error. It's also possible it is set to MacRoman but in that case I think you would see an infinity sign instead of a question mark. From the Python interpreter prompt, type import sys sys.stdout.encoding to see what encoding your terminal is set to. If it is UTF-8, change the \260 to \xc2\xb0 which is the correct sequence for a degree sign in UTF-8. If it is MacRoman, change the \260 to \xa1 Kent From kent37 at tds.net Fri Jun 2 12:08:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Jun 2006 06:08:50 -0400 Subject: [Tutor] implementing config files In-Reply-To: <447F8DB6.1040409@ultraviolet.org> References: <447F8DB6.1040409@ultraviolet.org> Message-ID: <44800E32.6070009@tds.net> Tracy R Reed wrote: > I need to implement a config file which will provide hostnames, the > names of checks to run on those hosts, and the options to those checks. > These things are sets which are nested inside each other which we can > think of like nested objects. I could make a dictionary containing the > host names each of which is a dictionary containing the services to be > checked etc. > > But rather than just make dictionaries of dictionaries (which could get > confusing) I was wondering if I could make it more robust by somehow > defining objects nested inside of other objects in the config file with > certain attributes. For example I would like to be able to have a > check_tcp object which would have two attributes: hostname and port. If > you try to assign it anything else you get an error. If port isn't a > number between 0 and 2^16 you get an error. One possibility is to make the config file be an actual Python module. Then it can instantiate objects directly. The class constructors can do as much checking as you like. Your config file might look like this: import testdefs host1 = testdefs.Host('192.168.0.53', '80') host2 = testdefs.Host('192.168.0.55', '27') tests = [ testdefs.check_tcp(host1), testdefs.check_http(host1), testdefs.check_tcp(host2), testdefs.check_ftp(host2), ] testdefs.Host is a class which validates and stores the hostname and port, raising an exception if there is a problem. testdefs.check_tcp() etc are classes that validate and remember their init parameters and have an execute() method to actually do the test. So just by importing the above module you validate all the parameters. To run the tests, use something like for test in tests: test.execute() > Basically I don't want > errors in the config file to propagate all the way to the client machine > on which the code is going to be executed and have wrong arguments > passed to the program which we os.popen() and read the results from. You obviously have to import the file to get the error checking, but you could do that on a test machine before you distribute it. Kent From Barry.Carroll at psc.com Fri Jun 2 19:45:17 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 2 Jun 2006 10:45:17 -0700 Subject: [Tutor] implementing config files Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AB@eugsrv400.psc.pscnet.com> Carlos: Where does one find the objxml module? I have looked on python.org and Google and can't find it. Thanks in advance, 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----- > Date: Thu, 1 Jun 2006 23:36:27 -0700 > From: "Carlos Daniel Ruvalcaba Valenzuela" > Subject: Re: [Tutor] implementing config files > To: "Tracy R Reed" > Cc: tutor at python.org > Message-ID: > <4fae7dfa0606012336k1999a7e7w3c5a290b4d413272 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Your could try to use XML files to store configuration files, I > already coded something like that, using expat parser and loading the > XML contents to objects and attributes, this is a sample code of how > works my module: > > Lets supouse we have this file config.xml with the following contents: > > > > MySQL > localhost > 21 > username > > > > > and in our code: > > from objxml import * > > fd = file('config.xml', 'r') > p = XMLParser(fd) > > root = p.Root > port = str(root.connection.port) > user = str(root.connection.username) > > All nodes are objects, converting them to strings gets you the > content, you can also access the atributes as normal object > attributes. > > This code can be useful for what you want, take a look. > > Regards > Carlos Daniel Ruvalcaba Valenzuela > > > On 6/1/06, Tracy R Reed wrote: > > Hello all! > > > > I am writing some code to implement a bunch of passive checks for the > > nagios network monitoring system. <> > > > > -- > > Tracy R Reed http://ultraviolet.org > > A: Because we read from top to bottom, left to right > > Q: Why should I start my reply below the quoted text From Barry.Carroll at psc.com Sat Jun 3 01:23:15 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 2 Jun 2006 16:23:15 -0700 Subject: [Tutor] Trouble with os.path.isfile Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AC@eugsrv400.psc.pscnet.com> Greetings: One of the functions of my test system web server program is to allow the user to view the contents of the image file directories and select files to load onto the hardware. Obviously, a central part of this function is to identify and display the names of directories and files in a specified directory. I haven't been able to find any canned code or cookbook entries that do this, so I'm making one from scratch. Here is the helper function that gets and returns the directory and file names: >>>>>>>>>>>>>>>>>>>>>>>>>> def lstdirsnfiles(tdir): flst = os.listdir(tdir) flst.sort() fnames = [] dnames = ['.', '..'] for name in flst: absfn = os.path.join(tdir, name) if os.path.isdir(absfn): dnames.append(name) elif os.path.isfile(absfn): fnames.append(name) return dnames, fnames >>>>>>>>>>>>>>>>>>>>>>>>>> The root of the image file directory tree is "/home/iip/images". When lstdirsnfiles is run with tdir set appropriately, the lists returned contain no additional information: dnames = ['.', '..'] and fnames = []. I added some tracing statements to see what was happening inside the function: >>>>>>>>>>>>>>>>>>>>>>>>>> def lstdirsnfiles(tdir): global DEBUG, dbgfname DEBUG = True flst = os.listdir(tdir) flst.sort() fnames = [] dnames = ['.', '..'] if DEBUG: dbgf = open(dbgfname,mode="a") dbgf.write("\n"+str (time.localtime())+"\n") dbgf.write("Entering lstdirsnfiles\n") dbgf.write("The directory = %s\n" % tdir) dbgf.write("The file list = %s\n" % flst) for name in flst: absfn = os.path.join(tdir, name) if DEBUG: dbgf.write("File path = %s, isfile = %s\n" % (absfn, os.path.isfile(absfn))) if os.path.isdir(absfn): dnames.append(name) elif os.path.isfile(absfn): fnames.append(name) if DEBUG: dbgf.write("dnames = %s\n" % dnames) dbgf.write("fnames = %s\n" % fnames) dbgf.close() DEBUG = False return dnames, fnames >>>>>>>>>>>>>>>>>>>>>>>>>> The log vile received the following: >>>>>>>>>>>>>>>>>>>>>>>>>> (2006, 6, 2, 15, 23, 4, 4, 153, 1) Entering lstdirsnfiles The directory = /home/iip/images The file list = ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', 'test5.bmp', 'test6.bmp'] File path = /home/iip/images/test1.bmp, isfile = False File path = /home/iip/images/test2.bmp, isfile = False File path = /home/iip/images/test3.bmp, isfile = False File path = /home/iip/images/test4.bmp, isfile = False File path = /home/iip/images/test5.bmp, isfile = False File path = /home/iip/images/test6.bmp, isfile = False dnames = ['.', '..'] fnames = [] >>>>>>>>>>>>>>>>>>>>>>>>>> So there are entries in the directory, but the function doesn't recognize them as files. Finally, I opened the interpreter and tried doing this, as nearly as possible, interactively. I got this: >>>>>>>>>>>>>>>>>>>>>>>>>> >>> import os >>> tdir = '/home/iip/images' >>> os.listdir(tdir) ['test4.bmp', 'test3.bmp', 'test2.bmp', 'test1.bmp', 'test5.bmp', 'test6.bmp'] >>> flst = os.listdir(tdir) >>> flst.sort() >>> flst ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', 'test5.bmp', 'test6.bmp'] >>> for name in flst: ... absfn = os.path.join(tdir,name) ... print absfn, "is", ... if not os.path.isfile(absfn): ... print "NOT", ... print "a file" ... /home/iip/images/test1.bmp is a file /home/iip/images/test2.bmp is a file /home/iip/images/test3.bmp is a file /home/iip/images/test4.bmp is a file /home/iip/images/test5.bmp is a file /home/iip/images/test6.bmp is a file >>>>>>>>>>>>>>>>>>>>>>>>>>>>> As you can see, the interpreter correctly identifies the strings in the list as names of files, but my function does not. I can't see anything wrong with the logic in the function. Can any or you see the problem I'm missing? As always, 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060602/f2ba27b8/attachment-0001.htm From clsdaniel at gmail.com Sat Jun 3 08:28:21 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Fri, 2 Jun 2006 23:28:21 -0700 Subject: [Tutor] Trouble with os.path.isfile In-Reply-To: <4fae7dfa0606022310g66f902b1j5b038ac940edff2c@mail.gmail.com> References: <2BBAEE949D384D40A2B851287ADB6A432C36AC@eugsrv400.psc.pscnet.com> <4fae7dfa0606022310g66f902b1j5b038ac940edff2c@mail.gmail.com> Message-ID: <4fae7dfa0606022328k57c6a5cewee68fa1a33537e6b@mail.gmail.com> From: Carlos Daniel Ruvalcaba Valenzuela Date: Jun 2, 2006 11:10 PM Subject: Re: [Tutor] Trouble with os.path.isfile To: "Carroll, Barry" Here is the problem IMO: I did some modifications to your code (very minimal on ifs) and it worked: import os def lstdirsnfiles(tdir): flst = os.listdir(tdir) flst.sort() fnames = [] dnames = ['.', '..'] for name in flst: absfn = os.path.join(tdir, name) if os.path.isdir(absfn): dnames.append(name) if os.path.isfile(absfn): fnames.append(name) return (dnames, fnames) (dirs, files) = lstdirsnfiles('/home/clsdaniel') It returns correctly all directories and files. Regards Carlos Daniel Ruvalcaba Valenzuela On 6/2/06, Carroll, Barry wrote: > > > > > Greetings: > > > > One of the functions of my test system web server program is to allow the > user to view the contents of the image file directories and select files to > load onto the hardware. Obviously, a central part of this function is to > identify and display the names of directories and files in a specified > directory. I haven't been able to find any canned code or cookbook entries > that do this, so I'm making one from scratch. Here is the helper function > that gets and returns the directory and file names: > > > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > def lstdirsnfiles(tdir): > > flst = os.listdir(tdir) > > flst.sort() > > fnames = [] > > dnames = ['.', '..'] > > for name in flst: > > absfn = os.path.join(tdir, name) > > if os.path.isdir(absfn): > > dnames.append(name) > > elif os.path.isfile(absfn): > > fnames.append(name) > > return dnames, fnames > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > > > The root of the image file directory tree is "/home/iip/images". When > lstdirsnfiles is run with tdir set appropriately, the lists returned > contain no additional information: dnames = ['.', '..'] and fnames = []. I > added some tracing statements to see what was happening inside the > function: > > > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > def lstdirsnfiles(tdir): > > global DEBUG, dbgfname > > DEBUG = True > > > > flst = os.listdir(tdir) > > flst.sort() > > fnames = [] > > dnames = ['.', '..'] > > > > if DEBUG: > > dbgf = open(dbgfname,mode="a") > > dbgf.write("\n"+str (time.localtime())+"\n") > > dbgf.write("Entering lstdirsnfiles\n") > > dbgf.write("The directory = %s\n" % tdir) > > dbgf.write("The file list = %s\n" % flst) > > > > for name in flst: > > absfn = os.path.join(tdir, name) > > > > if DEBUG: > > dbgf.write("File path = %s, isfile = %s\n" % > > (absfn, os.path.isfile(absfn))) > > > > if os.path.isdir(absfn): > > dnames.append(name) > > elif os.path.isfile(absfn): > > fnames.append(name) > > > > if DEBUG: > > dbgf.write("dnames = %s\n" % dnames) > > dbgf.write("fnames = %s\n" % fnames) > > dbgf.close() > > DEBUG = False > > > > return dnames, fnames > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > > > The log vile received the following: > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > (2006, 6, 2, 15, 23, 4, 4, 153, 1) > > Entering lstdirsnfiles > > The directory = /home/iip/images > > The file list = ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', > 'test5.bmp', 'test6.bmp'] > > File path = /home/iip/images/test1.bmp, isfile = False > > File path = /home/iip/images/test2.bmp, isfile = False > > File path = /home/iip/images/test3.bmp, isfile = False > > File path = /home/iip/images/test4.bmp, isfile = False > > File path = /home/iip/images/test5.bmp, isfile = False > > File path = /home/iip/images/test6.bmp, isfile = False > > dnames = ['.', '..'] > > fnames = [] > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > > > So there are entries in the directory, but the function doesn't recognize > them as files. > > > > Finally, I opened the interpreter and tried doing this, as nearly as > possible, interactively. I got this: > > > > >>>>>>>>>>>>>>>>>>>>>>>>>> > > >>> import os > > >>> tdir = '/home/iip/images' > > >>> os.listdir(tdir) > > ['test4.bmp', 'test3.bmp', 'test2.bmp', 'test1.bmp', 'test5.bmp', > 'test6.bmp'] > > >>> flst = os.listdir(tdir) > > >>> flst.sort() > > >>> flst > > ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', 'test5.bmp', > 'test6.bmp'] > > >>> for name in flst: > > ... absfn = os.path.join(tdir,name) > > ... print absfn, "is", > > ... if not os.path.isfile(absfn): > > ... print "NOT", > > ... print "a file" > > ... > > /home/iip/images/test1.bmp is a file > > /home/iip/images/test2.bmp is a file > > /home/iip/images/test3.bmp is a file > > /home/iip/images/test4.bmp is a file > > /home/iip/images/test5.bmp is a file > > /home/iip/images/test6.bmp is a file > > >>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > > > As you can see, the interpreter correctly identifies the strings in the list > as names of files, but my function does not. I can't see anything wrong > with the logic in the function. Can any or you see the problem I'm missing? > > > > As always, 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 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From oztriking at hotmail.com Sun Jun 4 15:33:48 2006 From: oztriking at hotmail.com (John Connors) Date: Sun, 04 Jun 2006 23:33:48 +1000 Subject: [Tutor] Not Really Questions Message-ID: G'day, While the list is kind of slow I thought I'd post a few thoughts on a couple of things in Python that bug me. They're not really questions but maybe someone can help me understand. The first one is lists... I can't for the life of me understand why a list starts at zero. In everything else in life other than programming the 1st item in a list is always 1. The next thing I don't understand is why the last number in a range is not used... For a in range(1,6): print a, 1 2 3 4 5 Once again it defies the logic of everything else we are taught in life. The 3rd whinge is object oriented programming. I think I understand the principle behind OOP but in practise, to me, it just makes programs jumbled, unreadable and bloated. Just about every summary I have read on Python says it is designed to have a simple syntax and is easy to learn. As a beginner I can look at Python code and have a very good idea of what is happening and why unless it's written in OOP style in which case I have no idea. John _________________________________________________________________ Read, write and reply to Hotmail on your mobile. Find out more. http://mobilecentral.ninemsn.com.au/mcmobileHotmail/home.aspx From dustin at ywlcs.org Sun Jun 4 17:15:43 2006 From: dustin at ywlcs.org (Dustin J.Mitchell) Date: Sun, 4 Jun 2006 10:15:43 -0500 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <130596e7576f948efc8bc8165788edc2@ywlcs.org> Let me see if I can tackle these.. On Jun 4, 2006, at 8:33 AM, John Connors wrote: > The first one is lists... I can't for the life of me understand why a > list > starts at zero. In everything else in life other than programming the > 1st > item in a list is always 1. > > The next thing I don't understand is why the last number in a range is > not > used... > Once again it defies the logic of everything else we are taught in > life. This is basically a historical precedent. At one point, long long ago, lists were implemented as a sequence of bytes in memory. The "list" was really the address of the first byte. So the index meant "look this many bytes after the first byte". The first byte was zero bytes after the first byte, so its index was zero. The range thing is similar -- think of the arguments to range being (first index to include, first index to exclude). There have been a few programming languages that have changed this (Pascal comes to mind), but none have fared well. You'll get used to it :) > The 3rd whinge is object oriented programming. I think I understand the > principle behind OOP but in practise, to me, it just makes programs > jumbled, > unreadable and bloated. Just about every summary I have read on Python > says > it is designed to have a simple syntax and is easy to learn. As a > beginner I > can look at Python code and have a very good idea of what is happening > and > why unless it's written in OOP style in which case I have no idea. I will be one of the first to say that OOP is grossly overused in commercial programming -- at some point, middle-management learned that "OOP is good", and demanded that programmers start using it everywhere. Sometimes it's the right tool for the job, and sometimes it isn't. I won't get into the details of that distinction, except to say that simpler tasks tend to not require OOP, while more complex tasks often do. Thus, the non-OOP programs you're looking at are probably performing simpler tasks than the OOP programs. Again, you'll get used to it. One of the nice things about Python is that it lets you write both OOP and non-OOP programs, so you've got a lot of room to experiment and learn OOP style. Java, on the other hand, requires OOP for everything, making it much harder to learn when OOP is and is not appropriate. Dustin -- # Dustin J. Mitchell # dustin at ywlcs.org/djmitche at alumni.uchicago.edu From bgailer at alum.rpi.edu Sun Jun 4 19:30:24 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 04 Jun 2006 10:30:24 -0700 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <448318B0.6080305@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060604/6900108c/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: show Type: image/gif Size: 43 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060604/6900108c/attachment.gif From kent37 at tds.net Sun Jun 4 20:05:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 04 Jun 2006 14:05:08 -0400 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <448320D4.7080201@tds.net> John Connors wrote: > G'day, > > While the list is kind of slow I thought I'd post a few thoughts on a couple > of things in Python that bug me. They're not really questions but maybe > someone can help me understand. Maybe I can give you some not-really answers ;) > > The first one is lists... I can't for the life of me understand why a list > starts at zero. In everything else in life other than programming the 1st > item in a list is always 1. Many programming languages start indexes at zero. It makes sense if you think of a list being stored as sequential values in memory, and the index as the offset from the start of the list. (This is in fact how arrays are often implemented.) > > The next thing I don't understand is why the last number in a range is not > used... > > For a in range(1,6): > print a, > > 1 2 3 4 5 > > Once again it defies the logic of everything else we are taught in life. This actually prevents many types of errors. Alex Martelli has a good explanation here (also see his other posts in the same thread): http://groups.google.com/group/comp.lang.python/msg/579b53de640190cd > > The 3rd whinge is object oriented programming. I think I understand the > principle behind OOP but in practise, to me, it just makes programs jumbled, > unreadable and bloated. Just about every summary I have read on Python says > it is designed to have a simple syntax and is easy to learn. As a beginner I > can look at Python code and have a very good idea of what is happening and > why unless it's written in OOP style in which case I have no idea. OOP does take some getting used to, it is a different way of thinking about the structure of a program. Done badly, it is a good way to make a mess. Done well, it is a tool for creating a highly modular program where the responsibilities of each piece are well defined. Kent From hugonz-lists at h-lab.net Sun Jun 4 22:54:36 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 04 Jun 2006 15:54:36 -0500 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <4483488C.1040506@h-lab.net> John Connors wrote: > > The first one is lists... I can't for the life of me understand why a list > starts at zero. In everything else in life other than programming the 1st > item in a list is always 1. Hi, Exactly, everything else other than programming. Zero indexed arrays are the norm in everything but moronic old VB. I guess it's just a defacto standard now. > > The next thing I don't understand is why the last number in a range is not > used... > > For a in range(1,6): > print a, > > 1 2 3 4 5 > This relates to the previous issue. This comes from the fact that range(3) = [0, 1, 2] This is extremely useful for iterating indices, and I can suppose that when range() was first extended, it had to remain consistent. > The 3rd whinge is object oriented programming. I think I understand the > principle behind OOP but in practise, to me, it just makes programs jumbled, > unreadable and bloated. Just about every summary I have read on Python says > it is designed to have a simple syntax and is easy to learn. As a beginner I > can look at Python code and have a very good idea of what is happening and > why unless it's written in OOP style in which case I have no idea. > OOP is a rare beast to me: it makes suitable problems very very easy (think about GUI programming without OOP) and unsuitable problems extremely convoluted. I guess it's just the fact that it is a paradigm and not just a programming technique. Fortunately, unless other languages which *force* you to use OOP (think Java), Python allows you to use at least 3 different paradigms (OOP, functional(like Lisp et al) and structured(like Pascal and C)) Just my 2 cents, Hugo From alan.gauld at btinternet.com Mon Jun 5 01:01:08 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 Jun 2006 00:01:08 +0100 Subject: [Tutor] Not Really Questions References: Message-ID: Hi John, I'll pitch in although I've read most of the other answers too so I'll be adding to them mostly. > The first one is lists... I can't for the life of me understand why > a list > starts at zero. In everything else in life other than programming Not quite. In math zero is usually the starting point, its generally viewed as a positive number(although it is obviously neither positive or negative) and proofs and definitions usually start by consideriung zero - or at least defining whether zero is in or out of scope. This math point is important because programming was originally a branch of math and it was mathematicians who laid the ground rules. But, it was by no means cast in stone until implementations of list indexing started to be based on the start addressof the list in memory. In C this is even explicitly visible. We can declare anm array of numbers like this int anArray[] = {1,3,5}; and then a pointer to an integer like this int* intPtr; We can now set intPtr to point at the array: intPtr = anArray; If we printed thevcontents of intPtr we would get 1 Now increment the pointer: intPtr == 1 Now id we print iojntPtr we will get 5, the next value in the array. We can also get the 3rd element by using intPtr = anArray + 2 printf("%d",*intPtr) // print the content of intPtr and of course we get the same result with printf("%d",intArray[2]) // print the 3rd element of intArray So in C you can see that indexing is really a very thin wrapper around memory aroithmetic. > The next thing I don't understand is why the last number in a range > is not > used... > > For a in range(1,6): > print a, > > 1 2 3 4 5 This is to make range match with the indexing. We can do stuff like for index in range(len(alist)): print alist[index] If the two did not match you would do something like: for index in range(len(alist)): print alist[index-1] If you are going to be weird at least be consistently weird! Finally some languages allow us to use "normal"! indexing Pascal for example allows: program test(output) var anArray : array [1..5] of integer; n : integer; begin for n := 1 to 5 do begin anArray[n] = 2 * n end; writeln anArray[1]; writeln anArray[3]; writeln anArray[5] end. Which populates an array with indices from 1 through 5 > The 3rd whinge is object oriented programming. I think I understand > the > principle behind OOP but in practise, to me, it just makes programs > jumbled, Further to the previous comments, OOP has several purposes and is used to achieve difgfferent things. But fundamentally OOP is used to control the complexity of large programs. If you are writing program of less than 100 lines you almost never need to use OOP (You may choose to for some of the other reasons below, but its not needed). Between 100 and 1000 lines you are more likely to find OOP coming in handy. Between 1000 lines and 10,000 lines you will almost certainly find at least some of your code that benefits. Beyond 10,000 lines (and I'm, talking Python code here) OOP will be almost indispensible in helping you keep the structure of the code clear in your mind (and in your code too!) There are other ways to control complexity and very large programs have been written without it. It fact its fairly safe to say that all the biggest programs are OOP free being written in COBOL. But COBOL has its own mechanisms for managing complexity and there is now an object oriented COBOL available to combine the best of both worlds. [On a personal note the two biggest programs I've worked on have both been COBOL - 10 million and 6 million lines respectively. The 3rd biggest was C++ at 3.5 million lines. The COBOL was easier... But I've also worked on a 500K lines C program(with no OOP) and that was the hardest of all of them! So OOP works but its not the holy grail that some pundits would have you believe] Other reasons to use OOP are that it definitely makes reuse easier both within a project and between projects. It also can reduce the code size on some types of project. It definitely makes code more flexible by allowing objects to be swapped in and out if they have the same "interface" or protocol. Also some people find objects more easy to think about. It seems more logical to move the table than to change the table's x and y coordinates... However folks brought up with a math or science background, or who have already programmed find it very hard to make the mental switch to seeing the world as communicating objects rather than data being maniupulated by functions... And thats way more than I set out to write!!! HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From yi at yiqiang.net Mon Jun 5 03:43:25 2006 From: yi at yiqiang.net (Yi Qiang) Date: Sun, 04 Jun 2006 18:43:25 -0700 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <44838C3D.9010907@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alan Gauld wrote, On 06/04/2006 04:01 PM: > Hi John, > > I'll pitch in although I've read most of the other answers > too so I'll be adding to them mostly. > >> The first one is lists... I can't for the life of me understand why >> a list >> starts at zero. In everything else in life other than programming > > Not quite. In math zero is usually the starting point, its generally > viewed as a positive number(although it is obviously neither positive > or negative) and proofs and definitions usually start by consideriung > zero - or at least defining whether zero is in or out of scope. That is just not true. A number is positive if and only if it is strictly greater than 0 by definition. Zero is not considered positive in mathematics. In fact, the set of positive integers, Z+, is the set {1,2,3,....}. - -- Yi Qiang (yi at yiqiang.net) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEg4w9tXlIMrUVVksRAn9RAJ9KAuaKvNvkXFwPNSn0+tMCKwOWMQCdHx6j L8pOPQRJMv8GcnypMblCIgI= =dtF3 -----END PGP SIGNATURE----- From tim at johnsons-web.com Mon Jun 5 03:21:04 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 4 Jun 2006 17:21:04 -0800 Subject: [Tutor] Not Really Questions In-Reply-To: <4483488C.1040506@h-lab.net> References: <4483488C.1040506@h-lab.net> Message-ID: <20060605012104.GC31550@johnsons-web.com> * Hugo Gonz?lez Monteverde [060604 13:04]: > > Exactly, everything else other than programming. Zero indexed arrays are > the norm in everything but moronic old VB. I guess it's just a defacto > standard now. I make equal parts of my income from writing python code and from writing code in rebol. Rebol starts indexes with 1. It also uses the 'first function (like lisp). This has prompted me to write and use the following: def first(v): return v[0] (-: Regardless of where you start counting, there you are! > OOP is a rare beast to me: it makes suitable problems very very easy > (think about GUI programming without OOP) and unsuitable problems > extremely convoluted. I guess it's just the fact that it is a paradigm > and not just a programming technique. comparing rebol and python - rebol is more productive, line for line, from my experience. But because of python's OOP engineering it, it scales better, enabling more maintainable code in larger projects. Consequently, I use python for big projects, rebol for small. """ The right tool for the right job """ tim -- Tim Johnson http://www.alaska-internet-solutions.com From rondosxx at yahoo.com Mon Jun 5 04:02:48 2006 From: rondosxx at yahoo.com (ron) Date: Sun, 4 Jun 2006 19:02:48 -0700 (PDT) Subject: [Tutor] Not Really Questions Message-ID: <20060605020248.76721.qmail@web52508.mail.yahoo.com> I think we should say that the number set is zero through nine (not 1-10 as we were taught in school), making "zero" the first number in the set; thus the offset by one. Of course zero is not a number, but a placeholder for a number. Thankfully this concept was invented a few centuries ago in India and brought to the West by Arab scholars. Unfortunately I think it's still not widely understood. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From wescpy at gmail.com Mon Jun 5 07:29:12 2006 From: wescpy at gmail.com (w chun) Date: Sun, 4 Jun 2006 22:29:12 -0700 Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: <78b3a9580606042229v232c2380xf43ef9fa0f9594e7@mail.gmail.com> hi john, everyone else has posted great replies to your inquiries, so i'll keep mine brief. > While the list is kind of slow I thought I'd post a few thoughts on a couple > of things in Python that bug me. my 1st comment is that you are not talking about Python alone. everything you state pertains to most other programming languages. > The first one is lists... I can't for the life of me understand why a list > starts at zero. In everything else in life other than programming the 1st > item in a list is always 1. sequences, arrays, etc., in most other languages do start at zero, and have a strong tie to that addressing stuff that's already been mentioned. this is just a fact of programming. > The next thing I don't understand is why the last number in a range is not > used... > > For a in range(1,6): > print a, > > 1 2 3 4 5 > > Once again it defies the logic of everything else we are taught in life. this is partially due to your 1st issue, that things start at zero. a sequence of length 5, for example, or range(5) means: 0, 1, 2, 3, 4. even tho the counting is up to 4, you will see that this is a collection of five items. this feature of "i up-to-but-not-including j" also mirrors other languages, say counting in C for example: for (i = 0; i < 5; i++); > The 3rd whinge is object oriented programming. like all programming tools, one must investigate whether it is the right tool for the job. if it's a simple one-off script, then probly not; but if it is a huge framework where you want to most code reuse, least amount of code to maintain, minimization of the number of bugs, and being able to lump functionality/logic with data, OOP is the way to go. a simple example would be shapes and functions like finding an area. like objects can share the same functions (called "methods"), i.e. square.area(), rectangle.area(), whereas for other objects that aren't similar, i wouldn't want the wrong functionality but i *would* want to use the same name, circle.area(). the good news, as others have mentioned, is that Python is flexible, letting you build the application as you see fit, and not locked to any specific paradigm except perhaps KISS. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From yi at yiqiang.net Mon Jun 5 08:03:32 2006 From: yi at yiqiang.net (Yi Qiang) Date: Sun, 04 Jun 2006 23:03:32 -0700 Subject: [Tutor] problem with unpickling an object Message-ID: <4483C934.40003@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi list, I am pickling a dictionary that has as one of it's values an object I create on the fly. When I try to unpickle that object, cPickle attempts to recreate that object but of course that module is not present anymore. How can I just make it skip over that particular key and just set the value to None? Thanks, - -- Yi Qiang (yi at yiqiang.net) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEg8k0tXlIMrUVVksRAt2tAJ4hq/3KmDo6BbS3p3AwhKf4Ga52DQCfXFtx GERJqs3IcLXuKaRcq/zuRUE= =SEZ6 -----END PGP SIGNATURE----- From alan.gauld at freenet.co.uk Mon Jun 5 08:46:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 5 Jun 2006 07:46:58 +0100 Subject: [Tutor] Not Really Questions References: <44838C3D.9010907@yiqiang.net> Message-ID: <001401c6886b$d7aac8d0$0a01a8c0@XPpro> >> Not quite. In math zero is usually the starting point, its >> generally >> viewed as a positive number(although it is obviously neither >> positive >> or negative) > That is just not true. A number is positive if and only if it is > strictly greater than 0 by definition. Zero is not considered > positive > in mathematics. In fact, the set of positive integers, Z+, is the > set > {1,2,3,....}. Quite so (as I pointed out in parens) but I'll retract the comment about it being viewed as positive and say it is viewed as being not negative (which is of course true!). Thus zero is frequently treated as the first significant number when considering sequences and ranges of numbers (Z+ not withstanding! :-) The introduction of zero into math was a huge step and as a result a lot of classical math does not consider it but in practical day to day math and science zero is treated as the first number. That's all I was really trying to say... Alan G. From kent37 at tds.net Mon Jun 5 12:12:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Jun 2006 06:12:24 -0400 Subject: [Tutor] problem with unpickling an object In-Reply-To: <4483C934.40003@yiqiang.net> References: <4483C934.40003@yiqiang.net> Message-ID: <44840388.2090803@tds.net> From a quick read of the docs, it looks like you should set the unpickler's find_global attribute to a function you define. This function can first attempt to load the desired class (see pickle.find_class() for an example). If the load fails, then return a placeholder class that you define. This won't give exactly the result you ask for, instead of None in the dictionary you will have instances of the placeholder. You could then post-process the dict to change the placeholder instances to None if you like. Kent Yi Qiang wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi list, > I am pickling a dictionary that has as one of it's values an object I > create on the fly. When I try to unpickle that object, cPickle attempts > to recreate that object but of course that module is not present > anymore. How can I just make it skip over that particular key and just > set the value to None? > > Thanks, > - -- > Yi Qiang (yi at yiqiang.net) > Web: http://www.yiqiang.net > Tel: (206) 661-8469 > PGP: 0xB515564B > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2.2 (GNU/Linux) > > iD8DBQFEg8k0tXlIMrUVVksRAt2tAJ4hq/3KmDo6BbS3p3AwhKf4Ga52DQCfXFtx > GERJqs3IcLXuKaRcq/zuRUE= > =SEZ6 > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From yi at yiqiang.net Mon Jun 5 16:14:12 2006 From: yi at yiqiang.net (Yi Qiang) Date: Mon, 05 Jun 2006 07:14:12 -0700 Subject: [Tutor] problem with unpickling an object In-Reply-To: <44840388.2090803@tds.net> References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net> Message-ID: <44843C34.2050502@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kent Johnson wrote, On 06/05/2006 03:12 AM: > From a quick read of the docs, it looks like you should set the > unpickler's find_global attribute to a function you define. This > function can first attempt to load the desired class (see > pickle.find_class() for an example). If the load fails, then return a > placeholder class that you define. > > This won't give exactly the result you ask for, instead of None in the > dictionary you will have instances of the placeholder. You could then > post-process the dict to change the placeholder instances to None if you > like. Interesting, so if I used this method I won't be able to use cPickle anymore. The documentation just says that cPickle is "faster", but can anyone quantify how much speed I am losing if I move to the regular pickle module? - -- Yi Qiang (yi at yiqiang.net) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEhDw0tXlIMrUVVksRApzBAJ427uRcMuQk6TgqGfWGZu8GjlZWBgCbBTBP 83oVZ9NNswfGrzk58Bat57k= =J5gs -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Mon Jun 5 16:15:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 5 Jun 2006 07:15:31 -0700 (PDT) Subject: [Tutor] Not Really Questions In-Reply-To: References: Message-ID: On Sun, 4 Jun 2006, John Connors wrote: > The first one is lists... I can't for the life of me understand why a > list starts at zero. In everything else in life other than programming > the 1st item in a list is always 1. Edsger Dijkstra wrote a technical note on why zero is a more natural starting point: http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Also, programming is one of those fields where appreciating the null case can be advantageous. From kent37 at tds.net Mon Jun 5 16:25:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Jun 2006 10:25:36 -0400 Subject: [Tutor] problem with unpickling an object In-Reply-To: <44843C34.2050502@yiqiang.net> References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net> <44843C34.2050502@yiqiang.net> Message-ID: <44843EE0.2080007@tds.net> Yi Qiang wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Kent Johnson wrote, On 06/05/2006 03:12 AM: >> From a quick read of the docs, it looks like you should set the >> unpickler's find_global attribute to a function you define. This >> function can first attempt to load the desired class (see >> pickle.find_class() for an example). If the load fails, then return a >> placeholder class that you define. >> >> This won't give exactly the result you ask for, instead of None in the >> dictionary you will have instances of the placeholder. You could then >> post-process the dict to change the placeholder instances to None if you >> like. > > Interesting, so if I used this method I won't be able to use cPickle > anymore. The documentation just says that cPickle is "faster", but can > anyone quantify how much speed I am losing if I move to the regular > pickle module? No, the find_global() hook is for cPickle. See the next-to-last paragraph on this page: http://docs.python.org/lib/pickle-sub.html As far as speed, the best thing is just to try it with your data. pickle and cPickle have the same API so it should be easy to switch your code to use pickle and run a timing test. Kent From Barry.Carroll at psc.com Mon Jun 5 21:16:18 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 5 Jun 2006 12:16:18 -0700 Subject: [Tutor] Trouble with os.path.isfile Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AF@eugsrv400.psc.pscnet.com> Carlos: Thank you for your response. It turns out that Python and os.path.isfile() are working as expected. A permissions conflict on my Linux-based system caused the isfile function to return false for all the entries in the directory. The web server is running as user apache. The files were owned by user iip. I don't have all the details worked out yet, but it appears that adding apache to iip's group list resolves the conflict. It would be nice if the library entries for os.path.is* (where * is one of {file, dir, link, mount) mentioned this restriction. 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----- > Date: Fri, 2 Jun 2006 23:28:21 -0700 > From: "Carlos Daniel Ruvalcaba Valenzuela" > Subject: Re: [Tutor] Trouble with os.path.isfile > To: tutor at python.org > Message-ID: > <4fae7dfa0606022328k57c6a5cewee68fa1a33537e6b at mail.gmail.com> > Content-Type: text/plain; charset=WINDOWS-1252; format=flowed > > From: Carlos Daniel Ruvalcaba Valenzuela > Date: Jun 2, 2006 11:10 PM > Subject: Re: [Tutor] Trouble with os.path.isfile > To: "Carroll, Barry" > > > Here is the problem IMO: > > I did some modifications to your code (very minimal on ifs) and it worked: > > import os > > def lstdirsnfiles(tdir): > flst = os.listdir(tdir) > flst.sort() > > fnames = [] > dnames = ['.', '..'] > > for name in flst: > absfn = os.path.join(tdir, name) > > if os.path.isdir(absfn): > dnames.append(name) > > if os.path.isfile(absfn): > fnames.append(name) > return (dnames, fnames) > > (dirs, files) = lstdirsnfiles('/home/clsdaniel') > > It returns correctly all directories and files. > > Regards > Carlos Daniel Ruvalcaba Valenzuela <> From Barry.Carroll at psc.com Mon Jun 5 22:11:14 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 5 Jun 2006 13:11:14 -0700 Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B1@eugsrv400.psc.pscnet.com> Greetings: > -----Original Message----- > Date: Sun, 04 Jun 2006 18:43:25 -0700 > From: Yi Qiang > Subject: Re: [Tutor] Not Really Questions > To: tutor at python.org > Message-ID: <44838C3D.9010907 at yiqiang.net> > Content-Type: text/plain; charset=ISO-8859-1 > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Alan Gauld wrote, On 06/04/2006 04:01 PM: > > Hi John, > > > > I'll pitch in although I've read most of the other answers > > too so I'll be adding to them mostly. > > > >> The first one is lists... I can't for the life of me understand why > >> a list > >> starts at zero. In everything else in life other than programming > > > > Not quite. In math zero is usually the starting point, its generally > > viewed as a positive number(although it is obviously neither positive > > or negative) and proofs and definitions usually start by consideriung > > zero - or at least defining whether zero is in or out of scope. > That is just not true. A number is positive if and only if it is > strictly greater than 0 by definition. Zero is not considered positive > in mathematics. In fact, the set of positive integers, Z+, is the set > {1,2,3,....}. > - -- > Yi Qiang (yi at yiqiang.net) > Web: http://www.yiqiang.net > Tel: (206) 661-8469 > PGP: 0xB515564B [Somewhat off topic] Strictly speaking, Yi Qiang is correct, of course. The set Z+ (which BTW is identical with the set of natural numbers, N), does not include 0. 0 is neither positive nor negative. However, the set of non-negative numbers does include 0, as does the set of non-positive numbers. The former set, {0, 1, 2, ...}, is the one associated with lists, arrays, etc, as it is possible to have 0 or more elements in a list, while it is not possible to have less than 0 elements. [Back on topic] Like John, I find the half-open range concept to be 'unnatural'. When waiting for checkout at the market, I don't think of myself as being 'zeroth' in line; I'm either 'first' or 'next' in line. For me, it's a matter of context. When programming, it helps remind myself that I'm not in the 'natural' universe where 'natural numbers' are the rule. I'm in the computer's mathematical universe, where 'zeroth' in line is perfectly natural. =8^) HTH Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From yi at yiqiang.net Mon Jun 5 22:22:46 2006 From: yi at yiqiang.net (Yi Qiang) Date: Mon, 05 Jun 2006 13:22:46 -0700 Subject: [Tutor] problem with unpickling an object In-Reply-To: <44843EE0.2080007@tds.net> References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net> <44843C34.2050502@yiqiang.net> <44843EE0.2080007@tds.net> Message-ID: <44849296.3060307@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kent Johnson wrote, On 06/05/2006 07:25 AM: > No, the find_global() hook is for cPickle. See the next-to-last > paragraph on this page: > http://docs.python.org/lib/pickle-sub.html Sorry, I don't follow. How does one get access to the find_global attribute for cPickle? I created an cPickle.Unpickler object, and the only attributes that I have access to are .load and .noload. What am I missing here? - -- Yi Qiang (yi at yiqiang.net) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEhJKWtXlIMrUVVksRAhCYAJ9NFNc601e0QdqUAWOFi1yUrKSvNQCdE/eE NJGCtVG6kYx89bsuLnCmIeo= =CRYn -----END PGP SIGNATURE----- From rondosxx at yahoo.com Mon Jun 5 22:48:45 2006 From: rondosxx at yahoo.com (ron) Date: Mon, 5 Jun 2006 13:48:45 -0700 (PDT) Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions) Message-ID: <20060605204845.43600.qmail@web52506.mail.yahoo.com> It seems that the confusion is exacerbated by the fact that we're using the theoretical number set to reference the common one. I suppose this is a carry-over from binary, since in binary if you don't have a zero, you also won't have a bunch of other numbers like 2, 4 and so forth. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dustin at ywlcs.org Mon Jun 5 23:14:51 2006 From: dustin at ywlcs.org (Dustin Mitchell) Date: Mon, 5 Jun 2006 16:14:51 -0500 Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions) In-Reply-To: <20060605204845.43600.qmail@web52506.mail.yahoo.com> References: <20060605204845.43600.qmail@web52506.mail.yahoo.com> Message-ID: <9738732e349662598606b194c3d663c7@ywlcs.org> Wait, all of this "not really a number" and "carry-over from binary" stuff deals with the *numeral* zero, which is neither here nor there. We could use a picture of a bunny-rabbit instead of the numeral zero, making this year 26. The discussion here is over the *value* zero -- the identity element under addition, and the number A such that A * X = A for all X. It's the first of those properties that makes it important in computer programming, and in more general terms considering the null (i.e., zero) case is always important in programming. Dustin On Jun 5, 2006, at 3:48 PM, ron wrote: > It seems that the confusion is exacerbated by the fact > that we're using the theoretical number set to > reference the common one. I suppose this is a > carry-over from binary, since in binary if you don't > have a zero, you also won't have a bunch of other > numbers like 2, 4 and so forth. From yi at yiqiang.net Mon Jun 5 22:33:18 2006 From: yi at yiqiang.net (Yi Qiang) Date: Mon, 05 Jun 2006 13:33:18 -0700 Subject: [Tutor] problem with unpickling an object In-Reply-To: <44849296.3060307@yiqiang.net> References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net> <44843C34.2050502@yiqiang.net> <44843EE0.2080007@tds.net> <44849296.3060307@yiqiang.net> Message-ID: <4484950E.30809@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Yi Qiang wrote, On 06/05/2006 01:22 PM: > Kent Johnson wrote, On 06/05/2006 07:25 AM: >>> No, the find_global() hook is for cPickle. See the next-to-last >>> paragraph on this page: >>> http://docs.python.org/lib/pickle-sub.html > Sorry, I don't follow. How does one get access to the find_global > attribute for cPickle? I created an cPickle.Unpickler object, and the > only attributes that I have access to are .load and .noload. What am I > missing here? Ok, it looks I have to create that attribute. Now, the next confusing part is that the documentation says: 'If it [find_global] is None then any attempts to unpickle instances will raise an UnpicklingError.' What exactly is considered an instance in this context? I tried unpickling a dictionary, and it unpickled just fine. Please, someone explain :) - -- Yi Qiang (yi at yiqiang.net) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEhJUOtXlIMrUVVksRAm8lAJwI1IKZlwiXDRVC+1c73c+ieOmYewCghceY F8Pqth3M/1ufF3hdkPufHv0= =Uavt -----END PGP SIGNATURE----- From pjlists at gmail.com Tue Jun 6 00:47:32 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 6 Jun 2006 00:47:32 +0200 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable Message-ID: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> The best way to explain my problem is with an example f0_n = "field0" f0_v ="value0" f1_n="field1" f1_v="value1" ... f100_n = "field100" f100_v = "value100" I now want to define a list of 2ples of the form [(f0_n,f0_v),(f1_n,f1_v),...,(f100_n,f100_v)] I wish to define the list using a for loop, i.e. data = [ ] for i in xrange(1,101): data = data.append((f %i _n, f %i_v)) I have put the % sign above. Obviously it is not like that but how does one do it? The aim is to reference the s variable whose name is the string that I create concatenating "f" + str(i)+"_n" and "f"+str(i)+"_v" Thanks Peter Jessop From andre.roberge at gmail.com Tue Jun 6 01:09:56 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 5 Jun 2006 20:09:56 -0300 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> Message-ID: <7528bcdd0606051609x5d2b8525l45e7be367c93e952@mail.gmail.com> I'm not sure if it's exactly what you need, but here's something that may come close. On 6/5/06, Peter Jessop wrote: > > The best way to explain my problem is with an example > > f0_n = "field0" > f0_v ="value0" > f1_n="field1" > f1_v="value1" > ... > > f100_n = "field100" > f100_v = "value100" Ok, I'm going to recreate this fake example, rather than typing it all out :-) for i in range(101): print 'f%d_n = "field%d"'%(i, i) print 'f%d_v = "value%d"'%(i, i) I then cut-and-paste the result in the editor window and start again. data1 = ["(f%d_n, f%d_v)"%(i, i) for i in range(101)] print data1 # This shows: ['(f0_n, f0_v)', '(f1_n, f1_v)', '(f2_n, f2_v)' ... '(f100_n, f100_v)'] data2 = ','.join(data1) data2 = '[' + data2 + ']' print eval(data2) The result is: [('field0', 'value0'), ('field1', 'value1'), ..., ('field100', 'value100')] i.e. it is a list of 2ples that contains the values of the variable, rather than the variables themselves. For most applications, this should be the same thing, right? Andr? I now want to define a list of 2ples of the form > > [(f0_n,f0_v),(f1_n,f1_v),...,(f100_n,f100_v)] > > I wish to define the list using a for loop, i.e. > > data = [ ] > for i in xrange(1,101): > data = data.append((f %i _n, f %i_v)) > > I have put the % sign above. Obviously it is not like that but how > does one do it? > The aim is to reference the s variable whose name is the string that I > create concatenating "f" + str(i)+"_n" and "f"+str(i)+"_v" > > Thanks > > Peter Jessop > _______________________________________________ > 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/20060605/15de327f/attachment.htm From pjlists at gmail.com Tue Jun 6 01:28:01 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 6 Jun 2006 01:28:01 +0200 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> Message-ID: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com> Thanks Andre I realise now I did not make it too clear. Basically the variable names are predictable but the values aren't. Maybe I should have expressed it like this f0_n = "arbitrayValue" f0_v ="another valule" f1_n="something else" f1_v="etc.." ... f100_n = "another value" f100_v = "nexvalue" I then wish to pass the list of 2ples as an argument to a function and thus I need the variable themselves and not the string values. From andre.roberge at gmail.com Tue Jun 6 01:47:19 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 5 Jun 2006 20:47:19 -0300 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com> Message-ID: <7528bcdd0606051647o30024fd3o30657a59cb8ce32e@mail.gmail.com> On 6/5/06, Peter Jessop wrote: > > Thanks Andre > > I realise now I did not make it too clear. > Basically the variable names are predictable but the values aren't. I assumed that. I just recreated the list as you gave it because it was easy :-) Maybe I should have expressed it like this > > f0_n = "arbitrayValue" > f0_v ="another valule" > f1_n="something else" > f1_v="etc.." > ... > > f100_n = "another value" > f100_v = "nexvalue" > > I then wish to pass the list of 2ples as an argument to a function and > thus I need the variable themselves and not the string values. Ok, the approach I gave you would produce instead: data = [ ("arbitraryValue", "another valule"), ("something else", .... ] Why couldn't you pass this to your function? Ok, here's another experiment... 1. I will first generate a whole bunch of arbitrary numerical values: import random for i in range(101): print 'f%d_n = %d'%(i, random.randint(0, 100)) print 'f%d_v = %d'%(i, random.randint(0, 100)) === f0_n = 40 f0_v = 28 f1_n = 49 f1_v = 5 ... ==================== 2. Next, I will use the approach I gave you before, but with these values, and I will do it with a one-liner: data = '[' + ','.join(["(f%d_n, f%d_v)"%(i, i) for i in range(101)]) + ']' big_list = eval(data) 3. Next, I will define a function that works on these values def find_special(data): for item in data: if item[0] < 10: print item[1], find_special(big_list) ========= The result in my case turns out to be: 49 50 57 96 98 23 69 16 4 ==================== Of course this result on its own is meaningless :-) Nonetheless, does this help? Or do you really, absolutely need to pass the named variables, not their values? Andr? _______________________________________________ > 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/20060605/9df13d9e/attachment.html From pjlists at gmail.com Tue Jun 6 02:00:22 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 6 Jun 2006 02:00:22 +0200 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> Message-ID: <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com> Andr? Thanks a lot for clearing this up for me. Regards Peter Jessop From kent37 at tds.net Tue Jun 6 02:03:32 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Jun 2006 20:03:32 -0400 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com> Message-ID: <4484C654.8040504@tds.net> Peter Jessop wrote: > Thanks Andre > > I realise now I did not make it too clear. > Basically the variable names are predictable but the values aren't. > > Maybe I should have expressed it like this > > f0_n = "arbitrayValue" > f0_v ="another valule" > f1_n="something else" > f1_v="etc.." > ... > > f100_n = "another value" > f100_v = "nexvalue" Generally the best way to do something like this is not to use named variables at all, rather to use some kind of data structure to store the values. In this case, you seem to have 101 pairs of values. Perhaps your primary data structure should be the list of (fx_n, fx_v) values, rather than trying to access the named variables. Alternately, it looks like your data pairs are actually (name, value) pairs. If so, and if the order of pairs is not important, you could store them in a dictionary using the name as the key and the value as, well, the value ;) > I then wish to pass the list of 2ples as an argument to a function and > thus I need the variable themselves and not the string values. Hmm, I don't know what you mean by "the variable themselves". Do you mean you want the called function to change the value of the variable? That is hard to do in Python. But it's easy for a function to modify a list or dictionary passed to it. A little more context might be helpful here. Where do all these values come from? What are you trying to do with them? Kent From keosophon at khmeros.info Tue Jun 6 04:20:29 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Tue, 6 Jun 2006 09:20:29 +0700 Subject: [Tutor] FileDialogBox in Tkinter Message-ID: <200606060920.29837.keosophon@khmeros.info> Hi all, What to do in order to get FileDialogBox in Tkinter for using? Where to find a complete reference of Tkinter? Thanks, Phon From 3dbernard at gmail.com Tue Jun 6 05:23:21 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 5 Jun 2006 23:23:21 -0400 Subject: [Tutor] FileDialogBox in Tkinter In-Reply-To: <200606060920.29837.keosophon@khmeros.info> References: <200606060920.29837.keosophon@khmeros.info> Message-ID: <61d0e2b40606052023x61de799awcabfd9a9a92f8161@mail.gmail.com> Hi Phon, This is the most complete Tkinter reference I could find (although it's not exactly "complete"): http://www.pythonware.com/library/tkinter/introduction/ As to how to make the file dialog box to work, I found this introduction tutorial extremely helpful to get started with the Tkinter widgets, methods and options: http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm The file dialog classes should not pose a problem, they work exactly like other Tkinter widgets. Cheers Bernard On 6/5/06, Keo Sophon wrote: > Hi all, > > What to do in order to get FileDialogBox in Tkinter for using? Where to find a > complete reference of Tkinter? > > Thanks, > Phon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From soumitr_sidd at yahoo.co.in Tue Jun 6 06:44:55 2006 From: soumitr_sidd at yahoo.co.in (soumitr siddharth) Date: Tue, 6 Jun 2006 05:44:55 +0100 (BST) Subject: [Tutor] doubt plz help Message-ID: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com> how do i clear the scseer ?? suppose i have two pages to display one after the other ,how should i do it ? --------------------------------- Yahoo! India Answers: Share what you know. Learn something new Click here Send free SMS to your Friends on Mobile from your Yahoo! Messenger Download now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060606/b3125819/attachment.htm From john at fouhy.net Tue Jun 6 07:24:39 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 6 Jun 2006 17:24:39 +1200 Subject: [Tutor] FileDialogBox in Tkinter In-Reply-To: <200606060920.29837.keosophon@khmeros.info> References: <200606060920.29837.keosophon@khmeros.info> Message-ID: <5e58f2e40606052224n446ddc8ya1a40558bceeaca8@mail.gmail.com> On 06/06/06, Keo Sophon wrote: > What to do in order to get FileDialogBox in Tkinter for using? Where to find a > complete reference of Tkinter? Fredrik Lundh's guide (which Bernard linked) is a good Tkinter reference. For the FileDialogBox, you will need another import statement --- 'import Tkinter' or 'from Tkinter import *' won't bring it in. New Mexico Tech has a good reference too: http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html It's a bit old, but a lot of it is still accurate, and it goes into more detail than the pythonware one. -- John. From hokkakada at khmeros.info Tue Jun 6 08:39:21 2006 From: hokkakada at khmeros.info (kakada) Date: Tue, 06 Jun 2006 13:39:21 +0700 Subject: [Tutor] combo box Message-ID: <44852319.1080804@khmeros.info> Dear Friends, I am now working on GUI python (Tkinter). I want to use combobox as my widget, but I cannot find it in any document. Does anybody have experience with that? Thanks, da From alan.gauld at freenet.co.uk Tue Jun 6 09:49:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 6 Jun 2006 08:49:05 +0100 Subject: [Tutor] FileDialogBox in Tkinter References: <200606060920.29837.keosophon@khmeros.info> Message-ID: <002701c6893d$af9c3c20$0a01a8c0@XPpro> > What to do in order to get FileDialogBox in Tkinter for using? >>> import tkFileDialog >>> res = tkFileDialog.asksaveasfilename(defaultextension=".txt") Does that help? > Where to find a complete reference of Tkinter? I assume you have checked the Tkinter section of the Python web site? It points at several resources. Fred Lundh's site is the best online resource I think. The most complete resource is Grayson's Book on Tkinter published by Manning. Alan G From pjlists at gmail.com Tue Jun 6 10:31:52 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 6 Jun 2006 10:31:52 +0200 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com> Message-ID: <7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com> Kent Thanks for your reply. The structure is for sending form variables and values to a web server with POST. I am using urllib.urlencode which accepts a list or dictionary as argument. The idea is to look for airline tickets. The airline I buy from only lets me search by data but I want to automate the process by POSTing the form for a range of dates so that effectively I can search by price not by date. I will then parse the returned HTML using HTMLParser or BeautifulSoup. The form has a large number of variables and I just want to find a tidy way to organise the information. Peter From keosophon at khmeros.info Tue Jun 6 10:36:55 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Tue, 6 Jun 2006 15:36:55 +0700 Subject: [Tutor] FileDialogBox in Tkinter In-Reply-To: <002701c6893d$af9c3c20$0a01a8c0@XPpro> References: <200606060920.29837.keosophon@khmeros.info> <002701c6893d$af9c3c20$0a01a8c0@XPpro> Message-ID: <200606061536.56067.keosophon@khmeros.info> On Tuesday 06 June 2006 14:49, you wrote: > > What to do in order to get FileDialogBox in Tkinter for using? > > > >>> import tkFileDialog > >>> res = tkFileDialog.asksaveasfilename(defaultextension=".txt") > > Does that help? > > > Where to find a complete reference of Tkinter? > > I assume you have checked the Tkinter section of the Python > web site? It points at several resources. > > Fred Lundh's site is the best online resource I think. > The most complete resource is Grayson's Book on Tkinter > published by Manning. > > Alan G Yes, it helps and does what I want. I had read some also your document, but they don't talk deeply and widely about Tkinter. However, they are good resource to start. Thanks. Phon From alan.gauld at freenet.co.uk Tue Jun 6 10:56:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 6 Jun 2006 09:56:45 +0100 Subject: [Tutor] FileDialogBox in Tkinter References: <200606060920.29837.keosophon@khmeros.info> <002701c6893d$af9c3c20$0a01a8c0@XPpro> <200606061536.56067.keosophon@khmeros.info> Message-ID: <000301c68947$237bff50$0a01a8c0@XPpro> > Yes, it helps and does what I want. I had read some also your > document, but > they don't talk deeply and widely about Tkinter. However, they are > good > resource to start. Yes, the GUI topic in my tutor only introduces some of the language and the most basic principles. I then leave you to read Fred's tutorial for more depth. But its one area where I keep toying with adding a new topic on "Advanced GUI programming" but I'm not really qualified to write that since I do very little GUI work! (For example I just realized the other day that I've never actually created a menu bar in any of my Tkinter programs to date! ;-) Alan G From python at kapitalisten.no Tue Jun 6 12:26:07 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 6 Jun 2006 12:26:07 +0200 (CEST) Subject: [Tutor] elif Message-ID: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net> Hello. I need to make a program that does certain things every 5 minutes mon-friday. I have started writing it like this: if strftime('%w') == 1: if strftime('%M') % 5 == 0: n.start() elif strftime('%w') == 2: if strftime('%M') % 5 == 0: n.start() ........ This seems kind of a redundant way of writing the code. I haven't gotten any statement like this to work: if strftime('%w') == 1 or 2 or 3: or for strftime('%w') in range(1,5): What would be a more efficient way of writing it without writing it several times? Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From python at kapitalisten.no Tue Jun 6 12:30:39 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 6 Jun 2006 12:30:39 +0200 (CEST) Subject: [Tutor] doubt plz help Message-ID: <10833.193.71.38.142.1149589839.squirrel@mail.sporck.net> Try to rephrase that question. I don't think I was the only one not understanding what you are asking? >how do i clear the scseer ?? >suppose i have two pages to display one >after the other ,how should i do it ? -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From m_webber_sydney at yahoo.com.au Tue Jun 6 13:26:22 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Tue, 6 Jun 2006 12:26:22 +0100 Subject: [Tutor] doubt plz help In-Reply-To: <10833.193.71.38.142.1149589839.squirrel@mail.sporck.net> Message-ID: <002f01c6895c$09eecf80$0200a8c0@kookaburra> >> Try to rephrase that question. I don't think I was the only one not understanding what you are asking? Try to rephrase that response. I'm sure that you understand the double negative in the second sentence, but many who speak English as a second language (including, possibly, the original poster) will not! From kent37 at tds.net Tue Jun 6 14:07:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 08:07:03 -0400 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable In-Reply-To: <7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com> References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com> <7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com> Message-ID: <44856FE7.9080808@tds.net> Peter Jessop wrote: > Kent > > Thanks for your reply. > The structure is for sending form variables and values to a web server > with POST. > I am using urllib.urlencode which accepts a list or dictionary as argument. > > The idea is to look for airline tickets. > The airline I buy from only lets me search by data but I want to > automate the process by POSTing the form for a range of dates so that > effectively I can search by price not by date. > I will then parse the returned HTML using HTMLParser or BeautifulSoup. > > The form has a large number of variables and I just want to find a > tidy way to organise the information. It sounds like you should use a dictionary directly as your primary data structure. For data that is fixed just use a literal dictionary, for example args = dict(origin='SJO', destination='MHO') For dates, you presumably have some kind of loop to generate dates in a range, then insert them into the dict: for date in : args['date'] = date # fetch and parse the URL with args as the POST data Kent From kent37 at tds.net Tue Jun 6 14:09:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 08:09:33 -0400 Subject: [Tutor] doubt plz help In-Reply-To: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com> References: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com> Message-ID: <4485707D.2010403@tds.net> soumitr siddharth wrote: > how do i clear the scseer ?? > suppose i have two pages to display one > after the other ,how should i do it ? It depends on the OS and the type of display. For a console application on Windows, use os.system('cls') On Linux I think the corresponding command is os.system('clear') If you are using a GUI toolkit then tell us which one and a bit more details about what you want to do. Kent From kent37 at tds.net Tue Jun 6 14:17:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 08:17:53 -0400 Subject: [Tutor] elif In-Reply-To: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net> References: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net> Message-ID: <44857271.1060202@tds.net> ?yvind wrote: > Hello. > > I need to make a program that does certain things every 5 minutes > mon-friday. I have started writing it like this: > > if strftime('%w') == 1: > if strftime('%M') % 5 == 0: > n.start() > > elif strftime('%w') == 2: > if strftime('%M') % 5 == 0: > n.start() > > ........ > > This seems kind of a redundant way of writing the code. > > I haven't gotten any statement like this to work: > if strftime('%w') == 1 or 2 or 3: > or > for strftime('%w') in range(1,5): > > What would be a more efficient way of writing it without writing it > several times? First, I don't think the code you show is correct, the result of strftime() is a string so you should compare to a string: if strftime('%w') == '1': You have to repeat the entire condition, so you could write: if strftime('%w') == '1' or strftime('%w') == '2': This could be cleaned up with a temporary variable: dow = strftime('%w') if dow == '1' or dow == '2': You could also write this as if dow in ['1', '2']: Rather than (ab)using strftime() in this fashion, you might want to look at datetime.datetime. You could write now = datetime.datetime.now() if now.weekday() in [1, 2, 3] and now.minute % 5 == 0: Kent From kermit at polaris.net Tue Jun 6 15:07:40 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 09:07:40 -0400 (Eastern Daylight Time) Subject: [Tutor] Reading characters from file in binary mode Message-ID: <44857E1C.000003.00468@YOUR-4105E587B6> Hello. I wish to translate a SAS data file to text, and do not have the professional version of SAS to do so. I have the student version of SAS, and have translated the shortest of 4 SAS data sets given. For the other 3, I wish to construct a python program to read the characters in, one at a time, translate them to hexadecimal, then figure out how the data matches the data dictionary that I have. I experimented with writing code in C++ to do this. My first experiment, in C++ is #include #include #define TRUE 1 /* Define some handy constants */ #define FALSE 0 /* Define some handy constants */ ifstream f("CMT_MCAID",ios_base::binary); ofstream G("mcaid.txt",ios_base::app); char ch int k int kh,kl int limit limit = 1000 for (int I=1;I<= limit;I++) { f >> ch; k = ch; kl = k%16; kh = (k -kl)/16; G << kh," ",kl," "; } How can I begin to experiment using python? What would be python code equivalent to the above C++ code? Kermit < kermit at Polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060606/92862444/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1431 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060606/92862444/attachment.jpe From ezra.taylor at gmail.com Tue Jun 6 18:05:37 2006 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Tue, 6 Jun 2006 12:05:37 -0400 Subject: [Tutor] doubt plz help In-Reply-To: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com> References: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com> Message-ID: Siddhart: Kent is correct, I tried the os.system('clear') on my Debian linux box and the screen clears. Don't forget to use import os. Also, I 'm new to Python. Hello community. Ezra Taylor On 6/6/06, soumitr siddharth wrote: > > how do i clear the scseer ?? > suppose i have two pages to display one > after the other ,how should i do it ? > > > ________________________________ > Yahoo! India Answers: Share what you know. Learn something new Click here > Send free SMS to your Friends on Mobile from your Yahoo! Messenger Download > now > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Ezra Taylor From kent37 at tds.net Tue Jun 6 18:21:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 12:21:51 -0400 Subject: [Tutor] Reading characters from file in binary mode In-Reply-To: <44857E1C.000003.00468@YOUR-4105E587B6> References: <44857E1C.000003.00468@YOUR-4105E587B6> Message-ID: <4485AB9F.5050106@tds.net> Kermit Rose wrote: > Hello. > > I wish to translate a SAS data file to text, and do not have the > professional > version of SAS to do so. > > I have the student version of SAS, and have translated the shortest of 4 SAS > data sets given. > > For the other 3, I wish to construct a python program to read the > characters in, one > at a time, translate them to hexadecimal, then figure out how the data > matches > the data dictionary that I have. > > I experimented with writing code in C++ to do this. > > My first experiment, in C++ is > > #include > #include > #define TRUE 1 /* Define some handy constants */ > #define FALSE 0 /* Define some handy constants */ > ifstream f("CMT_MCAID",ios_base::binary); > ofstream G("mcaid.txt",ios_base::app); > char ch > int k > int kh,kl > int limit > limit = 1000 > > for (int I=1;I<= limit;I++) > > { > f >> ch; > k = ch; > kl = k%16; > kh = (k -kl)/16; > G << kh," ",kl," "; > } > > > How can I begin to experiment using python? What would be python code > equivalent > to the above C++ code? Hmm, my C++ is remarkably rusty but I think you want something like this: inp = open("CMT_MCAID", "rb") out = open("mcaid.txt", "w") for i in range(1000): ch = inp.read(1) if not ch: break # EOF k = ord(ch) # convert to integer kl = k % 16 kh = k / 16 out.write('%x %x ' % (kh, kl)) out.close() If your input file will fit in memory, there is no need to read a byte at a time, you could change the for / read /test to this: for ch in inp.read()[:1000]: If you can live without the space between the two digits you could use out.write('%02x' % k) With these two changes the entire loop becomes for ch in inp.read()[:1000]: out.write('%02x' % ord(ch)) If your input files are in a well-understood format, you might be interested in the struct module in the standard lib, which will unpack fixed format binary data, or pyconstruct which I think is a bit more flexible: http://pyconstruct.wikispaces.com/ Kent From jsmith at medplus.com Tue Jun 6 18:22:28 2006 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 6 Jun 2006 12:22:28 -0400 Subject: [Tutor] Truly generic database API Message-ID: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> I'm looking for a truly generic database API in that the underlying DB could be text, XML, SQL engine, etc. For instance, initially, the underlying database will probably be text files but we may at some point want to move to a real database server or possibly an XML file without having to recode all of the upper level access. Is anyone aware of such a thing? Thanks, Jeff From jfabiani at yolo.com Tue Jun 6 19:25:01 2006 From: jfabiani at yolo.com (johnf) Date: Tue, 6 Jun 2006 10:25:01 -0700 Subject: [Tutor] Truly generic database API In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> Message-ID: <200606061025.02022.jfabiani@yolo.com> On Tuesday 06 June 2006 09:22, Smith, Jeff wrote: > I'm looking for a truly generic database API in that the underlying DB > could be text, XML, SQL engine, etc. > > For instance, initially, the underlying database will probably be text > files but we may at some point want to move to a real database server or > possibly an XML file without having to recode all of the upper level > access. > > Is anyone aware of such a thing? > > Thanks, > Jeff Jeff is looking for the holy grail. You might want to look at 'dabo' as a frame work. They currently support Postgres, MySQL, SQLite, Firebird, XML all with the same code base. John From kent37 at tds.net Tue Jun 6 19:32:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 13:32:01 -0400 Subject: [Tutor] Truly generic database API In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> Message-ID: <4485BC11.9080403@tds.net> Smith, Jeff wrote: > I'm looking for a truly generic database API in that the underlying DB > could be text, XML, SQL engine, etc. > > For instance, initially, the underlying database will probably be text > files but we may at some point want to move to a real database server or > possibly an XML file without having to recode all of the upper level > access. I don't know of any database API that spans even text files and a conventional database. The broadest Python database API I know of is the standard Python DB-API which give mostly portable access to a wide variety of databases. You will still have to deal with differences in data types, differing options in the API, and different SQL dialects but you can use a database as light as SQLite or as high-powered as Oracle or SQL Server or (insert your favorite high-end database here). http://www.python.org/dev/peps/pep-0249/ http://www.python.org/doc/topics/database/modules/ Object/relational layers like SQLObject and SQLAlchemy give you a higher-level API and more insulation from the variation between databases at the cost of a more limited selection of supported databases. http://www.sqlobject.org/ http://www.sqlalchemy.org/ I think to get the level of portability you are asking for you will have to write your own domain-specific data access module. This is a good idea anyway - you don't want to be spreading SQL code all over your program, for example. Your first implementation might be built on text files, maybe using the csv module. Later you can write new implementations for other back ends. If you write unit tests for the module it will ease the transition to a new back end greatly. I do question why you need such broad portability. Are you sure you can't start with something simple like SQLite with the option of MySQL, PostgreSQL or a commercial product later? Kent From patrick.john.wheeler at gmail.com Tue Jun 6 20:08:20 2006 From: patrick.john.wheeler at gmail.com (Patrick Wheeler) Date: Tue, 6 Jun 2006 13:08:20 -0500 Subject: [Tutor] Reference a variable from a string whose value is the name of the variable Message-ID: <78951a820606061108h3d31a6bcvaf0a63b6e5423cbe@mail.gmail.com> >data = [ ] >for i in xrange(1,101): > data = data.append((f %i _n, f %i_v)) The function locals() will return a dictionary of variables in the current scope. This can then be used to reference variables by name. x=1 xname = 'x' print locals()['x'] print locals()[xname] This prints: 1 1 or for your example. data = [ ] for i in xrange(1,101): data = data.append ((locals()['f'+str(i)+'_n'],locals()['f'+str(i)+'_v']{})) Hope this helps. pjw -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060606/d71a4352/attachment.html From sean.fioritto at gmail.com Tue Jun 6 21:04:14 2006 From: sean.fioritto at gmail.com (Sean Fioritto) Date: Tue, 6 Jun 2006 12:04:14 -0700 Subject: [Tutor] elif In-Reply-To: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net> References: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net> Message-ID: <5f1d9b0c0606061204y634e4a69y83e19b56b4fe62e4@mail.gmail.com> ?yvind, I know this isn't Python advice, but in general it seems as if setting up a cron job would be easier. If you don't know how, I could gladly help. - Sean On 6/6/06, ?yvind wrote: > Hello. > > I need to make a program that does certain things every 5 minutes > mon-friday. I have started writing it like this: > > if strftime('%w') == 1: > if strftime('%M') % 5 == 0: > n.start() > > elif strftime('%w') == 2: > if strftime('%M') % 5 == 0: > n.start() > > ........ > > This seems kind of a redundant way of writing the code. > > I haven't gotten any statement like this to work: > if strftime('%w') == 1 or 2 or 3: > or > for strftime('%w') in range(1,5): > > What would be a more efficient way of writing it without writing it > several times? > > Thanks in advance, > ?yvind > > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kermit at polaris.net Tue Jun 6 21:25:44 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 15:25:44 -0400 (Eastern Daylight Time) Subject: [Tutor] Tutor Digest, Vol 28, Issue 10 References: Message-ID: <4485D6B7.000001.03568@YOUR-4105E587B6> From: tutor-request at python.org Date: 06/06/06 12:31:25 To: tutor at python.org Subject: Tutor Digest, Vol 28, Issue 10 Message: 9 Date: Tue, 06 Jun 2006 12:21:51 -0400 From: Kent Johnson Subject: Re: [Tutor] Reading characters from file in binary mode To: Python Tutor Hmm, my C++ is remarkably rusty but I think you want something like this: inp = open("CMT_MCAID", "rb") out = open("mcaid.txt", "w") for i in range(1000): ch = inp.read(1) if not ch: break # EOF k = ord(ch) # convert to integer kl = k % 16 kh = k / 16 out.write('%x %x ' % (kh, kl)) out.close() ******* Thank you very much. It looks exactly what I wished to know. But now, I realize that I don't know how to invoke Python to compile and execute the program file. I will be making rapid changes to the file, and recompiling over and over again as I change the program during my experimentation. I guess that in the open command, the rb stands for read and something else. what is that something else? Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060606/798770c9/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1431 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060606/798770c9/attachment.jpe From puzzld_me at yahoo.com Tue Jun 6 19:24:30 2006 From: puzzld_me at yahoo.com (Puzzled Me) Date: Tue, 6 Jun 2006 10:24:30 -0700 (PDT) Subject: [Tutor] python application on a web page Message-ID: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com> Hi, I am so new to everything, I don't even know where to post my question... do bear... I made this Python calculator that will take an equation as an input and will display the computed curves on a shiny Tkinter interface Now, I'd like to make this application available on a public web page... and all I could come up with was this post Hints?! I'd also appreciate a link to a beginner forum Thanks Puzzled Me __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060606/d6ed556f/attachment.htm From kent37 at tds.net Wed Jun 7 01:50:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 19:50:01 -0400 Subject: [Tutor] Tutor Digest, Vol 28, Issue 10 In-Reply-To: <4485D6B7.000001.03568@YOUR-4105E587B6> References: <4485D6B7.000001.03568@YOUR-4105E587B6> Message-ID: <448614A9.706@tds.net> Kermit Rose wrote: > Thank you very much. It looks exactly what I wished to know. > > But now, I realize that I don't know how to invoke Python to compile and > execute the > program file. There is no separate compile step, Python does that automatically. The details of running a program vary depending on your OS and how you create the file. Here are some directions: http://www.byteofpython.info/read/source-file.html http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html > > I will be making rapid changes to the file, and recompiling over and > over again as > I change the program during my experimentation. Python is great for quick-turnaround incremental development. > > I guess that in the open command, the rb stands for read and something > else. > what is that something else? Binary. When a file is read in text mode, any line ending (CR, LF or CRLF) is converted to a newline (\n) character. Kent PS The standard on most public mailing lists is to send text email rather than HTML. I for one would appreciate it if you would lose the background graphics! From kermit at polaris.net Wed Jun 7 02:38:01 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 20:38:01 -0400 (Eastern Daylight Time) Subject: [Tutor] How do I get Dos to recognize python command? Message-ID: <44861FE9.00000E.03972@YOUR-4105E587B6> I followed the model in http://www.byteofpython.info/read/source-file.html and saw following results. C:\DavidKaremera\June2006\SAS>python med.py 'python' is not recognized as an internal or external command, operable program or batch file. What do I do to make DOS recognize python as a command? The link http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html that you suggested shows information about the idle. I've used idle for development until now, but it has the annoyance that I must close it and reopen it in order for it to import the changed copy of the program. Besides, I already have one default module saved, and it would seem complicated to have more than one. It would be simpler if I can get the dos prompt to work. Kermit < kermit at Polaris.net > From kermit at polaris.net Wed Jun 7 02:43:42 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 20:43:42 -0400 (Eastern Daylight Time) Subject: [Tutor] bounced email Message-ID: <4486213C.000012.03972@YOUR-4105E587B6> My last email to you bounced. Why? From: tutor-bounces at python.org Date: 06/06/06 20:30:49 To: kermit at polaris.net Subject: The results of your email commands The results of your email command are provided below. Attached is your original message. - Unprocessed: Why am I getting the following after my reply to you? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python org/pipermail/tutor/attachments/20060606/798770c9/attachment.HTML -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1431 bytes Desc: not available Url : http://mail.python org/pipermail/tutor/attachments/20060606/798770c9/attachment-0001.jpe ****** >>>>>> Message: 8 Date: Tue, 06 Jun 2006 19:50:01 -0400 From: Kent Johnson Subject: Re: [Tutor] Tutor Digest, Vol 28, Issue 10 - Ignored: Cc: tutor at python.org There is no separate compile step, Python does that automatically. The details of running a program vary depending on your OS and how you create the file. Here are some directions: http://www.byteofpython.info/read/source-file.html http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html **** Thanks. I will study those links. **** >>>>>>> PS The standard on most public mailing lists is to send text email rather than HTML. I for one would appreciate it if you would lose the background graphics! ***** I know. It annoys me that my current email program sends HTML by default. I don't like the different sized letters that it makes. I did not know anything about background graphics. I will attempt to make this one message plain text, and keep on guard for making each message plain text. If I can't find the option to make it automatically plain text, I will need to develop the habit to change every message to plain text. Kermit < kermit at Polaris.net > - Done. From kent37 at tds.net Wed Jun 7 02:59:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 20:59:11 -0400 Subject: [Tutor] How do I get Dos to recognize python command? In-Reply-To: <44861FE9.00000E.03972@YOUR-4105E587B6> References: <44861FE9.00000E.03972@YOUR-4105E587B6> Message-ID: <448624DF.8020908@tds.net> Kermit Rose wrote: > > I followed the model in > > http://www.byteofpython.info/read/source-file.html > > and saw following results. > > > C:\DavidKaremera\June2006\SAS>python med.py > 'python' is not recognized as an internal or external command, > operable program or batch file. > > > What do I do to make DOS recognize python as a command? You have to add the Python directory (C:\Python24) to your PATH environment variable. There are some directions here: http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-under-windows > > The link http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html > that you suggested > > shows information about the idle. > > I've used idle for development until now, but it has the annoyance > that I must close it and reopen it in order for it to import the changed > copy > of the program. I don't think you have to do that. If you open your file in an editing window you can run from there with Run / Run Module (F5). If you are importing into the shell window you can use Shell / Restart Shell to clear any imports, or use reload() to get a fresh copy. > > Besides, I already have one default module saved, and it would seem > complicated to have more than one. I don't know what you mean by this, what is a default module? Kent PS thanks for losing the graphics... From kent37 at tds.net Wed Jun 7 03:03:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Jun 2006 21:03:22 -0400 Subject: [Tutor] bounced email In-Reply-To: <4486213C.000012.03972@YOUR-4105E587B6> References: <4486213C.000012.03972@YOUR-4105E587B6> Message-ID: <448625DA.5080505@tds.net> Kermit Rose wrote: > > > My last email to you bounced. > > > Why? I don't know, it seems to be complaining about the HTML and missing some image? Kent From tim.peters at gmail.com Wed Jun 7 03:16:14 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 6 Jun 2006 21:16:14 -0400 Subject: [Tutor] bounced email In-Reply-To: <4486213C.000012.03972@YOUR-4105E587B6> References: <4486213C.000012.03972@YOUR-4105E587B6> Message-ID: <1f7befae0606061816h730ec0e7o92b6260f701ef13d@mail.gmail.com> [Kermit Rose] > My last email to you bounced. > > > Why? > > From: tutor-bounces at python.org > Date: 06/06/06 20:30:49 > To: kermit at polaris.net > Subject: The results of your email commands > > > The results of your email command are provided below. Attached is your > original message. > > - Unprocessed: > ... Looks like you sent your original email to tutor-request at python.org instead of to the correct address (tutor at python.org). tutor-request is looking for Mailman commands in the body of your message, and can't make sense of what you wrote. Send messages to the right address and you shouldn't see this again. From kermit at polaris.net Wed Jun 7 04:05:17 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 22:05:17 -0400 (Eastern Daylight Time) Subject: [Tutor] end of line character seems to be invisible. why? Message-ID: <4486345D.00001C.03972@YOUR-4105E587B6> I ran the program # inp = open("CMT_MCAID", "rb") # out = open("mcaid.txt", "w") # for I in range(1,1000): # if I I%60=== 0: # out.write('\n') # ch = inp.read(1) # if not ch: break # EOF # k = ord(ch) # convert to integer # kl = k % 16 # kh = k / 16 # out.write('%d %d ' % (kh, kl)) # out.close() I added the lines # if I%60 == 0: # out.write('\n') because the output was one long line, and I wanted to be able to see the output when I opened the file with notepad. I expected that it would break the line at every 60 characters. It made no difference. The output file is still one long line. Kermit < kermit at polaris.net > From keosophon at khmeros.info Wed Jun 7 04:06:39 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 7 Jun 2006 09:06:39 +0700 Subject: [Tutor] Combo Box in Tkinter Message-ID: <200606070906.39468.keosophon@khmeros.info> Hi, Is there any Combo Box in Tkinter? I looked for it but only found list box. Might it be list box having any option to make itself as a combo box? Thanks, Phon From kermit at polaris.net Wed Jun 7 04:11:18 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 6 Jun 2006 22:11:18 -0400 (Eastern Daylight Time) Subject: [Tutor] Apologies Message-ID: <448635C6.000020.03972@YOUR-4105E587B6> I%60 should have been I%12 My previous request has been solved. From: Kermit Rose Date: 06/06/06 22:05:17 To: tutor at python.org Subject: end of line character seems to be invisible. why? I ran the program # inp = open("CMT_MCAID", "rb") # out = open("mcaid.txt", "w") # for I in range(1,1000): # if I I%60=== 0: On reflection, I realized that more than one character is being written with each character input, so I should have divided 60 by the number of characters output per character input. Thanks for all your assistance. Kermit < kermit at Polaris.net > From john at fouhy.net Wed Jun 7 04:23:31 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 7 Jun 2006 14:23:31 +1200 Subject: [Tutor] Combo Box in Tkinter In-Reply-To: <200606070906.39468.keosophon@khmeros.info> References: <200606070906.39468.keosophon@khmeros.info> Message-ID: <5e58f2e40606061923o147d7652y473af11d1f147f6b@mail.gmail.com> Check out Python MegaWidgets (pmw.sourceforge.net). On 07/06/06, Keo Sophon wrote: > Hi, > > Is there any Combo Box in Tkinter? I looked for it but only found list box. > Might it be list box having any option to make itself as a combo box? > > Thanks, > Phon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emilia12 at mail.bg Wed Jun 7 08:20:16 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Wed, 07 Jun 2006 09:20:16 +0300 Subject: [Tutor] [tutor] dictionary Message-ID: <1149661216.3da261df05f98@mail.bg> Hi, how can i print a dictionary, sorted by the values? ----------------------------- ??????? 666. ???? ? ??????. From govilakanksha at yahoo.com Wed Jun 7 09:01:17 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Wed, 7 Jun 2006 00:01:17 -0700 (PDT) Subject: [Tutor] Affect of doc strings on performance Message-ID: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com> Hi, I wanted to know if we give large doc strings in the python scripts, does it slow down the script execution? Should we always keep those doc strings to minimum if we want fast script execution? Thanks Akanksha __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060607/5d37ad71/attachment.html From kent37 at tds.net Wed Jun 7 11:48:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Jun 2006 05:48:34 -0400 Subject: [Tutor] Affect of doc strings on performance In-Reply-To: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com> References: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com> Message-ID: <4486A0F2.8000405@tds.net> i don't think it makes any difference. I suppose it will slow down the parsing of the file by a tiny amount, and increase memory usage by the size of the strings, but I don't think it will change execution time. The Python standard library has lots of doc strings. Type help(dict) at the interpreter prompt for an example. The dict class is highly optimized so if doc strings affected speed that would be a problem. If you have a time critical function, you could always time it with and without doc strings to be sure! In Python it's always best to answer "which is faster" questions with real data. Kent Akanksha Govil wrote: > Hi, > > I wanted to know if we give large doc strings in the python scripts, > does it slow down the script execution? > > Should we always keep those doc strings to minimum if we want fast > script execution? > > Thanks > Akanksha > > __________________________________________________ > 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 kent37 at tds.net Wed Jun 7 11:56:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Jun 2006 05:56:50 -0400 Subject: [Tutor] [tutor] dictionary In-Reply-To: <1149661216.3da261df05f98@mail.bg> References: <1149661216.3da261df05f98@mail.bg> Message-ID: <4486A2E2.9020908@tds.net> emilia12 at mail.bg wrote: > how can i print a dictionary, sorted by the values? A dictionary itself is an unordered collection and can't be sorted. But you can sort and print the list of key, value pairs returned by dict.items(). For example: In [3]: from operator import itemgetter In [4]: d = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four' } In [5]: for k, v in sorted(d.items(), key=itemgetter(1)): ...: print k, '=', v ...: ...: 4 = four 1 = one 3 = three 2 = two d.items() returns a list of (key, value) pairs: In [6]: d.items() Out[6]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] itemgetter(1) actually returns a function which, when called with an argument x, returns x[1]: In [7]: get1 = itemgetter(1) In [8]: get1(d.items()) Out[8]: (2, 'two') In [9]: get1('abc') Out[9]: 'b' Using itemgetter(1) as the key argument to sorted() makes the sort happen on the second item of each pair, the value. (This example requires Python 2.4; Python 2.3 has no sorted() function, you have to do the sort in a separate step using list.sort(). In earlier Python you have to use a different trick called DSU to sort by key.) Kent From pjlists at gmail.com Wed Jun 7 12:00:15 2006 From: pjlists at gmail.com (Peter Jessop) Date: Wed, 7 Jun 2006 12:00:15 +0200 Subject: [Tutor] (OT) Monitorising WEB POSTs Message-ID: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com> I am building a python application to automate information capture from a web site. I want to use a python application to request and process the information instead of using the site's WEB page. However I am having problems finding out exactly what data the server expects. I have a firefox add-in called Web Developer that gives me good information about the form (fields names etc..) But what I want to do is find out exactly what POST data my browser is sending. I am aware of two ways of doing this. a) A sniffer to read the udp packet sent from my computer b) Send the page to my own WEB server Is there a program or add in that will give me this information without resorting to the solutions above. Peter Jessop From pjlists at gmail.com Wed Jun 7 12:17:09 2006 From: pjlists at gmail.com (Peter Jessop) Date: Wed, 7 Jun 2006 12:17:09 +0200 Subject: [Tutor] python application on a web page In-Reply-To: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com> References: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com> Message-ID: <7a8d5a0c0606070317w73c49c21m72b9449b54a056e5@mail.gmail.com> Tkinter is a multiplatform toolkit for producing programs with graphical interface. But multiplatform refers to BSD, Linux, Mackintosh, Windows etc. If you want to produce the output on the WEB you need to produce the output in HTML or in some way that most users can see it in their Browsers. (Java Script, Flash, etc...) This forum caters well for beginners (and more advanced) and the quality and helpfulness are very high. Here are a some links that may be useful. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://www.python.org/doc/Intros.html http://diveintopython.org/ From pjlists at gmail.com Wed Jun 7 12:37:56 2006 From: pjlists at gmail.com (Peter Jessop) Date: Wed, 7 Jun 2006 12:37:56 +0200 Subject: [Tutor] Truly generic database API In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com> Message-ID: <7a8d5a0c0606070337y38a0c329i9f183f2d018dbb7@mail.gmail.com> It depends on your system constraints. If you are only developing on Windows then you can use ODBC. ODBC supports writing to text files. It is an old fashioned technology and is not very fast. However it is well supported and mature. From m_webber_sydney at yahoo.com.au Wed Jun 7 13:01:12 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Wed, 7 Jun 2006 12:01:12 +0100 Subject: [Tutor] (OT) Monitorising WEB POSTs In-Reply-To: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com> Message-ID: <001501c68a21$b049ac90$0200a8c0@kookaburra> Install the Firefox extension called "Live HTTP headers", and look at the "Generator" tab. This appears to be what you want. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Peter Jessop Sent: 07 June 2006 11:00 To: tutor at python.org Subject: [Tutor] (OT) Monitorising WEB POSTs I am building a python application to automate information capture from a web site. I want to use a python application to request and process the information instead of using the site's WEB page. However I am having problems finding out exactly what data the server expects. I have a firefox add-in called Web Developer that gives me good information about the form (fields names etc..) But what I want to do is find out exactly what POST data my browser is sending. I am aware of two ways of doing this. a) A sniffer to read the udp packet sent from my computer b) Send the page to my own WEB server Is there a program or add in that will give me this information without resorting to the solutions above. Peter Jessop From pjlists at gmail.com Wed Jun 7 13:15:51 2006 From: pjlists at gmail.com (Peter Jessop) Date: Wed, 7 Jun 2006 13:15:51 +0200 Subject: [Tutor] (OT) Monitorising WEB POSTs In-Reply-To: <001501c68a21$b049ac90$0200a8c0@kookaburra> References: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com> <001501c68a21$b049ac90$0200a8c0@kookaburra> Message-ID: <7a8d5a0c0606070415n1a605772wf3251b081707cca8@mail.gmail.com> Matthew Fantastic! Exactly what I needed From kermit at polaris.net Wed Jun 7 13:59:18 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 7 Jun 2006 07:59:18 -0400 (Eastern Daylight Time) Subject: [Tutor] default module Message-ID: <4486BF96.000005.00248@YOUR-4105E587B6> Message: 3 Date: Tue, 06 Jun 2006 20:59:11 -0400 From: Kent Johnson Subject: Re: [Tutor] How do I get Dos to recognize python command? To: Python Tutor > > Besides, I already have one default module saved, and it would seem > complicated to have more than one. I don't know what you mean by this, what is a default module? Kent ****** Hello Kent. A while back in time, I wanted to make a library of subroutines. Someone showed me how to tell python to declare the file a module. I don't remember how I did it. Now whenever I want to make the library available, in idle, I type import factor30 from factor30 import factor00, gcd, ksqrt # what ever subroutines I wish to have local I assumed that I could have only one library. That why I called it the default module. Kermit < kermit at polaris.net > From kent37 at tds.net Wed Jun 7 14:12:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Jun 2006 08:12:59 -0400 Subject: [Tutor] default module In-Reply-To: <4486BF96.000005.00248@YOUR-4105E587B6> References: <4486BF96.000005.00248@YOUR-4105E587B6> Message-ID: <4486C2CB.9020001@tds.net> Kermit Rose wrote: > From: Kent Johnson >> Besides, I already have one default module saved, and it would seem >> complicated to have more than one. > > I don't know what you mean by this, what is a default module? > > A while back in time, I wanted to make a library of subroutines. > > Someone showed me how to tell python to declare the file a module. > > I don't remember how I did it. > > Now whenever I want to make the library available, > > in idle, > > I type > > import factor30 > from factor30 import factor00, gcd, ksqrt # what ever subroutines I > wish to have local > > I assumed that I could have only one library. > > That why I called it the default module. Hi Kermit, To make a module available for import, you just have to save it somewhere on your Python path. There are several ways to do this, but if you want to make another importable module just save it in the same location as factor30.py. There is no practical limit on how many modules you can have - just RAM and disk space limits, AFAIK. You already have many modules installed as part of the standard library and any third-party add-ons you have installed. If you are working with a module from the interpreter and you make changes to the module, you have to reload it with the command >>> reload(factor30) This won't work for local names (from factor30 import xx)! Just use the full name to access any elements of factor30, e.g. factor30.gcd. Read more here: http://www.python.org/doc/faq/programming/#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen Kent From doug.shawhan at gmail.com Wed Jun 7 18:55:57 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 7 Jun 2006 11:55:57 -0500 Subject: [Tutor] Offtopic observation Message-ID: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> This marks the third time this week I have been typing in a question for the group, and have made the answer apparent just by trying to explain my question clearly. This suggests that either I think better in text, or Proust was onto something ... but then again, I majored in english. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060607/d933845c/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Jun 7 19:28:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Jun 2006 10:28:39 -0700 (PDT) Subject: [Tutor] Offtopic observation In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> Message-ID: On Wed, 7 Jun 2006, doug shawhan wrote: > This marks the third time this week I have been typing in a question for > the group, and have made the answer apparent just by trying to explain > my question clearly. Yes. *grin* It's a very powerful technique. Writing does this for me as well. From ms at cerenity.org Wed Jun 7 21:10:54 2006 From: ms at cerenity.org (Michael) Date: Wed, 7 Jun 2006 20:10:54 +0100 Subject: [Tutor] Offtopic observation In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> Message-ID: <200606072010.54704.ms@cerenity.org> On Wednesday 07 June 2006 17:55, doug shawhan wrote: > This marks the third time this week I have been typing in a question for > the group, and have made the answer apparent just by trying to explain my > question clearly. > > This suggests that either I think better in text, or Proust was onto > something ... but then again, I majored in english. It's also called confessional debugging :-) It's also something that actually tends to apply outside programming as well. The act of understanding the problem often leads to a solution :-) Michael. From kent37 at tds.net Wed Jun 7 21:24:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jun 2006 15:24:43 -0400 Subject: [Tutor] Offtopic observation Message-ID: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net> > From: Danny Yoo > On Wed, 7 Jun 2006, doug shawhan wrote: > > > This marks the third time this week I have been typing in a question for > > the group, and have made the answer apparent just by trying to explain > > my question clearly. > > Yes. *grin* It's a very powerful technique. Writing does this for me as > well. For me it's often talking. I have a friend in the office I go to when I am stuck on something. He's a very powerful listener - often by the time I am done describing the problem and the available options I have settled on an answer. Kent From klappnase at freenet.de Wed Jun 7 23:52:15 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 7 Jun 2006 23:52:15 +0200 Subject: [Tutor] combo box In-Reply-To: <44852319.1080804@khmeros.info> References: <44852319.1080804@khmeros.info> Message-ID: <20060607235215.04540800.klappnase@freenet.de> On Tue, 06 Jun 2006 13:39:21 +0700 kakada wrote: > Dear Friends, > > I am now working on GUI python (Tkinter). > I want to use combobox as my widget, but I cannot find it in any document. > > Does anybody have experience with that? > There is no ComboBox widget in plain Tkinter. Probably the easiest way to get one is to use Tix which is included in the windows python distribution and should be available in any recent linux distro. If you want to use Tix simply replace the import line from Tkinter import * with from Tix import * You then can use your Tknter widgets as usual, plus a nice set of extra widgets (ComboBox, NoteBook, DirTree etc.) . I hope this helps Michael From kermit at polaris.net Thu Jun 8 00:44:08 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 7 Jun 2006 18:44:08 -0400 (Eastern Daylight Time) Subject: [Tutor] module versus file Message-ID: <448756B8.00001D.03044@YOUR-4105E587B6> Message: 7 Date: Wed, 07 Jun 2006 08:12:59 -0400 From: Kent Johnson Subject: Re: [Tutor] default module >>>>>>>>>> Hi Kermit, To make a module available for import, you just have to save it somewhere on your Python path. There are several ways to do this, ******* Yes. By some means that I don't remember I declared the file factor30.py in directory math\factoring to be a module. >>>>>>>>>>>> but if you want to make another importable module just save it in the same location as factor30.py. *************** Are you saying that any .py file that I save in math\factoring can be imported? >>>>>>>> There is no practical limit on how many modules you can have - just RAM and disk space limits, AFAIK. ****** Had to look up the acronyn. What is AFAIK? It's an acronym for As Far As I Know. >>>>>>>>>> You already have many modules installed as part of the standard library and any third-party add-ons you have installed. ********** Yes. I'm impressed with the listing in built_in. I assumed system modules were handled in a different way than user modules. ********* >>>>>>>> If you are working with a module from the interpreter and you make changes to the module, you have to reload it with the command >>> reload(factor30) ***** I will try the reload command next time I work with factor30. >>>>>> This won't work for local names (from factor30 import xx)! Just use the full name to access any elements of factor30, e.G. factor30.gcd. Read ****** In order to have the shorter name, gcd instead of factor30.gcd, I prepare by typing from factor30 import gcd Once someone said that modules and files are not the same thing. This statement left me puzzled. Why not? Kermit < kermit at polaris.net > From john at fouhy.net Thu Jun 8 00:45:41 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 8 Jun 2006 10:45:41 +1200 Subject: [Tutor] Offtopic observation In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> Message-ID: <5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com> On 08/06/06, doug shawhan wrote: > This marks the third time this week I have been typing in a question for the > group, and have made the answer apparent just by trying to explain my > question clearly. I'm usually a step back from that --- the answer becomes apparent approximately five seconds _after_ I send off my question.. -- John. From sisson.j at gmail.com Wed Jun 7 21:32:25 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Wed, 07 Jun 2006 20:32:25 +0100 Subject: [Tutor] Offtopic observation In-Reply-To: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net> References: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: <448729C9.2030108@gmail.com> Kent Johnson wrote: >> From: Danny Yoo >> On Wed, 7 Jun 2006, doug shawhan wrote: >> >>> This marks the third time this week I have been typing in a question for >>> the group, and have made the answer apparent just by trying to explain >>> my question clearly. >> Yes. *grin* It's a very powerful technique. Writing does this for me as >> well. > > For me it's often talking. I have a friend in the office I go to when I am stuck on something. He's a very powerful listener - often by the time I am done describing the problem and the available options I have settled on an answer. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I want one of those...hahaha...someone who would listen long enough for me to settle on an answer on my own? God, you're a lucky person. If I so much as shape my mouth like the word "computer" is going to come out, my wife runs for cover...my friends do their best, but most of them aren't great listeners so we end up getting off topic and never do find a solution. My daughter listens, but I have to wait for her to start pre-school for hope of any real response. Consider yourself quite lucky, Kent. Jon From dkuhlman at rexx.com Thu Jun 8 05:10:52 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 7 Jun 2006 20:10:52 -0700 Subject: [Tutor] module versus file In-Reply-To: <448756B8.00001D.03044@YOUR-4105E587B6> References: <448756B8.00001D.03044@YOUR-4105E587B6> Message-ID: <20060608031052.GA29650@cutter.rexx.com> On Wed, Jun 07, 2006 at 06:44:08PM -0400, Kermit Rose wrote: [snip] > > > Yes. By some means that I don't remember I declared the file factor30.py > in directory > math\factoring > > to be a module. > If you are importing a module from a directory other than your current directory, then the directory is effectively a package. In order to make a directory into a package, the directory must contain a file named __init__.py. The file __init__.py can be empty or can contain code. It will be evaluated the first time (and only the first time) an application imports the package or something in it. Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Thu Jun 8 05:15:48 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 7 Jun 2006 20:15:48 -0700 Subject: [Tutor] Offtopic observation In-Reply-To: <5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com> References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com> <5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com> Message-ID: <20060608031548.GB29650@cutter.rexx.com> On Thu, Jun 08, 2006 at 10:45:41AM +1200, John Fouhy wrote: > On 08/06/06, doug shawhan wrote: > > This marks the third time this week I have been typing in a question for the > > group, and have made the answer apparent just by trying to explain my > > question clearly. 1. That's why we write and ask questions: to make things clear to ourselves. 2. And the reason we teach (Python etc) is so that students ask us questions and we are forced to explain ourselves, which enables us to understand what we are talking about. Dave > > I'm usually a step back from that --- the answer becomes apparent > approximately five seconds _after_ I send off my question.. > You are one of the quick ones. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Thu Jun 8 11:54:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Jun 2006 5:54:42 -0400 Subject: [Tutor] module versus file Message-ID: <20060608095442.TOQR20006.outaamta01.mail.tds.net@smtp.tds.net> > From: Dave Kuhlman > > If you are importing a module from a directory other than your > current directory, then the directory is effectively a package. > In order to make a directory into a package, the directory must > contain a file named __init__.py. That's not quite right. If the module is in a directory that is in sys.path, it is just a plain module, not a package. If the module is in a subdirectory of a directory in sys.path, then the subdirectory is a package and requires an __init__.py file to be recognized as a package. There is a good discussion of modules and packages in the tutorial: http://docs.python.org/tut/node8.html Kent From kermit at polaris.net Thu Jun 8 14:59:24 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 8 Jun 2006 08:59:24 -0400 (Eastern Daylight Time) Subject: [Tutor] directory as package Message-ID: <44881F2C.000007.03652@YOUR-4105E587B6> Message: 4 Date: Wed, 7 Jun 2006 20:10:52 -0700 From: Dave Kuhlman Subject: Re: [Tutor] module versus file To: tutor at python.org Hello Dave. >>>>>>>>>> If you are importing a module from a directory other than your current directory, then the directory is effectively a package. In order to make a directory into a package, the directory must contain a file named __init__.py. The file __init__.py can be empty or can contain code. It will be evaluated the first time (and only the first time) an application imports the package or something in it. Dave ******* It must be someother method that I used, because there is no file named _init_.py is directory math\factoring Is it that the convention must be different for a windows machine? C:\Math\Factoring>dir *init* Volume in drive C has no label. Volume Serial Number is 4748-654D Directory of C:\Math\Factoring File Not Found Kermit < kermit at polaris.net > From kent37 at tds.net Thu Jun 8 15:28:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 08 Jun 2006 09:28:27 -0400 Subject: [Tutor] module versus file In-Reply-To: <448756B8.00001D.03044@YOUR-4105E587B6> References: <448756B8.00001D.03044@YOUR-4105E587B6> Message-ID: <448825FB.7030600@tds.net> Kermit Rose wrote: > Are you saying that any .py file that I save in math\factoring > can be imported? Yes > You already have > many modules installed as part of the standard library and any > third-party add-ons you have installed. > > ********** > > Yes. I'm impressed with the listing in built_in. > > I assumed system modules were handled in a different way than user modules. Many system modules are written in Python and handled the same way as user modules - they are found by searching sys.path. The actual files are in C:\Python24\Lib Some system modules are written in C, they are still on sys.path but the modules are called .pyd. Some system modules are built-in to Python and don't correspond to an actual file in the file system. > > ********* > > > If you are working with a module from the interpreter and you make > changes to the module, you have to reload it with the command > >>> reload(factor30) > > ***** > > I will try the reload command next time I work with factor30. > > This won't work for local names (from factor30 import xx)! Just use the > full name to access any elements of factor30, e.G. factor30.gcd. Read > > ****** > > In order to have the shorter name, > > gcd > > instead of factor30.gcd, > > I prepare by > > typing > > from factor30 import gcd If you do this, reload(factor30) will not get you a new copy of gcd because gcd is bound to the old function. > > > Once someone said that modules and files are not the same thing. > > This statement left me puzzled. Why not? Most modules do have corresponding files. The exceptions are the ones built-in to Python. In fact modules have a __file__ attribute that tells you where it came from; try typing factor30.__file__ Kent From emily.fortuna at nist.gov Thu Jun 8 15:19:58 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Thu, 08 Jun 2006 09:19:58 -0400 Subject: [Tutor] making a python program part of xhtml Message-ID: <448823FE.6080504@nist.gov> Hola everyone, I'm working on creating a webpage in which a user can submit data into fields to be held in a database (there are other details, but this is the gist of the idea), and I need to use python. I am unfamiliar with manipulating data and web apps as a whole (and new to python), so I have been encountering much unfamiliar terrain. I _think_ I want to somehow embed the python into the page, but I'm really not sure how to do it. After googling I found some programs that generate xhtml from python, but I don't think that is what I want, or is it? Your help is appreciated! Emily From cspears2002 at yahoo.com Thu Jun 8 18:44:24 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 8 Jun 2006 09:44:24 -0700 (PDT) Subject: [Tutor] PyGTK on cygwin Message-ID: <20060608164424.66786.qmail@web51604.mail.yahoo.com> Does PyGTK work well on cygwin? From mhansen at cso.atmel.com Thu Jun 8 18:59:57 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 08 Jun 2006 10:59:57 -0600 Subject: [Tutor] making a python program part of xhtml In-Reply-To: <448823FE.6080504@nist.gov> Message-ID: <000601c68b1c$f8aa66e0$28645f0a@mikehansen> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Emily Fortuna > Sent: Thursday, June 08, 2006 7:20 AM > To: tutor at python.org > Subject: [Tutor] making a python program part of xhtml > > Hola everyone, > I'm working on creating a webpage in which a user can submit > data into > fields to be held in a database (there are other details, but this is > the gist of the idea), and I need to use python. I am > unfamiliar with > manipulating data and web apps as a whole (and new to > python), so I have > been encountering much unfamiliar terrain. I _think_ I want > to somehow > embed the python into the page, but I'm really not sure how > to do it. > After googling I found some programs that generate xhtml from python, > but I don't think that is what I want, or is it? Your help > is appreciated! > Emily > Although you can embed python in a web page to be run on a server, you probably don't want to do that.(It can get pretty messy.) What I'd suggest is creating a web page that calls a python program on the server and processes form fields in the web page. The python program would save the data in the database. [web page] -> [python program on server] -> [database] Look at the FORM tag in HTML/XHTML. Also look at the cgi module for Python. I think there's some web topics on the Python web site that might point to articles about doing simple cgi stuff in Python. http://wiki.python.org/moin/CgiScripts http://www.devshed.com/index2.php?option=content&task=view&id=198&pop=1&page =0&hide_js=1 Is an article on cgi programming with Python. Mike From clsdaniel at gmail.com Thu Jun 8 19:37:14 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Thu, 8 Jun 2006 10:37:14 -0700 Subject: [Tutor] PyGTK on cygwin In-Reply-To: <20060608164424.66786.qmail@web51604.mail.yahoo.com> References: <20060608164424.66786.qmail@web51604.mail.yahoo.com> Message-ID: <4fae7dfa0606081037x4e283ed9i3cef04858e9613b8@mail.gmail.com> There is a PyGTK package for win32, don't know if it uses cygwin or mingw but works pretty well on windows, it only needs the gtk runtime. http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ Altough I might been misunderstanding your question ;) On 6/8/06, Christopher Spears wrote: > Does PyGTK work well on cygwin? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cspears2002 at yahoo.com Fri Jun 9 05:15:51 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 8 Jun 2006 20:15:51 -0700 (PDT) Subject: [Tutor] What is a widget? Message-ID: <20060609031551.70362.qmail@web51601.mail.yahoo.com> I'm a bit embarassed to ask this...I am looking at a tutorial for PyGTK+ that is discussing widgets. What are widgets? -Chris From bgailer at alum.rpi.edu Fri Jun 9 05:20:48 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 08 Jun 2006 20:20:48 -0700 Subject: [Tutor] What is a widget? In-Reply-To: <20060609031551.70362.qmail@web51601.mail.yahoo.com> References: <20060609031551.70362.qmail@web51601.mail.yahoo.com> Message-ID: <4488E910.6040605@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060608/771436c6/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: show Type: image/gif Size: 43 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060608/771436c6/attachment.gif From starredheeler at hotmail.com Fri Jun 9 09:52:42 2006 From: starredheeler at hotmail.com (Desk Jet) Date: Fri, 09 Jun 2006 02:52:42 -0500 Subject: [Tutor] layout ( i guess) Message-ID: uh ive been wondering if with python you would be able to make layouts? _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From etrade.griffiths at dsl.pipex.com Fri Jun 9 11:42:03 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Fri, 09 Jun 2006 10:42:03 +0100 Subject: [Tutor] Confused about globals Message-ID: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com> Hi I have a series of python programs that plot stuff using PYX. Common to these is the need to read in a list of (well) locations in (X,Y) coords so I put that code in a separate module called shared_funcs.py. The coords are stored in dictionaries which I want to use later in the "main" program - every time I find a well with data, I can get the well's (x,y) coords by looking up the well name in the dictionary. The code snippet looks like this: === main.py ==== # define coord dictionaries for global use DE={} DN={} import shared_funcs() shared_funcs.get_xy_data() # Get coords from file ... do plotting stuff === shared_funcs.py === def get_xy_data(): in_file=open("well_xy.txt","r") for line in in_file L=line.split() well=L[0] x=L[1] y=L[2] DE[well]=x DN[well]=y in_file.close() The problem is that DE and DN appear not to be accessible to get_xy_data - presumably this is because shared_funcs.py and main.py don't share the same scope. So, is there any way to let get_xy_data change DE and DN? I guess the obvious way is to pass them to get_xy_data as arguments - but is there a more "pythonic" method? Thanks in advance! From kent37 at tds.net Fri Jun 9 12:04:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 06:04:53 -0400 Subject: [Tutor] layout ( i guess) In-Reply-To: References: Message-ID: <448947C5.1010501@tds.net> Desk Jet wrote: > uh ive been wondering if with python you would be able to make layouts? What's a layout? For a web site, magazine page, printed circuit board... Kent From RPhillips at engineer.co.summit.oh.us Fri Jun 9 13:17:02 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 09 Jun 2006 07:17:02 -0400 Subject: [Tutor] making a python program part of xhtml Message-ID: >>> Emily Fortuna < emily.fortuna at nist.gov > 6/8/2006 9:19 AM >>> Hola everyone, I'm working on creating a webpage in which a user can submit data into fields to be held in a database (there are other details, but this is the gist of the idea), and I need to use python. I am unfamiliar with manipulating data and web apps as a whole (and new to python), so I have been encountering much unfamiliar terrain. I _think_ I want to somehow embed the python into the page, but I'm really not sure how to do it. After googling I found some programs that generate xhtml from python, but I don't think that is what I want, or is it? Your help is appreciated! Emily You might look at http://karrigell.sourceforge.net/: karrigell lets you embed python in xhtml, xhtml in python, execute straight python scripts, or execute python from a karrigell application server. Even if you don't choose karrigell for some reason, at least the documentation can help you sort out the variations on the python/xhtml theme! Ron From kieran.flanagan at gmail.com Fri Jun 9 14:52:23 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Fri, 9 Jun 2006 13:52:23 +0100 Subject: [Tutor] Maintain SessionID with AMARA Message-ID: Hi I want to have a script that can browse through a website and retrieve information upon request. If I use AMARA for this, in the form i.e. for subtree in binderytools.pushbind('panel', source='file1.xml'): print subtree.name And then once on this page 'file1.xml', need to peform an ACTION to change the page to file2.xml and retrieve information from there. How can I do the following: 1. Peform the actionURL using AMARA so it returns a different xml screen that I can parse i.e. peforms a click of a URL and then parses the resulting xml. 2. Maintain the sessionID across different pages. Are there any examples of this ?. Thanks Kieran -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/c6b3add5/attachment.htm From dustin at ywlcs.org Fri Jun 9 16:19:42 2006 From: dustin at ywlcs.org (Dustin Mitchell) Date: Fri, 9 Jun 2006 09:19:42 -0500 Subject: [Tutor] Confused about globals In-Reply-To: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com> References: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com> Message-ID: As a note, the "import" should be import shared_funcs In Python, most globals aren't really global -- they're local to the module. If you split your modules by functionality, then variables should naturally relate to a specific module, and be located there. So, for example, you could move those global variables to shared_funcs.py, renamed to wells.py: === wells.py == DE={} DN={} def get_xy_data(): in_file=open("well_xy.txt","r") for line in in_file L=line.split() well=L[0] x=L[1] y=L[2] DE[well]=x DN[well]=y in_file.close() def lookup_well(well): return (DE.get(well, None), DN.get(well, None)) === main.py === import wells def func_that_needs_wells(): ... for e n wells.DE.keys(): ... ... etc. On Jun 9, 2006, at 4:42 AM, Etrade Griffiths wrote: > Hi > > I have a series of python programs that plot stuff using PYX. Common > to > these is the need to read in a list of (well) locations in (X,Y) > coords so > I put that code in a separate module called shared_funcs.py. The > coords > are stored in dictionaries which I want to use later in the "main" > program > - every time I find a well with data, I can get the well's (x,y) > coords by > looking up the well name in the dictionary. The code snippet looks > like this: > > === main.py ==== > > # define coord dictionaries for global use > > DE={} > DN={} > > import shared_funcs() > > shared_funcs.get_xy_data() # Get coords from file > > ... do plotting stuff > > > === shared_funcs.py === > > def get_xy_data(): > in_file=open("well_xy.txt","r") > for line in in_file > L=line.split() > well=L[0] > x=L[1] > y=L[2] > > DE[well]=x > DN[well]=y > in_file.close() > > The problem is that DE and DN appear not to be accessible to > get_xy_data - > presumably this is because shared_funcs.py and main.py don't share the > same > scope. So, is there any way to let get_xy_data change DE and DN? I > guess > the obvious way is to pass them to get_xy_data as arguments - but is > there > a more "pythonic" method? Thanks in advance! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Jun 9 16:44:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 10:44:42 -0400 Subject: [Tutor] Confused about globals In-Reply-To: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com> References: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com> Message-ID: <4489895A.4010106@tds.net> Etrade Griffiths wrote: > Hi > > I have a series of python programs that plot stuff using PYX. Common to > these is the need to read in a list of (well) locations in (X,Y) coords so > I put that code in a separate module called shared_funcs.py. The coords > are stored in dictionaries which I want to use later in the "main" program > - every time I find a well with data, I can get the well's (x,y) coords by > looking up the well name in the dictionary. You don't need a global variable in shared_funcs.get_xy_data() at all. It is reading a file and creating two dicts. I would write it to create and return the dicts. Then you can save them where you like in the caller. Also, I would use one dict whose values are (x, y) pairs, rather than two parallel dicts. Then your code looks like this: === shared_funcs.py === def get_xy_data(): D = {} in_file=open("well_xy.txt","r") for line in in_file L=line.split() well=L[0] x=L[1] y=L[2] D[well]=(x, y) in_file.close() return D === main.py === import shared_funcs D = shared_funcs.get_xy_data() though I suggest a more descriptive name than D... If there are other related bits of data or operations other than lookup, that might point to using a class to wrap the dict, the other data and operations. Kent From kermit at polaris.net Fri Jun 9 16:48:46 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 9 Jun 2006 10:48:46 -0400 (Eastern Daylight Time) Subject: [Tutor] file attribute of module Message-ID: <44898A4E.00001D.00376@YOUR-4105E587B6> Message: 2 Date: Thu, 08 Jun 2006 09:28:27 -0400 From: Kent Johnson Subject: Re: [Tutor] module versus file Most modules do have corresponding files. The exceptions are the ones built-in to Python. In fact modules have a __file__ attribute that tells you where it came from; try typing factor30.__file__ Kent ******* >>> import factor30 >>> factor30._file_ Traceback (most recent call last): File "", line 1, in -toplevel- factor30._file_ AttributeError: 'module' object has no attribute '_file_' >>> >>> factor30.__file__ 'c:\\math\\factoring\\factor30.py' >>> Ok. Now I understand it. The module is named factor30. The file is named factor30.py I presume that if I created another library in the same directory in a file named factor31.py that it would create a module named factor31. ??? From kent37 at tds.net Fri Jun 9 17:02:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 11:02:44 -0400 Subject: [Tutor] file attribute of module In-Reply-To: <44898A4E.00001D.00376@YOUR-4105E587B6> References: <44898A4E.00001D.00376@YOUR-4105E587B6> Message-ID: <44898D94.4030405@tds.net> Kermit Rose wrote: >>>> factor30.__file__ > 'c:\\math\\factoring\\factor30.py' > > Ok. Now I understand it. > > The module is named factor30. > > The file is named factor30.py > > I presume that if I created another library in the same directory > in a file named factor31.py > that it would create a module named factor31. ??? Yes. Try it and see! Kent From paul.kraus at gmail.com Fri Jun 9 17:02:50 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 11:02:50 -0400 Subject: [Tutor] pyexcelerator Message-ID: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> Are their docs anywhere for pyexcelerator? the built in docs are a bit lacking. For instance I can't figure out how to set a column width. I am just reading the examples and they kind of help but I don't follow this ... ws.col(i).width = 0x0d00 + i where i is an incrementing integer. so to me it reads if i = 0. set col 0's width to hexnumber plus 0 why the hex number? does it have to be written this way? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/bcf1f7db/attachment.htm From kent37 at tds.net Fri Jun 9 17:20:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 11:20:17 -0400 Subject: [Tutor] pyexcelerator In-Reply-To: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> Message-ID: <448991B1.3070505@tds.net> Paul D. Kraus wrote: > Are their docs anywhere for pyexcelerator? the built in docs are a bit > lacking. > > For instance I can't figure out how to set a column width. > I am just reading the examples and they kind of help but I don't follow > this ... > > ws.col(i).width = 0x0d00 + i > > where i is an incrementing integer. > so to me it reads if i = 0. > > set col 0's width to hexnumber plus 0 > > why the hex number? does it have to be written this way? Maybe just try without the 0x0d00 and see what happens? or try the pyExcelerator mailing list on SourceForge... Kent From doug.shawhan at gmail.com Fri Jun 9 17:46:25 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 9 Jun 2006 10:46:25 -0500 Subject: [Tutor] errno vs. sys.exc_info Message-ID: <5e1ceb8a0606090846s1dc4f45ei52ec6ecf851d9faf@mail.gmail.com> I am in need of a clear way to return exceptions within a try loop. I have been looking at both errno and sys.exc_info. I know that using errno is not encouraged in threaded programs, but this is no big deal for my purposes. I found a good, clear example for translating the rather cryptic output from sys.exc_info: def formatExceptionInfo(maxTBlevel=5): cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__["args"] except KeyError: excArgs = "" excTb = traceback.format_tb(trbk, maxTBlevel) return (excName, excArgs, excTb) Which seems to cover most of the bases, but I have yet to find a good example of using errno. Can someone provide a quick cut? :-) Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/be906a2c/attachment.htm From dkuhlman at rexx.com Fri Jun 9 17:57:59 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 9 Jun 2006 08:57:59 -0700 Subject: [Tutor] making a python program part of xhtml In-Reply-To: References: Message-ID: <20060609155759.GA90220@cutter.rexx.com> On Fri, Jun 09, 2006 at 07:17:02AM -0400, Ron Phillips wrote: > >>> Emily Fortuna < emily.fortuna at nist.gov > 6/8/2006 9:19 AM >>> [snip] > ... I _think_ I want to somehow > embed the python into the page, but I'm really not sure how to do it. > After googling I found some programs that generate xhtml from python, > but I don't think that is what I want, or is it? Your help is > appreciated! > Emily > > You might look at http://karrigell.sourceforge.net/: karrigell lets you > embed python in xhtml, xhtml in python, execute straight python scripts, > or execute python from a karrigell application server. Even if you don't > choose karrigell for some reason, at least the documentation can help > you sort out the variations on the python/xhtml theme! > You may also want to visit the following Web page, then scroll down and look for "Templating Engines": http://wiki.python.org/moin/WebProgramming Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From mail.roma1 at gmail.com Fri Jun 9 18:20:25 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Fri, 9 Jun 2006 18:20:25 +0200 Subject: [Tutor] layout ( i guess) Message-ID: <6122a57a0606090920m5e13cab8i5e91d9eefb43c5e3@mail.gmail.com> Desk Jet wrote: > uh ive been wondering if with python you would be able to make layouts? Hello,I premise that i don't get the exact meaning you are using for 'layouts',GUI-enabled applications (i.e. those with windows,buttons,progress bars,notebooks..) could it be? Well,sure Python can :) In the majority of case,programming graphical user interfaces will require you to install additional packages,but there is one that comes along with Python : Tkinter. Cheers, Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/d87384e6/attachment.html From paul.kraus at gmail.com Fri Jun 9 19:34:32 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 13:34:32 -0400 Subject: [Tutor] pyexcelerator In-Reply-To: <448991B1.3070505@tds.net> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> <448991B1.3070505@tds.net> Message-ID: <4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com> > > > Maybe just try without the 0x0d00 and see what happens? or try the > pyExcelerator mailing list on SourceForge... Mailing list looks dead only 2 messages. Man this is the exact module i need to finish converting about 20 scripts from perl and I have no idea how to use most of it. This is very frustrating. Is there another excel writer module that has documentation? Or on a broader topic is their a CPAN equivalent? Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/4becd62d/attachment.html From Barry.Carroll at psc.com Fri Jun 9 19:33:24 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 9 Jun 2006 10:33:24 -0700 Subject: [Tutor] Files and Modules Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B5@eugsrv400.psc.pscnet.com> Kermit: > ------------------------------ > > Message: 7 > Date: Fri, 09 Jun 2006 11:02:44 -0400 > From: Kent Johnson > Subject: Re: [Tutor] file attribute of module > Cc: tutor at python.org > Message-ID: <44898D94.4030405 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Kermit Rose wrote: > >>>> factor30.__file__ > > 'c:\\math\\factoring\\factor30.py' > > > > Ok. Now I understand it. > > > > The module is named factor30. > > > > The file is named factor30.py > > > > I presume that if I created another library in the same directory > > in a file named factor31.py > > that it would create a module named factor31. ??? > > Yes. Try it and see! > > Kent > If by "it" you mean "Python", you are correct. As you are finding out, the distinction between 'file' and 'module' in Python is subtle but important. The words are often used synonymously, but they actually have very different meanings. Here is the best short description I have found of the distinction. It is from Learning Python, 2nd Edition By David Ascher, Mark Lutz Publisher: O'Reilly Modules are probably best understood as simply packages of names-places to define names you want to make visible to the rest of a system. In Python, modules are a namespace-a place where names are created. Names that live in a module are called its attributes. Technically, modules usually correspond to files, and Python creates a module object to contain all the names assigned in the file; but in simple terms, modules are just namespaces. So, in your example above, Python uses the contents of the file "factor31.py" to create the module "factor31". As others have hinted, Python can use things other than files, and types of files other than "???.py", to make a module, but you don't need to worry about that yet. HTH. Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Fri Jun 9 19:52:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 13:52:53 -0400 Subject: [Tutor] pyexcelerator In-Reply-To: <4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> <448991B1.3070505@tds.net> <4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com> Message-ID: <4489B575.3080809@tds.net> Paul D. Kraus wrote: > > Maybe just try without the 0x0d00 and see what happens? or try the > pyExcelerator mailing list on SourceForge... > > > Mailing list looks dead only 2 messages. > Man this is the exact module i need to finish converting about 20 > scripts from perl and I have no idea how to use most of it. This is very > frustrating. > > Is there another excel writer module that has documentation? If you are running on Windows and have Excel installed you can talk to Excel using COM. Take a look here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html If no one on tutor knows about this you can probably get help with COM on the python-win32 list or comp.lang.python. Kent From jeffpeery at yahoo.com Fri Jun 9 20:06:38 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri, 9 Jun 2006 11:06:38 -0700 (PDT) Subject: [Tutor] numpy speed problems Message-ID: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com> hello, I am having some trouble with the speed of numpy. I'm crunching some numbers (see the attached script) and in total I have 1,000,000 grid points over which I am integrating. I'm doing a bunch of adding, mulitply, divide, powers, etc, but in total there are 1,000,000 points to do these operations over and it really shouldn't take this long... as far as I know. my last simulation took about 8+ hours. What might I be doing wrong in my code to cause this to be so slow? big thanks!! Jeff __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e24716e2/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: HW 5c.py Url: http://mail.python.org/pipermail/tutor/attachments/20060609/e24716e2/attachment.asc From bgailer at alum.rpi.edu Fri Jun 9 20:34:55 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 09 Jun 2006 11:34:55 -0700 Subject: [Tutor] pyexcelerator In-Reply-To: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> Message-ID: <4489BF4F.7000102@alum.rpi.edu> Paul D. Kraus wrote: > Are their docs anywhere for pyexcelerator? the built in docs are a bit > lacking. > > For instance I can't figure out how to set a column width. > I am just reading the examples and they kind of help but I don't > follow this ... > > ws.col(i).width = 0x0d00 + i > > where i is an incrementing integer. > so to me it reads if i = 0. > > set col 0's width to hexnumber plus 0 > > why the hex number? does it have to be written this way? Nothing has to be written in hex. Judging from some of the modules the author used hex a lot. I just looked at my copy of PyExcelerator. It seems to be in poor shape. I tried running some of the modules that have if __name__ == '__main__': (i.e. self-testing) and they failed with errors! And I find no visible documentation or working examples. Sigh. The only thing I've used it for is parsing an existing Excel Workbook. -- Bob Gailer 510-978-4454 From cspears2002 at yahoo.com Fri Jun 9 20:35:45 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 9 Jun 2006 11:35:45 -0700 (PDT) Subject: [Tutor] problems using PyGTK on cygwin Message-ID: <20060609183545.74165.qmail@web51609.mail.yahoo.com> I have been trying to work throught the PyGTK tutorial using cygwin, but I have been having problems. For example when I try to launch the helloworld.py program (http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html#sec-HelloWorld), I get this: $ python helloworld.py No fonts found; this probably means that the fontconfig library is not correctly configured. You may need to edit the fonts.conf configuration file. More information about fontconfig can be found in the fontconfig(3) manual page and on http://fontconfig.org I located the files, but the content is Greek to me! Likewise, I tried running pygtkconsole.py program (http://www.pygtk.org/pygtk2tutorial/examples/pygtkconsole.py) and got $ python pygtkconsole.py 5 [main] python2.4 1360 C:\cygwin\bin\python2.4.exe: *** fatal error - unable to remap C:\cygwin\usr\X11R6\bin\cygXcursor-1.dll to same address as parent(0x18870000) != 0x188A0000 6 [main] python 1588 child_copy: loaded dll data write copy failed, 0x60084000..0x60085150, done 0, windows pid 2286452, Win32 error 5 Traceback (most recent call last): File "pygtkconsole.py", line 119, in ? interact() File "pygtkconsole.py", line 101, in interact gi = GtkInterpreter() File "pygtkconsole.py", line 81, in __init__ child_pid = os.fork() OSError: [Errno 11] Resource temporarily unavailable Any suggestions? I have been seriously thinking of just downloading PyGTK for Windows instead of trying to run it in the faux Unix environment of cygwin. -Chris From bgailer at alum.rpi.edu Fri Jun 9 20:44:44 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 09 Jun 2006 11:44:44 -0700 Subject: [Tutor] pyexcelerator CORRECTION In-Reply-To: <4489BF4F.7000102@alum.rpi.edu> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> <4489BF4F.7000102@alum.rpi.edu> Message-ID: <4489C19C.10601@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/03abed3b/attachment.htm From paul.kraus at gmail.com Fri Jun 9 20:52:57 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 14:52:57 -0400 Subject: [Tutor] pyexcelerator In-Reply-To: <4489BF4F.7000102@alum.rpi.edu> References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com> <4489BF4F.7000102@alum.rpi.edu> Message-ID: <4e2aea430606091152sc5ac5a2rc9ed426daa4f75b3@mail.gmail.com> > > > > I just looked at my copy of PyExcelerator. It seems to be in poor shape. > I tried running some of the modules that have if __name__ == '__main__': > (i.e. self-testing) and they failed with errors! And I find no visible > documentation or working examples. Sigh. > You might want to check out the recent source from sourceforge its seems very functional and it has a bunch of examples. Not very useful for ones as far as I am concrened. I have not tried to run the modules by themselves. I hate the idea of having to pass or make a call to a perl script to handle the excel stuff its just seems wrong. I wish there was some kind of *open* format that i could write the spreadsheets to that both open office and excel 2000/2003 could read natively. Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/c31f1bdc/attachment.html From bgailer at alum.rpi.edu Fri Jun 9 20:57:32 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 09 Jun 2006 11:57:32 -0700 Subject: [Tutor] numpy speed problems In-Reply-To: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com> References: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com> Message-ID: <4489C49C.8040800@alum.rpi.edu> Jeff Peery wrote: > hello, I am having some trouble with the speed of numpy. I'm crunching > some numbers (see the attached script) and in total I have 1,000,000 > grid points over which I am integrating. I'm doing a bunch of adding, > mulitply, divide, powers, etc, but in total there are 1,000,000 points > to do these operations over and it really shouldn't take this long... > as far as I know. my last simulation took about 8+ hours. > > What might I be doing wrong in my code to cause this to be so slow? > big thanks!! I don't have time to analyze all your code but I'll point out that it is repeating some calculations many times. Example: x_coord[ii])**2.0 y_coord[jj])**2.0 are calculated every time GetPressure is called. I suggest you calculate these one time outside any loops and pass the result into GetPressure. Inside GetPressure: 1j*w_mn*rho exp(1j*k_mn*r)*dx*dy/(2.0*pi*r are repeatedly calculated inside the for loop. Move them out of the loop. Then look for other "loop invariants". sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j])) is another place to look. > > ------------------------------------------------------------------------ > > from numpy import * > > """ > function definitions > """ > def GetPressure(x_coord, y_coord, x_r, y_r, z_r, dx, dy, w_mn, rho, v_mn, k_mn, n, m): > # intialize pressure > p = 0.0 + 1j > > # sum contributions from all point sources to receiver > for ii in range(n): > for jj in range(m): > r = ((x_r - x_coord[ii])**2.0 + (y_r - y_coord[jj])**2.0 + (z_r - 0.0)**2)**0.5 > p += (1j*w_mn*rho*v_mn[ii][jj])*exp(1j*k_mn*r)*dx*dy/(2.0*pi*r) > > p = sqrt(p*conjugate(p)) > return abs(p) > > > """ > vaiables and constants > """ > > """problem definition parameter""" > n = arange(1,70) #mode number in x direction > m = arange(1,70) #mode number in y direction > mode_n = 10 #mode number - 1 > mode_m = 10 #mode number - 1 > L = 1.2 #piston length (m) > W = 0.6 #piston width (m) > > """material properties fluid""" > c = 343.0 #speed sound in water (m/s) > rho_a = 1.21 #density of air (kg/m^3) > > """piston material properties""" > E = 7.0e10 #youngs modulus (N/m^2) (stainless steel) > nu = 0.29 #poisson's ratio (stainless steel > rho = 2700.0 #density of piston (stainless steel) (kg/m^3) > t = 0.0015 #piston thickness (m) > > """wave speed, wave number, frequency""" > c_l = (E/(rho*(1 - nu**2)))**0.5 #longitudinal wave speed in piston > k_x = n*pi/W #wave number x direction > k_y = m*pi/L #wave number y direction > k_mn = (k_x[mode_n]**2 + k_y[mode_m]**2)**0.5 #bending wave number for n and m mode > w_c = (c**2)/(1.8*c_l*t) #critical frequency (Hz) > w_mn = (k_mn**2)*1.8*c_l*t/(2.0*pi)**2 #frequency for n and m (see notes 5/15/06) > k_c = 2.0*pi*(w_c/(1.8*c_l*t))**0.5 #critical wave number > k_a = 2.0*pi*w_mn/c #wave number in acoustic medium (air) > > """piston grid""" > dx = 1.0/k_a #x direction step in space (m) > dy = 1.0/k_a #y direction step in space (m) > > if dx < 0.005: > dx = 0.005 > dy = 0.005 > > num_y = int(L/dy) #number of nodes in y direction > num_x = int(W/dx) #number of nodes in x direction > > #piston grid coordinates > x_coord = arange(num_x, dtype=float)*W/num_x - W/2.0 > y_coord = arange(num_y, dtype=float)*L/num_y - L/2.0 > > """field grid""" > a = 1 > b = 50 > d = 50 > x_r = arange(a, dtype=float)*1.0/float(a) #x position of receiver (m) > y_r = arange(b, dtype=float)*1.0/float(b) #y position of receiver (m) > z_r = arange(d, dtype=float)*10.0/float(d) #z position of receiver (m) > > """acoustic variables""" > p = 0 #amplitude of pressure at receiver (Pa) > r = 0 #distance from origin to receiver (m) > p_field = zeros((a,b,d), dtype=float) #pressure field (m) > > """calculate piston surface velocity amplitude""" > U_mn = zeros((len(x_coord), len(y_coord)), dtype=float) > for i in range(len(x_coord)): > for j in range(len(y_coord)): > #amplitude of piston surface displacement > U_mn[i][j] = sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j])) > #amplitude of piston surface velocity (m/s) > V_mn = w_mn*U_mn > > > """ > numerical integration of Raleigh's equation > """ > for i in range(a): > for j in range(b): > for k in range(d): > p_field[i][j][k] = GetPressure(x_coord, y_coord, x_r[i], y_r[j], z_r[k], dx, dy, w_mn, rho, V_mn, k_mn, num_x, num_y) > print '%d Percent Complete'%(100.0*j/b) > > p_field = 20.0*log10(p_field) > > fileHandle = file('beam pattern.dat', "w") > fileHandle.write('TITLE = "HW 4"\n') > fileHandle.write('VARIABLES = "x"\n"y"\n"z"\n"pressure"\n') > fileHandle.write('ZONE T="%s"\n' % 'pressure field') > fileHandle.write('I=%d, J=1, ZONETYPE=Ordered\n' % (a*b*d)) > fileHandle.write('DATAPACKING=POINT DT=(DOUBLE DOUBLE DOUBLE DOUBLE)\n') > for ii in range(a): > for jj in range(b): > for kk in range(d): > fileHandle.write('%f %f %f %f\n' % (x_r[ii], y_r[jj], z_r[kk], p_field[ii][jj][kk])) > fileHandle.close() > > > > """ > contour of surface velocity > """ > > fileHandle = file('mode shape.dat', "w") > fileHandle.write('TITLE = "HW 4"\n') > fileHandle.write('VARIABLES = "x"\n"y"\n"velocity"\n') > fileHandle.write('ZONE T="%s"\n' % 'velocity field') > fileHandle.write('I=%d, J=1, ZONETYPE=Ordered\n' % (num_y*num_x)) > fileHandle.write('DATAPACKING=POINT DT=(DOUBLE DOUBLE DOUBLE)\n') > for ii in range(num_x): > for jj in range(num_y): > fileHandle.write('%f %f %f\n' % (x_coord[ii], y_coord[jj], V_mn[ii][jj])) > fileHandle.close() > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From 3dbernard at gmail.com Fri Jun 9 21:38:58 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 9 Jun 2006 15:38:58 -0400 Subject: [Tutor] Difference between popens Message-ID: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> Hi, I'd like to know what are the differences at the various os.popenX flavors. I read the documentation and I can see they return file objects..... so what can you do with these file objects? I mean, why would you need a set of file objects rather than another? Sorry the difference is very not clear to me. Thanks Bernard From michael at espersunited.com Fri Jun 9 21:42:25 2006 From: michael at espersunited.com (Michael Sullivan) Date: Fri, 09 Jun 2006 14:42:25 -0500 Subject: [Tutor] An Introduction and a question Message-ID: <1149882145.10792.37.camel@camille.espersunited.com> My name is Michael Sullivan. I am a 26 year-old college student in Oklahoma. My wife and I have a small (three PCs) computer network that we operate out of our home. We have our own domain (as one could tell by examining my email address) I have novice-level experience with VB, C/C++, Java, and PHP, but I'm just starting out with Python. Here's the situation: My wife likes to play the game Chuzzle, found at Yahoo Games. We use primarily Linux, however Chuzzle is written as an ActiveX control, which only works on Windows. I have not been able to get Internet Explorer to work correctly through Wine, so I determined to write a Chuzzle-like game (with many of my own enhancements) for Linux. I've been playing around with some Pygame examples lately, and thought that I'd try writing the game in Python (I've been meaning to learn Python for years, but just never got around to it.) Today I started on writing the game. I've decided (at least for now) to call my version, LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic concept: There are individual pieces of different colors arranged on a grid. The pieces can be moved on a line either vertically or horizontally. The object of the game is to position three similarly colored pieces ajacent to each other. At this point the three pieces will disappear, and the pieces above them will fall to take their place. As the levels progress, locks are added so that the player cannot move a locked piece either horizontally or vertically. The game is over when no more pieces can be removed. I started my script by creating a class called LinePuzzlePiece which represents a single coloured piece. I wanted a random colour chosen from a list to be assigned to the piece, and then to prove that I had it set up correctly, I wanted to call a method that would print out the color of the piece. Here is my code: #!/usr/bin/env python import random import time import math class LinePuzzlePiece: """This class defines a single playing piece for LinePuzzle""" def __init__(self): seed(time) index = int(math.floor(uniform(1, 10))) colorlist = ["red", "blue", "green" "yellow", "purple"] self.color = colorlist[index] def printcolor(): print self.color mypiece = LinePuzzlePiece mypiece.printcolor I saved the script and made it chmod +x. However, when I run it, I get this: michael at camille ~ $ ./linepuzzle.py michael at camille ~ $ Now, I'm no expert, but I really think something should have been printed, if even a blank line. What am I doing wrong here? Why is nothing printing? Is my printcolor method even being called successfully? -Michael Sullivan- From andre.roberge at gmail.com Fri Jun 9 22:00:48 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Fri, 9 Jun 2006 17:00:48 -0300 Subject: [Tutor] An Introduction and a question In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> Message-ID: <7528bcdd0606091300p2bd41ee6je99c14b153a3565b@mail.gmail.com> On 6/9/06, Michael Sullivan wrote: > My name is Michael Sullivan. I am a 26 year-old college student in > Oklahoma. My wife and I have a small (three PCs) computer network that > we operate out of our home. We have our own domain (as one could tell > by examining my email address) I have novice-level experience with VB, > C/C++, Java, and PHP, but I'm just starting out with Python. > > Here's the situation: My wife likes to play the game Chuzzle, found at > Yahoo Games. We use primarily Linux, however Chuzzle is written as an > ActiveX control, which only works on Windows. I have not been able to > get Internet Explorer to work correctly through Wine, so I determined to > write a Chuzzle-like game (with many of my own enhancements) for Linux. > I've been playing around with some Pygame examples lately, and thought > that I'd try writing the game in Python (I've been meaning to learn > Python for years, but just never got around to it.) Today I started on > writing the game. I've decided (at least for now) to call my version, > LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic > concept: There are individual pieces of different colors arranged on a > grid. The pieces can be moved on a line either vertically or > horizontally. The object of the game is to position three similarly > colored pieces ajacent to each other. At this point the three pieces > will disappear, and the pieces above them will fall to take their place. > As the levels progress, locks are added so that the player cannot move a > locked piece either horizontally or vertically. The game is over when > no more pieces can be removed. > > I started my script by creating a class called LinePuzzlePiece which > represents a single coloured piece. I wanted a random colour chosen > from a list to be assigned to the piece, and then to prove that I had it > set up correctly, I wanted to call a method that would print out the > color of the piece. Here is my code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > seed(time) > index = int(math.floor(uniform(1, 10))) colorlist = ["red", > "blue", "green" "yellow", "purple"] self.color = colorlist[index] > > def printcolor(): > print self.color > > mypiece = LinePuzzlePiece > mypiece.printcolor > 1. try mypiece.printcolor() instead. 2. I'm cc-ing the pygame user group. I suggest that future questions related to pygame be sent over to that group instead. They are just as friendly as the folks on the tutor list. Andr? > > I saved the script and made it chmod +x. However, when I run it, I get > this: > > michael at camille ~ $ ./linepuzzle.py > michael at camille ~ $ > > Now, I'm no expert, but I really think something should have been > printed, if even a blank line. What am I doing wrong here? Why is > nothing printing? Is my printcolor method even being called > successfully? > -Michael Sullivan- > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Jun 9 22:08:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Jun 2006 16:08:25 -0400 Subject: [Tutor] An Introduction and a question In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> Message-ID: <4489D539.9020402@tds.net> Michael Sullivan wrote: > Here is my code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > seed(time) > index = int(math.floor(uniform(1, 10))) colorlist = ["red", > "blue", "green" "yellow", "purple"] self.color = colorlist[index] > > def printcolor(): > print self.color > > mypiece = LinePuzzlePiece > mypiece.printcolor > > > I saved the script and made it chmod +x. However, when I run it, I get > this: > > michael at camille ~ $ ./linepuzzle.py > michael at camille ~ $ > > Now, I'm no expert, but I really think something should have been > printed, if even a blank line. What am I doing wrong here? Why is > nothing printing? Is my printcolor method even being called > successfully? No, you have not created a LinePuzzlePiece or called printcolor. In Python, parentheses are required for function calls. A class or function name without the parentheses is a reference to the class or function object itself, not a call to the object. This can be very useful but it's not what you want! mypiece = LinePuzzlePiece # This makes mypiece refer to the class, not an instace mypiece.printcolor # This is a reference to a method of the class, but you don't do anything with the reference What you really want: mypiece = LinePuzzlePiece() mypiece.printcolor() Kent From paul.kraus at gmail.com Fri Jun 9 22:41:40 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 16:41:40 -0400 Subject: [Tutor] Function list that might have a tuple that might have one of its indexs set to 's' Message-ID: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com> I am writing my first python program(at least in a really long time). Its purpose is to take csv or pipe delimintaed files and convert them to html pages. Was going to be excel but its just not worth the headache. Everyone viewing the reports is doing just that viewing simple tables. I need to scan through a list that contains headers to my table. If one of the elements is a tuple and one of the elements of the tuple is "s" set self.sort to the index of the tuple in the header list and then replace the element in header with a two field tuple containing everything that was not 's'. header = ['my first column',('my second num column','s','r'),(' my third num column','r') ] I pass header to a function actually a method but lets pretend its just a plain old function. Be careful reading the below code may cause random strokes. I have woken up twice laying on the floor disoriented.... :) Actual code in my working example used to call function ... report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header): list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's': self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append (header[cindex][tindex]) header[cindex] = tuple(list) self.header = header -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/af757925/attachment.htm From dkuhlman at rexx.com Fri Jun 9 23:26:52 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 9 Jun 2006 14:26:52 -0700 Subject: [Tutor] Difference between popens In-Reply-To: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> Message-ID: <20060609212652.GB92694@cutter.rexx.com> On Fri, Jun 09, 2006 at 03:38:58PM -0400, Bernard Lebel wrote: > Hi, > > I'd like to know what are the differences at the various os.popenX > flavors. I read the documentation and I can see they return file > objects..... so what can you do with these file objects? I mean, why > would you need a set of file objects rather than another? > See documentation at http://docs.python.org/lib/os-newstreams.html#l2h-1552. And, notice how the return values from the various versions of popen are different file types: stdin, stdout, and stderr. A summary: - popen() gives you either an input pipe (stdin) or an output pipe (stdout) but not both. - popen2() gives you both an input pipe (stdin) and output pipe (stdout). - popen3() gives you an input pipe (stdin) and output pipe (stdout) and an error pipe (stderr). - popen4() gives you an input pipe and a pipe that combines output and errors (stdout and stderr). Specifically, if you want to run a command, just like you would with os.system(), but: 1. You want to *either* feed (pipe) text to your command *or* read results from your command, use os.popen() and use mode= 'w' or 'r'. 2. You want to both feed (pipe) text to your command *and* read results from your command, use os.popen2(). Etc. If you get an input pipe, you should write text to that pipe, then close that stream. Doing close() is what triggers execution of the command. If you get an output pipe, then (after the command runs), read from that pipe to get the results of your command (i.e. the text that the command wrote to stdout). Here is a simple example that uses popen2:: import os def test(): instream, outstream = os.popen2('grep dave') instream.write('Line #1\n') instream.write('Line #2 dave is here\n') instream.write('Line #3\n') instream.write('Line #4 dave is also here\n') instream.write('Line #5\n') instream.close() for line in outstream: print 'Line: %s' % line.rstrip() test() Note that there is also a popen module, which has functions with the same names and functionality: "This functionality is also available in the popen2 module using functions of the same names, but the return values of those functions have a different order." See: http://docs.python.org/lib/module-popen2.html Hope this helps. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From 3dbernard at gmail.com Fri Jun 9 23:27:37 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 9 Jun 2006 17:27:37 -0400 Subject: [Tutor] Difference between popens In-Reply-To: <7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com> References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> <7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com> Message-ID: <61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com> Hey, thanks for the nice explanation Michael! Bernard On 6/9/06, Michael P. Reilly wrote: > Excuse the slightly pedantic discussion before I get to a real-world > example, but the differences get into something a bit deeper than Python and > into what is called "interprocess communication". Each program that's > running has an input data stream and an output data steam and on many modern > computer systems there is a third stream for error messages. The idea is > that the program doesn't need to know that the input is coming from a user > or a keyboard; it could be coming from a file or another program - the > program shouldn't care. The same thing with the output and the error > messages. > > These three data streams have traditionally been called "stdin" (standard > input), "stdout" (standard output) and "stderr" (standard error). And in > Python, they are known by the same names in the 'sys' module. > > Now before I said that the concept of these is that the program should not > care where its data is going to or coming from, including another program. > This is where interprocess communication comes into play. Specifically, > this is accomplished with a data construct called "pipes" (the name 'popen' > comes from "pipe open" in the C world, akin to 'fopen' for "file open"). > Pipes are created between the programs to redirect data between inputs and > outputs. The most well known and viewed form of this is the vertical bar > "|" on command-lines in UNIX, then DOS had to adopt it: type README.txt | > more. > > Back to the question at hand: why and how would you use the files returned. > Let's say you have a large dictionary of values in your Python program, and > the system has a very nice spelling program out there. You would like to > use that program so you don't have to write you own routine. How the > spelling program is normally called is that words are sent to its standard > input (stdin) stream, separated by newlines, and the misspelled words are > printed on its stdout, also separated by newlines. We want to start the > program (called "spawning"), write our dictionary values to its stdin and > read its stdout. For this, we need to gain access to the program's stdin > and stdout. Since we are spawning it, it is called our "child" process. > > def verify_dictionary(dict_o_words): > reverse_dict = {} # to get back to the keys > (child_stdin, child_stdout) = os.popen2('spell') > for (key, value) in dict_o_words.items(): > if reverse_dict.has_key(value): > reverse_dict[value].append(key) > else: > reverse_dict[value] = [key] > child_stdin.write('%s\n' % value) > child_stdin.close() # close the data stream to tell other program we're > finished > misspellings = [] > for line in child_stdout.readlines(): > value = line.strip() > if reverse_dict.has_key(value): > misspellings.extend(reverse_dict[value]) > close_stdout.close() # tells other program we're finished reading from > it > return misspellings > > I hope this discussion answers your questions and hasn't been too beneath > you. :) Some of it might be arcane history now, but I always feel it is > good to know the roots to understand where you are going. > -Michael > > > On 6/9/06, Bernard Lebel <3dbernard at gmail.com> wrote: > > > Hi, > > I'd like to know what are the differences at the various os.popenX > flavors. I read the documentation and I can see they return file > objects..... so what can you do with these file objects? I mean, why > would you need a set of file objects rather than another? > > Sorry the difference is very not clear to me. > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- > There's so many different worlds, > So many different suns. > And we have just one world, > But we live in different ones. From michael at espersunited.com Fri Jun 9 23:28:43 2006 From: michael at espersunited.com (Michael Sullivan) Date: Fri, 09 Jun 2006 16:28:43 -0500 Subject: [Tutor] An Introduction and a question (continuing) In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> Message-ID: <1149888523.10792.50.camel@camille.espersunited.com> OK. I've got it working this far. Now I want the script to generate eight pieces, each with a random colour. Here's my current code: #!/usr/bin/env python import random import time import math class LinePuzzlePiece: """This class defines a single playing piece for LinePuzzle""" def __init__(self): random.seed(time) index = int(math.floor(random.uniform(0, 8))) colorlist = ["red", "blue", "green", "yellow", "purple", "cyan", "orange", "white"] self.color = colorlist[index] def printcolor(self): print self.color piececount = 0 mypiece = ["", "", "", "", "", "", "", "", ""] while (piececount < 9): mypiece[piececount] = LinePuzzlePiece() mypiece[piececount].printcolor() piececount += 1 The problem is that while eight pieces are created and assigned a colour, the colour is always the same. I need the colours of the pieces to be in a somewhat random order. What am I doing wrong? From dkuhlman at rexx.com Fri Jun 9 23:33:18 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 9 Jun 2006 14:33:18 -0700 Subject: [Tutor] numpy speed problems In-Reply-To: <4489C49C.8040800@alum.rpi.edu> References: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com> <4489C49C.8040800@alum.rpi.edu> Message-ID: <20060609213318.GC92694@cutter.rexx.com> On Fri, Jun 09, 2006 at 11:57:32AM -0700, Bob Gailer wrote: > Jeff Peery wrote: > > hello, I am having some trouble with the speed of numpy. I'm crunching > > some numbers (see the attached script) and in total I have 1,000,000 > > grid points over which I am integrating. I'm doing a bunch of adding, > > mulitply, divide, powers, etc, but in total there are 1,000,000 points > > to do these operations over and it really shouldn't take this long... > > as far as I know. my last simulation took about 8+ hours. > > > > What might I be doing wrong in my code to cause this to be so slow? > > big thanks!! > I don't have time to analyze all your code but I'll point out that it is > repeating some calculations many times. Example: > > x_coord[ii])**2.0 > y_coord[jj])**2.0 > > > are calculated every time GetPressure is called. I suggest you calculate > these one time outside any loops and pass the result into GetPressure. > > Inside GetPressure: > > 1j*w_mn*rho > exp(1j*k_mn*r)*dx*dy/(2.0*pi*r > > > are repeatedly calculated inside the for loop. Move them out of the loop. > > Then look for other "loop invariants". > > sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j])) > > is another place to look. > Also, if you are serious about SciPy, NumPy, etc, be sure to visit http://scipy.org/, *and* check into the mailing lists there. That's not just for your benefit; if there are problems with SciPy, the people at that list will want to know about them. [snip] Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From mail.roma1 at gmail.com Sat Jun 10 00:05:34 2006 From: mail.roma1 at gmail.com (Ivan Furone) Date: Sat, 10 Jun 2006 00:05:34 +0200 Subject: [Tutor] Fwd: Difference between popens In-Reply-To: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> Message-ID: <6122a57a0606091505p378d2edw279cbef337ae7da3@mail.gmail.com> 2006/6/9, Bernard Lebel <3dbernard at gmail.com>: > > Hi, > > I'd like to know what are the differences at the various os.popenX > flavors. I read the documentation and I can see they return file > objects..... so what can you do with these file objects? I mean, why > would you need a set of file objects rather than another? > > Sorry the difference is very not clear to me. > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hello, The common idea behind the various popen implementation is to provide the creation of pipes.A pipe is a flavor of a file object.A pipe serves the job to address data from a process to another,but what if sometimes you want to execute a command out of the parent process on a child process?You should be able to issue the command,catch the result and even to know which way the thing has ended,at times. If you are familiar with the concept of 'streams',the "input","output" and "error" stream are the resource of communication provided by Unix to handle these tasks,respectively.Nevertheless,at times you don't need to gather data from all the streams,but just to control two of them out of three,for example.The reason could be that of sparing system resources,time or just that you don't need or want to.popen2,popen3 and popen4 are designed to catch exactly the streams you want to control.So: popen2: returns the file objects corresponding to the child stdin and stdout; popen3: returns the file objects corresponding to the child stdin,stdout and stderr; popen4: returns the file objects corresponding to the child stdout and stderr (together as a single object) and stdin. The file objects,you see,are what you normally make use to manipulate data within processes. They are memory structures which assume peculiar names based on their type : Queues,Semaphores,Pipes and so on... And they can persist a) in the scope of a process b) of a machine session c) on the filesystem (the strongest kind of persistence). Choosing the right one for each task a matter depending on what you want to do with them. I recognize I'm not being exhaustive but hope that helps. Cheers, Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060610/49c8ba12/attachment.html From python at venix.com Sat Jun 10 00:10:28 2006 From: python at venix.com (Python) Date: Fri, 09 Jun 2006 18:10:28 -0400 Subject: [Tutor] An Introduction and a question (continuing) In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> <1149888523.10792.50.camel@camille.espersunited.com> Message-ID: <1149891028.24742.204.camel@www.venix.com> On Fri, 2006-06-09 at 16:28 -0500, Michael Sullivan wrote: > OK. I've got it working this far. Now I want the script to generate > eight pieces, each with a random colour. Here's my current code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > random.seed(time) The seed allows you to reuse a particular set of random numbers - which can be highly useful in testing so that successive runs use the same numbers. In general, there is no need to call seed. You are calling seed with the same value every time, a reference to the time module. You really wanted: random.seed(time.time()) I'd recommend simply deleting the call to random.seed. If you do find you want to re-use the same set of "random" numbers, call seed once right after you import random with a known value. If your computer really needs to call seed to randomize effectively, then you can try seeding with time.time(). > index = int(math.floor(random.uniform(0, 8))) > colorlist = ["red", "blue", "green", "yellow", "purple", "cyan", > "orange", "white"] > self.color = colorlist[index] > > def printcolor(self): > print self.color > > piececount = 0 > mypiece = ["", "", "", "", "", "", "", "", ""] > while (piececount < 9): > mypiece[piececount] = LinePuzzlePiece() > mypiece[piececount].printcolor() > piececount += 1 A suggestion: mypieces = [] # pluralize container names piececount = 9 for x in range(piececount): > > The problem is that while eight pieces are created and assigned a > colour, the colour is always the same. I need the colours of the pieces > to be in a somewhat random order. What am I doing wrong? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From bgailer at alum.rpi.edu Sat Jun 10 00:13:07 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 09 Jun 2006 15:13:07 -0700 Subject: [Tutor] An Introduction and a question (continuing) In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> <1149888523.10792.50.camel@camille.espersunited.com> Message-ID: <4489F273.9050400@alum.rpi.edu> Michael Sullivan wrote: > OK. I've got it working this far. Now I want the script to generate > eight pieces, each with a random colour. Here's my current code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > random.seed(time) > index = int(math.floor(random.uniform(0, 8))) > colorlist = ["red", "blue", "green", "yellow", "purple", "cyan", > "orange", "white"] > self.color = colorlist[index] > > def printcolor(self): > print self.color > > piececount = 0 > mypiece = ["", "", "", "", "", "", "", "", ""] > while (piececount < 9): > mypiece[piececount] = LinePuzzlePiece() > mypiece[piececount].printcolor() > piececount += 1 > > The problem is that while eight pieces are created and assigned a > colour, the colour is always the same. I need the colours of the pieces > to be in a somewhat random order. What am I doing wrong? > random.seed(time) sets the seed to the same value each time. (You are passing a module object, whose ID becomes the seed). Try random.seed(time.time()). Also you can set the seed once, then let each call to uniform get the next "random" number. Also consider: mypiece = [] for piececount in range(8): mypiece.append(LinePuzzlePiece()) mypiece[piececount].printcolor() -- Bob Gailer 510-978-4454 Broadband Phone Service for local and long distance $19.95/mo plus 1 mo Free -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e0b57ab8/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: show Type: image/gif Size: 43 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060609/e0b57ab8/attachment.gif From doug.shawhan at gmail.com Sat Jun 10 00:28:25 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 9 Jun 2006 17:28:25 -0500 Subject: [Tutor] XML: Expletive Deleted Message-ID: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> I realize XML is going to save us all from something or other, but I just can't get my head around it. I have been trying to do what should be a very simple action: Extract values from element tags. I first grab my data from a website with httplib: >> connection = httplib.HTTPSConnection(serverUrl) >> connection.request("POST", serverDir, buildRequestXml("ReturnAll", "1"), buildHttpHeaders()) >> response = connection.getresponse() >> from xml.dom.minidom import parse, parseString >> data = response.read() >> connection.close() >> response = parseString(data) >> itemIDs = response.getElementsByTagName("ItemID") >> response.unlink() I have tried everything I can find to extract the values from the elements: >> for item in itemIDs: >> print item yeilds Okay, no problem. Now all I have to do is figure out which particlular.string.of.words.interconnected.by.periods to pass to extract the values. >> for item in itemIDs: >> print item.nodeValue Seems logical: None None None None None Oh for crying out loud ... Hmmm ... I have saved the output from response.read() to a file and sure enough, amid all the other element tags, I find the expected values in My problem is: I'm ignorant. I don't know whether my data is being returned from parseString() as text, or a list or a beautiful rainbow made of skittles and pixie droppings. The Python/XML howto and the bajillion other "XML made clear to YOU!" sites I have looked at have left me more confused ... I'm just completely lost in the (apparently arbitrary) nomeclature of lists, nodes, elements, trees, habitrails and intestines. (Yes, I'm just complaining now, but dang it! I'm frustrated! *ahem* Could someone kindly point out where I am going wrong and perhaps send me to a very *practical* introduction to reading data from a dom? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/0b888d30/attachment.htm From paul.kraus at gmail.com Sat Jun 10 00:58:58 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 18:58:58 -0400 Subject: [Tutor] Is there a better way to write this function? Message-ID: <4e2aea430606091558s57ab89e2jc750b6208e8a173b@mail.gmail.com> This is a second... the first one never hit the list. *shrug* should i be using a different interface to post? is this a gateway to newsgroup? I am writing my first python program(at least in a really long time). Its purpose is to take csv or pipe delimintaed files and convert them to html pages. Was going to be excel but its just not worth the headache. Everyone viewing the reports is doing just that viewing simple tables. I need to scan through a list that contains headers to my table. If one of the elements is a tuple and one of the elements of the tuple is "s" set self.sort to the index of the tuple in the header list and then replace the element in header with a two field tuple containing everything that was not 's'. header = ['my first column',('my second num column','s','r'),(' my third num column','r') ] I pass header to a function actually a method but lets pretend its just a plain old function. Be careful reading the below code may cause random strokes. I have woken up twice laying on the floor disoriented.... :) Actual code in my working example used to call function ... report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header): list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's': self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append (header[cindex][tindex]) header[cindex] = tuple(list) self.header = header -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/6e820b5c/attachment.html From alan.gauld at freenet.co.uk Sat Jun 10 01:04:16 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 10 Jun 2006 00:04:16 +0100 Subject: [Tutor] Difference between popens References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> Message-ID: <00e701c68c19$08b357c0$0301a8c0@XPpro> > I'd like to know what are the differences at the various os.popenX > flavors. I read the documentation and I can see they return file > objects..... so what can you do with these file objects? I mean, why > would you need a set of file objects rather than another? My OS topic covers some of the popen variants with explanation. It might help. Here are the most relevant two paragraphs: -------------- In fact there are several variations of the popen command called popen, popen2, popen3 and popen4. The numbers refer to the various data stream combinations that are made available. The standard data streams were described in a sidebar in the Talking to the User topic. The basic version of popen simply creates a single data stream where all input/output is sent/received depending on a mode parameter passed to the function. In essence it tries to make executing a command look like using a file object. By contrast, popen2 offers two streams, one for standard output and another for standard input, so we can send data to the process and read the output without closing the process. popen3 provides stderr access in addition to stdin/stdout. Finally there is popen4 that combines stderr and stdout into a single stream which appears very like normal console output. In Python 2.4 all of these popen calls have been superseded by a new Popen class found in a new subprocess module which we will look at later. For now we will only look at the standard os.popen() function, the others I will leave as a research exercise! --------------- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Jun 10 01:07:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Jun 2006 00:07:29 +0100 Subject: [Tutor] Expletive Deleted References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> Message-ID: "doug shawhan" wrote in message >I realize XML is going to save us all from something or other, but I >just > can't get my head around it. Nope its only going to save Sun and IBM and Cisco etc by forcing us all to buy really powerful computers and really big networks! Alan (with only slightly tongue in cheek) G. From dyoo at hkn.eecs.berkeley.edu Sat Jun 10 02:55:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 9 Jun 2006 17:55:19 -0700 (PDT) Subject: [Tutor] XML: Expletive Deleted In-Reply-To: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> Message-ID: >>> from xml.dom.minidom import parse, parseString > >>> data = response.read() >>> connection.close() >>> response = parseString(data) >>> itemIDs = response.getElementsByTagName("ItemID") >>> response.unlink() ^^^^^^^^^^^^^^^^^ Hi Doug, What's going on here? Why unlink()? > Okay, no problem. Now all I have to do is figure out which > particlular.string.of.words.interconnected.by.periods to pass to extract > the values. > >>> for item in itemIDs: >>> print item.nodeValue You may want to look at the minidom example here: http://www.python.org/doc/lib/dom-example.html Does this help? From paul.kraus at gmail.com Sat Jun 10 04:22:11 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Fri, 9 Jun 2006 22:22:11 -0400 Subject: [Tutor] Function list that might have a tuple that might have one of its indexs set to 's' Message-ID: <4e2aea430606091922k6a5a2a0ar37b06b8e9edda289@mail.gmail.com> I am writing my first python program(at least in a really long time). Its purpose is to take csv or pipe delimited files and convert them to html pages. Was going to be excel but its just not worth the headache. Everyone viewing the reports is doing just that viewing simple tables. I need to scan through a list that contains headers to my table. If one of the elements is a tuple and one of the elements of the tuple is "s" set self.sort to the index of the tuple in the header list and then replace the element in header with a two field tuple containing everything that was not 's'. header = ['my first column',('my second num column','s','r'),(' my third num column','r') ] I pass header to a function actually a method but lets pretend its just a plain old function. Be careful reading the below code may cause random strokes. I have woken up twice laying on the floor disoriented.... :) Actual code in my working example used to call function ... report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header): list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's': self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append (header[cindex][tindex]) header[cindex] = tuple(list) self.header = header TIA, Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e8af7256/attachment.html From levity at gmail.com Sat Jun 10 08:31:55 2006 From: levity at gmail.com (lawrence wang) Date: Sat, 10 Jun 2006 02:31:55 -0400 Subject: [Tutor] XML: Expletive Deleted In-Reply-To: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> Message-ID: <22e13a220606092331r772a848dvf4a98d3f61a1d8ef@mail.gmail.com> > >> for item in itemIDs: > >> print item > > yeilds > > > > > > > > Okay, no problem. Now all I have to do is figure out which > particlular.string.of.words.interconnected.by.periods to > pass to extract the values. > > >> for item in itemIDs: > >> print item.nodeValue > > Seems logical: > > None > None > None > None > None try dir(item) to see what attributes the item has, and try the ones that sound right. e.g.: >>> from xml.dom.minidom import parse, parseString >>> resp = parseString("foo") >>> bottom = resp.getElementsByTagName("bottom") >>> bottom [] >>> dir(bottom[0]) ['ATTRIBUTE_NODE', ...long list snipped..., 'writexml'] >>> bottom[0].hasChildNodes() True >>> bottom[0].childNodes [] >>> dir(bottom[0].childNodes[0]) ['ATTRIBUTE_NODE', ...long list snipped..., 'writexml'] >>> bottom[0].childNodes[0].data u'foo' so you see, with "value", there's an invisible text node. it's one of the quirks of xml, i guess. then the attribute you're looking for is "data", not "nodeValue". in summary: instead of item.nodeValue, item.childNodes[0].data. --lawrence From sisson.j at gmail.com Sat Jun 10 04:27:08 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 10 Jun 2006 03:27:08 +0100 Subject: [Tutor] An Introduction and a question In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> Message-ID: <448A2DFC.9030403@gmail.com> Michael Sullivan wrote: > Here's the situation: My wife likes to play the game Chuzzle, found at > Yahoo Games. We use primarily Linux, however Chuzzle is written as an > ActiveX control, which only works on Windows. I have not been able to > get Internet Explorer to work correctly through Wine, This might not be a Python topic, but I figured I'd respond with what I know on this particular subject... ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make sure you install the ActiveX control in Wine...): http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html World of Warcraft uses ActiveX in it's patch updater, and although I've never personally run it I've had many people tell me this method works. Now if I could just figure out how to convince my wife to try Linux (as you apparently have done) then I'd be set...kudos to you on that. Jonathon so I determined to > write a Chuzzle-like game (with many of my own enhancements) for Linux. > I've been playing around with some Pygame examples lately, and thought > that I'd try writing the game in Python (I've been meaning to learn > Python for years, but just never got around to it.) Today I started on > writing the game. I've decided (at least for now) to call my version, > LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic > concept: There are individual pieces of different colors arranged on a > grid. The pieces can be moved on a line either vertically or > horizontally. The object of the game is to position three similarly > colored pieces ajacent to each other. At this point the three pieces > will disappear, and the pieces above them will fall to take their place. > As the levels progress, locks are added so that the player cannot move a > locked piece either horizontally or vertically. The game is over when > no more pieces can be removed. > > I started my script by creating a class called LinePuzzlePiece which > represents a single coloured piece. I wanted a random colour chosen > from a list to be assigned to the piece, and then to prove that I had it > set up correctly, I wanted to call a method that would print out the > color of the piece. Here is my code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > seed(time) > index = int(math.floor(uniform(1, 10))) colorlist = ["red", > "blue", "green" "yellow", "purple"] self.color = colorlist[index] > > def printcolor(): > print self.color > > mypiece = LinePuzzlePiece > mypiece.printcolor > > > I saved the script and made it chmod +x. However, when I run it, I get > this: > > michael at camille ~ $ ./linepuzzle.py > michael at camille ~ $ > > Now, I'm no expert, but I really think something should have been > printed, if even a blank line. What am I doing wrong here? Why is > nothing printing? Is my printcolor method even being called > successfully? > -Michael Sullivan- > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Jun 10 13:08:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jun 2006 07:08:04 -0400 Subject: [Tutor] An Introduction and a question (continuing) In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> <1149888523.10792.50.camel@camille.espersunited.com> Message-ID: <448AA814.3020406@tds.net> Michael Sullivan wrote: > OK. I've got it working this far. Now I want the script to generate > eight pieces, each with a random colour. Here's my current code: > > #!/usr/bin/env python > > import random > import time > import math > > class LinePuzzlePiece: > """This class defines a single playing piece for LinePuzzle""" > def __init__(self): > random.seed(time) The above statement initializes the random number generator with the time *module*, not the current time. The time module never changes. So every time you need a random number your are initializing the generator with the same constant. That's why you always get the same number. The docs for random.seed() say, "If x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported." So you could omit the time argument to use the actual time; better is to omit the call completely and let the module init itself when you load it. > index = int(math.floor(random.uniform(0, 8))) > colorlist = ["red", "blue", "green", "yellow", "purple", "cyan", > "orange", "white"] > self.color = colorlist[index] random.choice() would be simpler here. Kent > > def printcolor(self): > print self.color > > piececount = 0 > mypiece = ["", "", "", "", "", "", "", "", ""] > while (piececount < 9): > mypiece[piececount] = LinePuzzlePiece() > mypiece[piececount].printcolor() > piececount += 1 > > The problem is that while eight pieces are created and assigned a > colour, the colour is always the same. I need the colours of the pieces > to be in a somewhat random order. What am I doing wrong? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Jun 10 13:25:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jun 2006 07:25:08 -0400 Subject: [Tutor] Function list that might have a tuple that might have one of its indexs set to 's' In-Reply-To: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com> References: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com> Message-ID: <448AAC14.4080301@tds.net> Paul D. Kraus wrote: > I need to scan through a list that contains headers to my table. > If one of the elements is a tuple and one of the elements of the tuple > is "s" set self.sort to the index of the tuple in the header list and > then replace the element in header with a two field tuple containing > everything that was not 's'. > > Actual code in my working example used to call function ... > > report.set_header( > ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max > Talk','r') ] ) > > def set_header(self,header): > list = [] > for cindex in range(len(header)): > if type(()) == type(header[cindex]): > for index in range(len(header[cindex]) ): > if header[cindex][index] == 's': > self.sort = cindex > for tindex in range(len(header[cindex])): > if tindex != index: > list.append(header[cindex][tindex]) > header[cindex] = tuple(list) > self.header = header You didn't actually ask a question. I assume you are looking for a version of this that is less stroke-inducing? You are doing a lot of work that Python would happily do for you. To iterate over a sequence h, instead of generating the indexes to h, use for x in h: which will return the items of h directly. If you also need the indices, use for i, x in enumerate(h) You can test for membership in a sequence with if i in h: You can filter a sequence with a list comprehension: [ x for x in h if x != s ] creates a new list containing all the elements of h that are not s. Putting this all together gives this rewrite: def set_header(self, header): for i, item in enumerate(header): if type(item) != type(()): continue if 's' in item: self.sort = i header[i] = tuple([x for x in item if x!='s']) self.header = header Note this does change the list passed in, that could be a problem depending on if you use it for anything else. Kent From rstoos at rochester.rr.com Sat Jun 10 02:46:27 2006 From: rstoos at rochester.rr.com (Ralph H. Stoos Jr.) Date: Fri, 09 Jun 2006 20:46:27 -0400 Subject: [Tutor] Expletive Deleted Message-ID: <448A1663.7020103@rochester.rr.com> My $.02, First, I subscribed to this list to help learn Python as my first language so my opinion is far from expert. In my real job, I am attempting to get our real programmers to support exporting one of our system logs in XML format, hence, the following opinion. I think XML is a tool that allows non-programmers to look at structured data and have it a in human readable form that gives us a chance of understanding that structure. The other strength that I can see is this: Once data is in this format, and a tool has been written to parse it, data can be added to the structure (more elements) and the original tool will not be broken by this. Whatever it is parsed for is found and the extra is ignored. Without a doubt, the overhead XML adds over say, something as simple as CSV is considerable, and XML would appear to be rather more hard to work with in things like Python and PERL. So, I think XML has it's place but I will not fault anyone for trying to make it easier to get code to work. Good Luck in all endeavors, Ralph From kent37 at tds.net Sat Jun 10 13:34:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jun 2006 07:34:00 -0400 Subject: [Tutor] XML: Expletive Deleted In-Reply-To: References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> Message-ID: <448AAE28.1000701@tds.net> In my opinion the standard DOM models are the most awkward way to deal with XML. If you are trying to get data from HTML on a web page, look at BeautifulSoup. For general XML processing, look at ElementTree. They are both simpler than DOM. http://www.crummy.com/software/BeautifulSoup/ http://effbot.org/zone/element.htm Kent From michael at espersunited.com Sat Jun 10 15:16:56 2006 From: michael at espersunited.com (Michael Sullivan) Date: Sat, 10 Jun 2006 08:16:56 -0500 Subject: [Tutor] An Introduction and a question In-Reply-To: <448A2DFC.9030403@gmail.com> References: <1149882145.10792.37.camel@camille.espersunited.com> <448A2DFC.9030403@gmail.com> Message-ID: <1149945416.10792.66.camel@camille.espersunited.com> On Sat, 2006-06-10 at 03:27 +0100, Jonathon Sisson wrote: > Michael Sullivan wrote: > > Here's the situation: My wife likes to play the game Chuzzle, found at > > Yahoo Games. We use primarily Linux, however Chuzzle is written as an > > ActiveX control, which only works on Windows. I have not been able to > > get Internet Explorer to work correctly through Wine, > > This might not be a Python topic, but I figured I'd respond with what I > know on this particular subject... > > ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine > and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make > sure you install the ActiveX control in Wine...): > > http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html > > World of Warcraft uses ActiveX in it's patch updater, and although I've > never personally run it I've had many people tell me this method works. > Now if I could just figure out how to convince my wife to try Linux (as > you apparently have done) then I'd be set...kudos to you on that. > > Jonathon My wife says that she actually prefers Linux over Windows. The only thing we use Windows for is playing Civilizations II and The Sims, although she also uses it for playing Internet games that don't work on Linux. She's said that if I can make Linux versions of those games she plays on Windows, she won't use Windows at home anymore. When I first started with Linux, she was kinda iffy about it, but now she loves it. We've only used it since fall of 2003... From arcege at gmail.com Sat Jun 10 15:17:33 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Sat, 10 Jun 2006 09:17:33 -0400 Subject: [Tutor] Difference between popens In-Reply-To: <61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com> References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com> <7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com> <61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com> Message-ID: <7e5ba9220606100617m3251f9ddpe36c278bccf5b62@mail.gmail.com> On 6/9/06, Bernard Lebel <3dbernard at gmail.com> wrote: > > Hey, thanks for the nice explanation Michael! > > > Bernard > Whoops.. Hit "reply" instead of "reply to all". My apologies to the group. Dang gmail. -Michael -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060610/ba883bf7/attachment.html From eu_alfonso at yahoo.es Sat Jun 10 20:48:49 2006 From: eu_alfonso at yahoo.es (Alfonso) Date: Sat, 10 Jun 2006 20:48:49 +0200 Subject: [Tutor] problems with python and glade Message-ID: <448B1411.70408@yahoo.es> Hi, I'm trying to learn to use python with glade. As start I have tried to run a program from a tutorial, but when I run it I become this exception: class GladeXML(_gtk.GtkData): AttributeError: 'module' object has no attribute 'GtkData' This ist the program: import pygtk pygtk.require('2.0') import gtk import libglade import gtk.glade class HellowWorldGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file self.gladefile = "proyecto2.glade" self.wTree = gtk.glade.XML(self.gladefile) #Get the Main Window, and connect the "destroy" event self.window = self.wTree.get_widget("MainWindow") if (self.window): self.window.connect("destroy", gtk.main_quit) Does anyone know what could be wrong? Thank you for your attention. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From sisson.j at gmail.com Sat Jun 10 19:07:36 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 10 Jun 2006 18:07:36 +0100 Subject: [Tutor] An Introduction and a question In-Reply-To: <1149945416.10792.66.camel@camille.espersunited.com> References: <1149882145.10792.37.camel@camille.espersunited.com> <448A2DFC.9030403@gmail.com> <1149945416.10792.66.camel@camille.espersunited.com> Message-ID: <448AFC58.70806@gmail.com> 've triedMichael Sullivan wrote: > On Sat, 2006-06-10 at 03:27 +0100, Jonathon Sisson wrote: >> Michael Sullivan wrote: >>> Here's the situation: My wife likes to play the game Chuzzle, found at >>> Yahoo Games. We use primarily Linux, however Chuzzle is written as an >>> ActiveX control, which only works on Windows. I have not been able to >>> get Internet Explorer to work correctly through Wine, >> This might not be a Python topic, but I figured I'd respond with what I >> know on this particular subject... >> >> ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine >> and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make >> sure you install the ActiveX control in Wine...): >> >> http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html >> >> World of Warcraft uses ActiveX in it's patch updater, and although I've >> never personally run it I've had many people tell me this method works. >> Now if I could just figure out how to convince my wife to try Linux (as >> you apparently have done) then I'd be set...kudos to you on that. >>'ve triedi >> Jonathon > > My wife says that she actually prefers Linux over Windows. The only > thing we use Windows for is playing Civilizations II and The Sims, > although she also uses it for playing Internet games that don't work on > Linux. She's said that if I can make Linux versions of those games she > plays on Windows, she won't use Windows at home anymore. When I first > started with Linux, she was kinda iffy about it, but now she loves it. > We've only used it since fall of 2003... > > Part of my reasoning behind learning Python is that Python used so heavily in the Gentoo Linux package management system "Portage." I love portage because of it's flexibility and configurability, and I hope someday to make a contribution back to the OS that really got me hooked on Linux. (I started out with RedHat around May of 2002, but I grew tired of it pretty quickly. I moved from there to try out SuSE, Slackware, Mandrake, Fedora (after giving RedHat a break for a few months), and a few others (haven't tried out Debian...I hear it's really nice, too), but when I saw Gentoo's optimization and configuration capabilities, I was in for life...). Therein lies the difference...I'm an efficiency nut (no I really do not mind compiling the entire OS from source, as long as I can compile it *exactly* how I want, using *only* what I want), and my wife just wants to kick people's a$$es online. She got a bad first impression of Linux from the start because I was constantly tweaking (and breaking) my Linux system, so the chances of her using Linux are rather slim, even though as I progress with my Computer Science degree, I break my Linux system less and less...hahaha. Jonathon From kermit at polaris.net Sun Jun 11 08:28:58 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 11 Jun 2006 02:28:58 -0400 (Eastern Daylight Time) Subject: [Tutor] buggy bug in my program Message-ID: <448BB82A.000003.04032@YOUR-4105E587B6> # def insertw(j1,k,w1,w2,jar,limit): # trace = 1 # if k == 0: # jar[k][0] = k # jar[k][1] = w1 # jar[k][2] = w2 # return # if j1 > k: # jar[j1][0] = k # jar[j1][1] = w1 # jar[j1][2] = w2 # return # # for j2 in range(j1+1,k+1): # j3 = k + j1 - j2 # if trace > 0: # print " insertw: move jar[",j3,"] up one"," j1 = ",j1," k = " k," w1 = ",w1," w2 = ",w2 # f = jar[j3] # jar[j3+1] = f # if trace > 0: # print " insertw: jar[",j3+1," is now ",jar[j3+1] # # # jar[j1][0] = k # jar[j1][1] = w1 # jar[j1][2] = w2 # # if trace > 0: # for j in range(k+1): # print " insertw: jar[",j,"] = ",jar[j] # return # debug trace shows the following puzzling behavior. fermat2: before insertw: jar[ 0 ] = [0, 2, 4] fermat2: before insertw: jar[ 1 ] = [1, 4, 16] fermat2: before insertw: jar[ 2 ] = [-1, -1, -1] I show the array jar before going into insert. remember the heading of insertw is # def insertw(j1,k,w1,w2,jar,limit): insertw: move jar[ 1 ] up one j1 = 1 k = 2 w1 = 16 w2 = 13 This shows that insert made one shift, and sifted jar[1] to jar[2]. j1 = 1 means that insertw was supposed to insert new value into jar[1] insertw: jar[ 2] is now [1, 4, 16] I print out jar[2] to show that insertw really did shift jar[1] to jar[2]. insertw: jar[ 0 ] = [0, 2, 4] insertw: jar[ 1 ] = [2, 16, 13] insertw: jar[ 2 ] = [2, 16, 13] Now, outside the loop, I set jar[j1] to the new values. And I print the resulting array, still within the routine insertw. jar[1] has been set to the new values. BUT, and this is the problem, jar[2] has been also set to the new values. WHY??????????? From alan.gauld at freenet.co.uk Sun Jun 11 09:55:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 11 Jun 2006 08:55:17 +0100 Subject: [Tutor] Expletive Deleted References: <448A1663.7020103@rochester.rr.com> Message-ID: <001d01c68d2c$62077090$0301a8c0@XPpro> > I think XML is a tool that allows non-programmers to look at > structured > data and have it a in human readable form that gives us a chance of > understanding that structure. Thats not a great reason to choose a file format IMHO. Tools can be written to display data in a readable format. For example SQL can be used to view the data in a database. File formats should be designed to store data, compactly and with easy access. > The other strength that I can see is this: Once data is in this > format, > and a tool has been written to parse it, data can be added to the > structure (more elements) and the original tool will not be broken > by > this. Whatever it is parsed for is found and the extra is ignored. But this is a very real plus point for XML. And this IMHO is the biggest single reason for using it, if you have data where the very structure itself is changing yet the same file has to be readable by old and new clients then XML is a good choice. > Without a doubt, the overhead XML adds over say, something as simple > as > CSV is considerable, and XML would appear to be rather more hard to > work > with in things like Python and PERL. Considerable is an understatement, its literally up to 10 or 20 times more space and that means bandwidth and CPU resource to process it. Using XML as a storage medium - a file - is not too bad, you suck it up, process it and foirget the file. MY big gripe is that people are inceasingly trying to use XML as the payload in comms systems, sending XML messages around. This is crazy! The extra cost of the network and hardware needed to process that kind of architecture is usually far higher than the minimal savings it gives in developer time. [As an example I recently had to uplift the bandwidth of the intranet pipe in one of our buildings from 4Mb to a full ATM pipe of 34Mb just to accomodate a system 'upgrade' that now used XML. That raised the network operations cost of that one building from $10k per year to over $100k! - The software upgrade by contrast was only a one-off cost of $10K] > So, I think XML has it's place but I will not fault anyone for > trying to > make it easier to get code to work. Absolutely agree with that. Just be careful how you use it and think of the real cost impact you may be having if its your choice. Your customers will thank you. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Jun 11 09:58:49 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 11 Jun 2006 08:58:49 +0100 Subject: [Tutor] problems with python and glade References: <448B1411.70408@yahoo.es> Message-ID: <002d01c68d2c$dfb3ae50$0301a8c0@XPpro> Can you send the complete error trace. The line you have copied looks like it is from inside GTk somewhere, we need the stack trace to see where it originates in your code. But I'm no GTk expert so I probably can't help anyway! :-) Alan G. ----- Original Message ----- From: "Alfonso" To: Sent: Saturday, June 10, 2006 7:48 PM Subject: [Tutor] problems with python and glade > Hi, > I'm trying to learn to use python with glade. As start I have tried > to > run a program from a tutorial, but when I run it I become this > exception: class GladeXML(_gtk.GtkData): AttributeError: 'module' > object has no attribute 'GtkData' > > > This ist the program: > > import pygtk > pygtk.require('2.0') > import gtk > import libglade > import gtk.glade > > class HellowWorldGTK: > """This is an Hello World GTK application""" > > def __init__(self): > > #Set the Glade file > self.gladefile = "proyecto2.glade" > self.wTree = gtk.glade.XML(self.gladefile) > > #Get the Main Window, and connect the "destroy" event > self.window = self.wTree.get_widget("MainWindow") > if (self.window): > self.window.connect("destroy", gtk.main_quit) > > > Does anyone know what could be wrong? Thank you for your attention. > > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > > From kent37 at tds.net Sun Jun 11 12:58:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 11 Jun 2006 06:58:39 -0400 Subject: [Tutor] buggy bug in my program In-Reply-To: <448BB82A.000003.04032@YOUR-4105E587B6> References: <448BB82A.000003.04032@YOUR-4105E587B6> Message-ID: <448BF75F.3020709@tds.net> Kermit Rose wrote: > # def insertw(j1,k,w1,w2,jar,limit): > # trace = 1 > # if k == 0: > # jar[k][0] = k > # jar[k][1] = w1 > # jar[k][2] = w2 > # return > # if j1 > k: > # jar[j1][0] = k > # jar[j1][1] = w1 > # jar[j1][2] = w2 > # return > # > # for j2 in range(j1+1,k+1): > # j3 = k + j1 - j2 > # if trace > 0: > # print " insertw: move jar[",j3,"] up one"," j1 = ",j1," k = " > k," w1 = ",w1," w2 = ",w2 > # f = jar[j3] > # jar[j3+1] = f I think you want to copy jar[j3] here. In your code, jar[j3] and jar[j3+1] both refer to the same list! If you change the list, you will see it in both places. Assignment in Python is not a copy, it is a name binding. Assignment creates a name for an object. If you assign the same object to two names, they both are bound to the same thing. If the object is mutable, like a list, changes to the object will be seen regardless of which name you use to refer to it. For example: In [14]: d = [1, 2, 3] In [15]: e=d d and e are now references to the same list In [18]: d[0]=55 The changes the list, the change can be seen regardless of which reference to the list is used to access it. In [19]: d Out[19]: [55, 2, 3] In [20]: e Out[20]: [55, 2, 3] Here is one way to make a copy; d and f refer to different lists: In [21]: f=d[:] In [22]: f Out[22]: [55, 2, 3] Changing f doesn't affect d or e: In [23]: f[1]=23 In [24]: f Out[24]: [55, 23, 3] In [25]: d Out[25]: [55, 2, 3] In [26]: e Out[26]: [55, 2, 3] This may help: http://www.effbot.org/zone/python-objects.htm Kent > # if trace > 0: > # print " insertw: jar[",j3+1," is now ",jar[j3+1] > # > # > # jar[j1][0] = k > # jar[j1][1] = w1 > # jar[j1][2] = w2 > # > # if trace > 0: > # for j in range(k+1): > # print " insertw: jar[",j,"] = ",jar[j] > # return > # > > > debug trace shows the following puzzling behavior. > > > fermat2: before insertw: jar[ 0 ] = [0, 2, 4] > fermat2: before insertw: jar[ 1 ] = [1, 4, 16] > fermat2: before insertw: jar[ 2 ] = [-1, -1, -1] > > > I show the array jar before going into insert. > > remember the heading of insertw is > > # def insertw(j1,k,w1,w2,jar,limit): > > > > insertw: move jar[ 1 ] up one j1 = 1 k = 2 w1 = 16 w2 = 13 > > This shows that insert made one shift, and sifted jar[1] to jar[2]. > j1 = 1 means that insertw was supposed to insert new value into jar[1] > > insertw: jar[ 2] is now [1, 4, 16] > > I print out jar[2] to show that insertw really did shift jar[1] to jar[2]. > > > > > insertw: jar[ 0 ] = [0, 2, 4] > insertw: jar[ 1 ] = [2, 16, 13] > insertw: jar[ 2 ] = [2, 16, 13] > > Now, outside the loop, > I set jar[j1] to the new values. > > And I print the resulting array, still within the routine insertw. > > jar[1] has been set to the new values. > > BUT, and this is the problem, > > jar[2] has been also set to the new values. > > WHY??????????? > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From patriciap.gu at gmail.com Sun Jun 11 17:19:06 2006 From: patriciap.gu at gmail.com (Patricia) Date: Sun, 11 Jun 2006 15:19:06 +0000 (UTC) Subject: [Tutor] connect to a remote machine - Linux Message-ID: Hi All, I need to connect to a remote computer on the same network to store data into its mysql database, and I need to do this using python script. Although I've used mysql and python before, I have no idea how to access a remote computer with Python. Also, I would have to enter a passphrase and password to successfully connect to it.. I'd appreciate any help. Thanks!! Patricia From michael at espersunited.com Sun Jun 11 17:38:01 2006 From: michael at espersunited.com (Michael Sullivan) Date: Sun, 11 Jun 2006 10:38:01 -0500 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: References: Message-ID: <1150040281.10761.16.camel@camille.espersunited.com> On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote: > Hi All, > > I need to connect to a remote computer on the same network to store data into > its mysql database, and I need to do this using python script. > > Although I've used mysql and python before, I have no idea how to access a > remote computer with Python. Also, I would have to enter a passphrase and > password to successfully connect to it.. > > I'd appreciate any help. > Thanks!! > > Patricia From python at venix.com Mon Jun 12 00:48:50 2006 From: python at venix.com (Python) Date: Sun, 11 Jun 2006 18:48:50 -0400 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: References: Message-ID: <1150066130.24742.254.camel@www.venix.com> On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote: > Hi All, > > I need to connect to a remote computer on the same network to store data into > its mysql database, and I need to do this using python script. > > Although I've used mysql and python before, I have no idea how to access a > remote computer with Python. Also, I would have to enter a passphrase and > password to successfully connect to it.. I could not simply cut and paste working code, but this should get you started. There is no programming difference in using a remote sql server. import MySQLdb dbparms = { 'host':'dbserver.example.com', # name of sql server # (localhost for your local computer) 'user':'dbusername', # your identifier 'passwd':'dbpassword', # your password 'db':'dbname_to_use', # initial database } conn = MySQLdb.connect( **dbparms) > > I'd appreciate any help. > Thanks!! > > Patricia > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From roymac1 at ntlworld.com Mon Jun 12 00:41:19 2006 From: roymac1 at ntlworld.com (Roy Mac) Date: Sun, 11 Jun 2006 23:41:19 +0100 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: Message-ID: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1> Try looking at PyDO - This provides an interface between Python and your database. This allows you to change your database at a later time and not have to change any Python. The excerpt below is from: http://skunkweb.sourceforge.net/PyDO2/api/html/public/pydo-module.html PyDO (Python Data Objects) is an object-relational wrapper for relational databases. It provides a convenient API for retrieving and manipulating data without constraining in any way how the data is persisted at the RDBMS level. Supported databases are: * postgresql * mysql * sqlite * mssql * oracle -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Patricia Sent: Sunday, June 11, 2006 4:19 PM To: tutor at python.org Subject: [Tutor] connect to a remote machine - Linux Hi All, I need to connect to a remote computer on the same network to store data into its mysql database, and I need to do this using python script. Although I've used mysql and python before, I have no idea how to access a remote computer with Python. Also, I would have to enter a passphrase and password to successfully connect to it.. I'd appreciate any help. Thanks!! Patricia _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From patriciap.gu at gmail.com Mon Jun 12 01:48:06 2006 From: patriciap.gu at gmail.com (Patricia G.) Date: Sun, 11 Jun 2006 19:48:06 -0400 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1> References: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1> Message-ID: <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com> I'm sorry. I think I didn't explain myself well. My problem is not with the database.. The part I'm not sure how to do is connect to the remote computer.. I read somewhere that os.popen would work, but I'm not sure if that will do for me because I have to enter a passphrase and password to connect to the remote machine. Any ideas?? Thanks, Patricia On 6/11/06, Roy Mac wrote: > > Try looking at PyDO - This provides an interface between Python and your > database. This allows you to change your database at a later time and not > have to change any Python. > > The excerpt below is from: > http://skunkweb.sourceforge.net/PyDO2/api/html/public/pydo-module.html > > PyDO (Python Data Objects) is an object-relational wrapper for > relational databases. It provides a convenient API for retrieving and > manipulating data without constraining in any way how the data is > persisted at the RDBMS level. Supported databases are: > > * postgresql > * mysql > * sqlite > * mssql > * oracle > > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Patricia > Sent: Sunday, June 11, 2006 4:19 PM > To: tutor at python.org > Subject: [Tutor] connect to a remote machine - Linux > > Hi All, > > I need to connect to a remote computer on the same network to store data > into its mysql database, and I need to do this using python script. > > Although I've used mysql and python before, I have no idea how to access a > remote computer with Python. Also, I would have to enter a passphrase and > password to successfully connect to it.. > > I'd appreciate any help. > Thanks!! > > Patricia > > _______________________________________________ > 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/20060611/adfc3566/attachment.htm From python at venix.com Mon Jun 12 02:28:13 2006 From: python at venix.com (Python) Date: Sun, 11 Jun 2006 20:28:13 -0400 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: <18f27cbe0606111559vf630f2ex996e11da3504ed95@mail.gmail.com> References: <1150066130.24742.254.camel@www.venix.com> <18f27cbe0606111559vf630f2ex996e11da3504ed95@mail.gmail.com> Message-ID: <1150072093.24742.291.camel@www.venix.com> (back on list) On Sun, 2006-06-11 at 18:59 -0400, Patricia G. wrote: > I'm sorry. I think I didn't explain myself well. My problem is not > with the database.. The part I'm not sure how to do is connect to the > remote computer.. MySQL will accept connections from other computers. It listens on port 3306. There are network setup and security issues, but those would be outside the scope of a Python database program. > I read somewhere that os.popen would work, but I'm not sure if that > will do for me because I have to enter a passphrase and password to > connect to the remote machine. I presume that was using os.popen to talk to stdin/stdout files connected to a telnet or ssh session established from outside Python. That is likely to prove pretty clumsy for all but the simplest cases. > Any ideas?? Logging on to a remote computer should not have anything to do with accessing a remote MySQL database. ssh would probably be the preferred way to login to a remote computer. http://www.lag.net/paramiko/ would appear to do the trick. If you're stuck with telnet, the stdlib has a telnetlib module that would help. http://pexpect.sourceforge.net/ Provides an expect like module to help manage a terminal session conversation. In general, program-to-program interaction between computers works best with protocols that were designed for programs. Telnet expects a person who will interpret error strings, not type too quickly, and understand (and wait for) prompts. Obviously, I don't know your situation, but scripting remote terminal sessions should be a last resort. (I used to do it a lot (15 - 20 years ago) over serial connections where there was no alternative protocol.) > > Thanks, > Patricia > > > On 6/11/06, Python wrote: > On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote: > > Hi All, > > > > I need to connect to a remote computer on the same network > to store data into > > its mysql database, and I need to do this using python > script. > > > > Although I've used mysql and python before, I have no idea > how to access a > > remote computer with Python. Also, I would have to enter a > passphrase and > > password to successfully connect to it.. > > I could not simply cut and paste working code, but this should > get you > started. There is no programming difference in using a remote > sql > server. > > import MySQLdb > > dbparms = { > 'host':'dbserver.example.com', # name of sql server > # (localhost for your local > computer) > 'user':'dbusername', # your identifier > 'passwd':'dbpassword', # your password > 'db':'dbname_to_use', # initial database > } > conn = MySQLdb.connect( **dbparms) > > > > > > I'd appreciate any help. > > Thanks!! > > > > Patricia > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -- Lloyd Kvam Venix Corp From hokkakada at khmeros.info Mon Jun 12 03:15:41 2006 From: hokkakada at khmeros.info (kakada) Date: Mon, 12 Jun 2006 08:15:41 +0700 Subject: [Tutor] combo box In-Reply-To: <20060607235215.04540800.klappnase@freenet.de> References: <44852319.1080804@khmeros.info> <20060607235215.04540800.klappnase@freenet.de> Message-ID: <448CC03D.7000301@khmeros.info> Michael Lange wrote: > On Tue, 06 Jun 2006 13:39:21 +0700 > kakada wrote: > > >> Dear Friends, >> >> I am now working on GUI python (Tkinter). >> I want to use combobox as my widget, but I cannot find it in any document. >> >> Does anybody have experience with that? >> >> > > There is no ComboBox widget in plain Tkinter. > Probably the easiest way to get one is to use Tix which is included in the windows python > distribution and should be available in any recent linux distro. > > If you want to use Tix simply replace the import line > > from Tkinter import * > > with > > from Tix import * > > You then can use your Tknter widgets as usual, plus a nice set of extra widgets (ComboBox, NoteBook, DirTree etc.) . > > I hope this helps > > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Thank Michael, How about putting an icon on an Windows Manager, do you know? da From hokkakada at khmeros.info Mon Jun 12 04:01:07 2006 From: hokkakada at khmeros.info (kakada) Date: Mon, 12 Jun 2006 09:01:07 +0700 Subject: [Tutor] icon on windows manager Message-ID: <448CCAE3.30207@khmeros.info> Hi everyone! Does any body know how to put icon on windows manager using Tix module? Thanks, da From kermit at polaris.net Mon Jun 12 04:14:37 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 11 Jun 2006 22:14:37 -0400 (Eastern Daylight Time) Subject: [Tutor] assignment statements in python Message-ID: <448CCE0D.00000F.01420@YOUR-4105E587B6> Message: 1 Date: Sun, 11 Jun 2006 06:58:39 -0400 From: Kent Johnson Subject: Re: [Tutor] buggy bug in my program Cc: tutor at python.org Assignment in Python is not a copy, it is a name binding. Assignment creates a name for an object. If you assign the same object to two names, they both are bound to the same thing. If the object is mutable, like a list, changes to the object will be seen regardless of which name you use to refer to it. ****** I feel a little bit better now that I know that there is a reason for what my program did. However, I still don't have any idea how to copy values from one cell in an array to the adjacent cell in the same array. I looked at the reference , http://www.effbot.org/zone/python-objects.htm that you gave, but did not gleam any hint from it how to copy values from one place in an array to another place within the same array. It must be possible, for otherwise, you could not sort an array. It is quite remarkable that my not knowing that assignment is not a copy gave me no difficulties before now. Kermit < kermit at polaris.net > From python at venix.com Mon Jun 12 04:59:04 2006 From: python at venix.com (Python) Date: Sun, 11 Jun 2006 22:59:04 -0400 Subject: [Tutor] assignment statements in python In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6> References: <448CCE0D.00000F.01420@YOUR-4105E587B6> Message-ID: <1150081144.24742.310.camel@www.venix.com> On Sun, 2006-06-11 at 22:14 -0400, Kermit Rose wrote: > Message: 1 > Date: Sun, 11 Jun 2006 06:58:39 -0400 > From: Kent Johnson > Subject: Re: [Tutor] buggy bug in my program > Cc: tutor at python.org > > Assignment in Python is not a copy, it is a name binding. Assignment > creates a name for an object. If you assign the same object to two > names, they both are bound to the same thing. If the object is mutable, > like a list, changes to the object will be seen regardless of which name > you use to refer to it. > > ****** > > I feel a little bit better now that I know that there is a reason for what > my > program did. > > However, I still don't have any idea how to copy values from one cell in > an array to the adjacent cell in the same array. > > I looked at the reference , > > http://www.effbot.org/zone/python-objects.htm > > that you gave, > > but did not gleam any hint from it how to copy values from one place in an > array to another place within the same array. > > It must be possible, for otherwise, you could not sort an array. > > > It is quite remarkable that my not knowing that > > assignment is not a copy > > gave me no difficulties before now. The basic python objects: numbers, strings, and tuples are immutable and can not be changed (mutated). a = b = 3 b = 4 # binds b to a different object with value 4 # the object with value 3 is unchanged print a 3 Container objects such as lists and dictionaries can be changed in place. >>> a = b = [1,2,3] >>> b.append(4) # changes (mutates) b >>> print a [1, 2, 3, 4] >>> b[2] = b[3] # positions 2 and 3 reference the same object >>> print b [1, 2, 4, 4] >>> print a [1, 2, 4, 4] > > > > Kermit < kermit at polaris.net > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Mon Jun 12 04:59:47 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 11 Jun 2006 19:59:47 -0700 (PDT) Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com> References: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1> <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com> Message-ID: > I'm sorry. I think I didn't explain myself well. My problem is not with > the database.. The part I'm not sure how to do is connect to the remote > computer.. Hi Patricia, There's some confusion here. Let's get that out in the open. It sounds like you have a remote server. That server provides login shell service through ssh, and this login shell service runs on port 22, I think. But if your server is running MySQL, it is very likely that it provides network access to that MySQL database through port 3306. I think you believe that ssh login access is required to access MySQL on your remote network server. But this is not necessarily true: one can access MySQL remotely without having a login shell account into the machine. That is, rather than: Client ----> Login through SSH ----> Execute mysql client which is three steps, the conventional route here is: Client ----> Connect to networked MySQL using a database driver (MySQLdb) which is more direct. See: MySQLdb: http://sourceforge.net/projects/mysql-python as well as: http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/ However, this does mean that the remote MySQL server has to be set up with a separate MySQL username/password account. That is, MySQL keeps its own set of usernames and passwords that can be separate from the shell logins. Also, mysqld --- the software that drives the MySQL server --- has to be enabled to work across tcp. That requirement sounds obvious enough, but it is not the default in the MySQL server installs I've seen lately, so double check this with your database system administrator. In short: you can not automatically assume that having login access to the machine will give you MySQL database access, and visa-versa. Does this make sense so far? > I read somewhere that os.popen would work, but I'm not sure if that will > do for me Almost certainly no. popen is not for external database access. People have written database drivers to solve this problem for you already. It is perhaps possible to bend popen() in such a way to access MySQL, but this will involve an amount of work to get right, and there will be a lot of ways of getting it wrong. *grin* So I'd recommend changing this question from: "How do I get popen() to access MySQL across a remote interface?" to a more general: "How do I connect to MySQL from Python?" The link above to MySQLdb will give you the software necessary to connect your client to a MySQL server, and the link to the Devshed article is a tutorial on how to use it effectively. Good luck! From efoda at hotmail.com Mon Jun 12 07:26:28 2006 From: efoda at hotmail.com (graphic design) Date: Sun, 11 Jun 2006 22:26:28 -0700 Subject: [Tutor] please remove this address from list: efoda@hotmail.com In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060611/5c151b76/attachment.htm From kent37 at tds.net Mon Jun 12 11:59:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jun 2006 05:59:16 -0400 Subject: [Tutor] assignment statements in python In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6> References: <448CCE0D.00000F.01420@YOUR-4105E587B6> Message-ID: <448D3AF4.20403@tds.net> Kermit Rose wrote: > > Message: 1 > Date: Sun, 11 Jun 2006 06:58:39 -0400 > From: Kent Johnson > Subject: Re: [Tutor] buggy bug in my program > Cc: tutor at python.org > > Assignment in Python is not a copy, it is a name binding. Assignment > creates a name for an object. If you assign the same object to two > names, they both are bound to the same thing. If the object is mutable, > like a list, changes to the object will be seen regardless of which name > you use to refer to it. > > ****** > > I feel a little bit better now that I know that there is a reason for what > my > program did. > > However, I still don't have any idea how to copy values from one cell in > an array to the adjacent cell in the same array. You need to copy the value stored in the list, which is itself a list. > It must be possible, for otherwise, you could not sort an array. Actually sorting doesn't require copying the values in the list, it just requires moving values to different locations of the list. A list element is somewhat like a name - it is a reference to a value, not a container for a value. If you say a=[1,2,3] b=a then a and b refer to the same list. Likewise, if you say x=[ [1,2,3], [4,5,6] ] x[1] = x[0] then x[1] and x[0] refer to the same list. If you want x[1] (or b) to refer to a new list, you have to copy the old list: x[1] = x[0][:] list[:] is the slice of the list that goes from the beginning to the end - a copy. Kent From andrew.arobert at gmail.com Mon Jun 12 13:53:05 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 12 Jun 2006 07:53:05 -0400 Subject: [Tutor] Python related mags Message-ID: <448D55A1.6010002@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi everyone, Does anyone know of any Python related magazines available that would be worth subscribing to? Ideally, a free one, but I would not object to a reasonably priced one either. I was able to find pyzine located at www.pyzine.com but it appears to be defunct. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEjVWhDvn/4H0LjDwRAtsnAJwJ6I6elkmzCwmJUNC3CxDPxjR3bQCeOwL6 IMxn+qVOqe4uwuaCrGA8Qww= =hJPj -----END PGP SIGNATURE----- From patriciap.gu at gmail.com Mon Jun 12 15:32:33 2006 From: patriciap.gu at gmail.com (Patricia G.) Date: Mon, 12 Jun 2006 09:32:33 -0400 Subject: [Tutor] connect to a remote machine - Linux In-Reply-To: References: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1> <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com> Message-ID: <18f27cbe0606120632x7ebc390ay6074c2eaa8312920@mail.gmail.com> Thank you for the great explanation, Danny.. I was confused... Thank you all for your help! Patricia On 6/11/06, Danny Yoo wrote: > > > > > I'm sorry. I think I didn't explain myself well. My problem is not with > > the database.. The part I'm not sure how to do is connect to the remote > > computer.. > > Hi Patricia, > > There's some confusion here. Let's get that out in the open. > > It sounds like you have a remote server. That server provides login shell > service through ssh, and this login shell service runs on port 22, I > think. But if your server is running MySQL, it is very likely that it > provides network access to that MySQL database through port 3306. > > I think you believe that ssh login access is required to access MySQL on > your remote network server. But this is not necessarily true: one can > access MySQL remotely without having a login shell account into the > machine. That is, rather than: > > Client ----> Login through SSH ----> Execute mysql client > > which is three steps, the conventional route here is: > > Client ----> Connect to networked MySQL using a database driver > (MySQLdb) > > which is more direct. > > > See: > > MySQLdb: http://sourceforge.net/projects/mysql-python > > as well as: > > http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/ > > > However, this does mean that the remote MySQL server has to be set up with > a separate MySQL username/password account. That is, MySQL keeps its own > set of usernames and passwords that can be separate from the shell > logins. > > Also, mysqld --- the software that drives the MySQL server --- has to be > enabled to work across tcp. That requirement sounds obvious enough, but > it is not the default in the MySQL server installs I've seen lately, so > double check this with your database system administrator. In short: you > can not automatically assume that having login access to the machine will > give you MySQL database access, and visa-versa. > > Does this make sense so far? > > > > I read somewhere that os.popen would work, but I'm not sure if that will > > do for me > > Almost certainly no. > > popen is not for external database access. People have written database > drivers to solve this problem for you already. It is perhaps possible to > bend popen() in such a way to access MySQL, but this will involve an > amount of work to get right, and there will be a lot of ways of getting it > wrong. *grin* > > > So I'd recommend changing this question from: "How do I get popen() to > access MySQL across a remote interface?" to a more general: "How do I > connect to MySQL from Python?" The link above to MySQLdb will give you > the software necessary to connect your client to a MySQL server, and the > link to the Devshed article is a tutorial on how to use it effectively. > > > Good luck! > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060612/98ba0d73/attachment.htm From jfabiani at yolo.com Mon Jun 12 15:47:23 2006 From: jfabiani at yolo.com (johnf) Date: Mon, 12 Jun 2006 06:47:23 -0700 Subject: [Tutor] Wondering is there a pyQT list Message-ID: <200606120647.23493.jfabiani@yolo.com> Hi, I was wondering if there is a pyqt list like the wxPython-users at lists.wxwidgets.org list? Thanks John From andrew.arobert at gmail.com Mon Jun 12 15:56:09 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 12 Jun 2006 09:56:09 -0400 Subject: [Tutor] Odd traceback - invalid token when extracting contents of XML data element Message-ID: <448D7279.4040600@gmail.com> Hi Everyone, Attached are three scripts that I intend to use for transporting a file via IBM's WebSphere MQSeries middle-ware. The sender script uses a regular expression to replace characters not [a-z][A-Z][0-9] or white space with their hex value equivalents. The purpose of this is to make the contents of a transported file viewable inside MQSeries queues. The attached code works just fine for transporting ASCII text files but it bombs with the following trace when run against binary files. Does anyone know why this might be occurring? Traceback (most recent call last): File "M:\MQ\MQ\Scripts\receiver.py", line 267, in ? receiver.run() File "M:\MQ\MQ\Scripts\receiver.py", line 110, in run self.get() File "M:\MQ\MQ\Scripts\receiver.py", line 139, in get tree = ElementTree(file=buff) File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line 543, in __init__ self.parse(file) File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line 583, in parse parser.feed(data) File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line 1242, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3, column 39 I think that a particular character is perhaps not being translated to ascii as required but I don't know which one it mught be. Part of the reason for this encoding mechanism is so that it plays nice with existing perl code already in place. Not my choice, but what can you do. Any help you can provide on this would be greatly appreciated. -- Thank you, Andrew Robert -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sender.py Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0002.pot -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: file_encoder.py Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0001.asc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: receiver.py Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0003.pot -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 208 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0001.pgp From michael at espersunited.com Mon Jun 12 15:56:46 2006 From: michael at espersunited.com (Michael Sullivan) Date: Mon, 12 Jun 2006 08:56:46 -0500 Subject: [Tutor] assignment statements in python In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6> References: <448CCE0D.00000F.01420@YOUR-4105E587B6> Message-ID: <1150120606.10767.6.camel@camille.espersunited.com> On Sun, 2006-06-11 at 22:14 -0400, Kermit Rose wrote: > Message: 1 > Date: Sun, 11 Jun 2006 06:58:39 -0400 > From: Kent Johnson > Subject: Re: [Tutor] buggy bug in my program > Cc: tutor at python.org > > Assignment in Python is not a copy, it is a name binding. Assignment > creates a name for an object. If you assign the same object to two > names, they both are bound to the same thing. If the object is mutable, > like a list, changes to the object will be seen regardless of which name > you use to refer to it. > > ****** In that case, is it possible to copy a variable by value, instead of by reference, in Python? From dyoo at hkn.eecs.berkeley.edu Mon Jun 12 16:20:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 12 Jun 2006 07:20:19 -0700 (PDT) Subject: [Tutor] assignment statements in python In-Reply-To: <1150120606.10767.6.camel@camille.espersunited.com> References: <448CCE0D.00000F.01420@YOUR-4105E587B6> <1150120606.10767.6.camel@camille.espersunited.com> Message-ID: >> Assignment in Python is not a copy, it is a name binding. Assignment >> creates a name for an object. If you assign the same object to two >> names, they both are bound to the same thing. If the object is mutable, >> like a list, changes to the object will be seen regardless of which >> name you use to refer to it. >> >> ****** > > In that case, is it possible to copy a variable by value, instead of by > reference, in Python? The 'copy' module is available, http://www.python.org/doc/lib/module-copy.html So in a pinch, if we're really paranoid, we can pass copies of our argument values to a function. In general, though, a function should really document if it mutates its arguments, because that's generally a very rude thing to do unless it's the expected behavior. From doug.shawhan at gmail.com Mon Jun 12 16:34:23 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Mon, 12 Jun 2006 09:34:23 -0500 Subject: [Tutor] XML: Expletive Deleted In-Reply-To: <448AAE28.1000701@tds.net> References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com> <448AAE28.1000701@tds.net> Message-ID: <5e1ceb8a0606120734y489cf1bdt63f6258dd652f7ba@mail.gmail.com> Kent, Danny, Lawrence, et. al. Thanks! I was kind of cringing as I sent this plaint/rant, but it seems I'm not the only one who has had trouble grokking DOM. I spanked the problem temporarily with regex, but can now actually fix it properly. Appreciate all the help! On 6/10/06, Kent Johnson wrote: > > In my opinion the standard DOM models are the most awkward way to deal > with XML. If you are trying to get data from HTML on a web page, look at > BeautifulSoup. For general XML processing, look at ElementTree. They are > both simpler than DOM. > http://www.crummy.com/software/BeautifulSoup/ > http://effbot.org/zone/element.htm > > 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/20060612/3b828444/attachment.htm From python at venix.com Mon Jun 12 17:20:55 2006 From: python at venix.com (Python) Date: Mon, 12 Jun 2006 11:20:55 -0400 Subject: [Tutor] assignment statements in python In-Reply-To: <448D6E09.000001.03656@YOUR-4105E587B6> References: <1150081144.24742.310.camel@www.venix.com> <448D6E09.000001.03656@YOUR-4105E587B6> Message-ID: <1150125655.24742.328.camel@www.venix.com> On Mon, 2006-06-12 at 09:37 -0400, Kermit Rose wrote: > > From: Python > Date: 06/11/06 22:59:38 > To: Kermit Rose > Cc: Tutor Python > Subject: Re: [Tutor] assignment statements in python > > > The basic python objects: numbers, strings, and tuples are immutable and > can not be changed (mutated). > a = B = 3 > B = 4 # binds B to a different object with value 4 > # the object with value 3 is unchanged > print a > 3 > > ** > If I write > > a = 3 > a = 4 > a = 5 > > Are the objects containing 3 and 4 erased when they no longer have a name? Yes > > ** > > >>>>> > > Container objects such as lists and dictionaries can be changed in > place. > >>> a = B = [1,2,3] > >>> B.append(4) # changes (mutates) B > >>> print a > [1, 2, 3, 4] > > ****** > > Good. Now I know a more efficient way to extend an array. > > I had been creating an entire new array, and equivalencing the old array to > it. > > ****** > >>>>>> > > >>> B[2] = B[3] # positions 2 and 3 reference the same object > >>> print B > [1, 2, 4, 4] > >>> print a > [1, 2, 4, 4] > > ****** > > I still don't know how to make it so that > > If B = [ 1,2,4,5] > > B.append(value of B[4]) There is no B[4] B[0] is 1 B[1] is 2 B[2] is 4 B[3] is 5 Perhaps you mean to search B looking for the value 4 and then append that value? index_of_4 = B.index(4) # returns index to location of first 4 B.append( B[index_of_4]) # appends the 4 to the end of B > copy the value of B[2] into B[3] >>> import copy >>> B = [ 1,2,4,5] >>> B[3] = copy.copy(B[2]) >>> B [1, 2, 4, 4] Since 4 is immutable, there is no need to use the copy module, but it is there for when you need to make copies of an object. > copy the value 3 into B[2]. B[2] = 3 # no need for a copy since 3 is immutable > > > Or, equivalently, > > If B = [1,2,4,5] > > Insert the value 3 between > B[1] and b[2], > >>> B = [ 1,2,4,5] >>> B.insert(2,3) # inserts 3 before B[2] >>> B [1, 2, 3, 4, 5] >>> help(B.insert) insert(...) L.insert(index, object) -- insert object before index (Use q to leave the help screen) > so that B > becomes > [1,2,3,4,5]. > > Kermit < kermit at polaris.net > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kermit at polaris.net Mon Jun 12 17:26:33 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 12 Jun 2006 11:26:33 -0400 (Eastern Daylight Time) Subject: [Tutor] sorting in python Message-ID: <448D87A8.00000D.03656@YOUR-4105E587B6> Message: 6 Date: Mon, 12 Jun 2006 05:59:16 -0400 From: Kent Johnson Subject: Re: [Tutor] assignment statements in python Actually sorting doesn't require copying the values in the list, it just requires moving values to different locations of the list. ***** Yes. I wish to know how I can , for examplem, given B = [1,2,4,5], move B[3] to a position of newly created B[4], move B[2] to position of B[3] Assign value 3 to position B[2]. That is, I wish to insert the value 3, into it's sorted place within the already sorted list B. **** >>>>> A list element is somewhat like a name - it is a reference to a value, not a container for a value. If you say a=[1,2,3] B=a then a and B refer to the same list. Likewise, if you say x=[ [1,2,3], [4,5,6] ] x[1] = x[0] then x[1] and x[0] refer to the same list. *** >>> x = [ [1,2,3],[4,5,6]] >>> x [[1, 2, 3], [4, 5, 6]] >>> x[1] = x[0] >>> x [[1, 2, 3], [1, 2, 3]] >>> Needed to make sure I understood what would happen. Does the value [4,5,6] get erased at this point? ******** If you want x[1] (or B) to refer to a new list, you have to copy the old list: x[1] = x[0][:] list[:] is the slice of the list that goes from the beginning to the end - a copy. ***** I missed the significance of the [:] slice until you explained it. So, now I could write my code as # to insert 3 between 2 and 4 in B = [1,2,4,5] B.append(B[3:3]) # I expected B[4] to have the value 5 at this point. # It is empty. Why? # So, I compensate by making the next line B[4] = B[3:3] # B[4] is still an empty list. Why? # I try B[4] = B[3] # That seemed to work. B[3] = B[2] # Now I try B[2] = 3 That worked. However, I don't see the difference between this code, and what I had before that did not work. Kermit < kermit at polaris.net > Kent From python at venix.com Mon Jun 12 17:44:50 2006 From: python at venix.com (Python) Date: Mon, 12 Jun 2006 11:44:50 -0400 Subject: [Tutor] sorting in python In-Reply-To: <448D87A8.00000D.03656@YOUR-4105E587B6> References: <448D87A8.00000D.03656@YOUR-4105E587B6> Message-ID: <1150127090.24742.340.camel@www.venix.com> On Mon, 2006-06-12 at 11:26 -0400, Kermit Rose wrote: > # to insert 3 between 2 and 4 in > > B = [1,2,4,5] > > B.append(B[3:3]) >>> B[3:3] [] >>> B[3:4] [5] >>> B[0:1] [1] >>> B[:2] [1, 2] >>> B.append(B[3:3]) >>> B [1, 2, 4, 5, []] > > # I expected B[4] to have the value 5 at this point. > # It is empty. Why? You appended an empty list. Note that slice notation returns a list, so you would more commonly use B.extend(B[0:3]) to avoid nested lists. The number before the : is the index to include from The number after the : is the index to exclude Slices are half-open intervals. The lower-bound is included while the upper-bound is excluded. http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Provides an excellent justification for this approach (cited recently on this list) -- Lloyd Kvam Venix Corp From Barry.Carroll at psc.com Mon Jun 12 18:55:53 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 12 Jun 2006 09:55:53 -0700 Subject: [Tutor] XML: Expletive Deleted (OT) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com> Alan, Ralph, et al: This is a little off-topic, I guess, being not directly related to Python. Oh, well. Here are a couple of personal opinions and a question about XML. > -----Original Message----- > Date: Sun, 11 Jun 2006 08:55:17 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Expletive Deleted > To: "Ralph H. Stoos Jr." , > Message-ID: <001d01c68d2c$62077090$0301a8c0 at XPpro> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > I think XML is a tool that allows non-programmers to look at > > structured > > data and have it a in human readable form that gives us a chance of > > understanding that structure. > > Thats not a great reason to choose a file format IMHO. > Tools can be written to display data in a readable format. > For example SQL can be used to view the data in a database. > File formats should be designed to store data, compactly > and with easy access. One reason to for choosing a human-readable format is the desire to visually confirm the correctness of the stored data and format. This can be invaluable when troubleshooting a bug involving stored data. If there is a tool between the user and the data, one must then rely upon the correctness of the tool to determine the correctness of the data. In a case like this, nothing beats the evidence of one's eyes, IMHO. In their book, "The Pragmatic Programmer: From Journeyman to Master" (Addison Wesley Professional), Andrew Hunt and David Thomas give another reason for storing data in human readable form: The problem with most binary formats is that the context necessary to understand the data is separate from the data itself. You are artificially divorcing the data from its meaning. The data may as well be encrypted; it is absolutely meaningless without the application logic to parse it. With plain text, however, you can achieve a self-describing data stream that is independent of the application that created it. Tip 20 Keep Knowledge in Plain Text > > The other strength that I can see is this: Once data is in this > > format, > > and a tool has been written to parse it, data can be added to the > > structure (more elements) and the original tool will not be broken > > by > > this. Whatever it is parsed for is found and the extra is ignored. > > But this is a very real plus point for XML. > And this IMHO is the biggest single reason for using it, if you have > data where the very structure itself is changing yet the same file > has to be readable by old and new clients then XML is a good choice. No argument there. > > Without a doubt, the overhead XML adds over say, something as simple > > as > > CSV is considerable, and XML would appear to be rather more hard to > > work > > with in things like Python and PERL. > > Considerable is an understatement, its literally up to 10 or 20 times > more space and that means bandwidth and CPU resource to > process it. > > Using XML as a storage medium - a file - is not too bad, you suck > it up, process it and foirget the file. MY big gripe is that people > are > inceasingly trying to use XML as the payload in comms systems, > sending XML messages around. This is crazy! The extra cost of the > network and hardware needed to process that kind of architecture > is usually far higher than the minimal savings it gives in developer > time. > [As an example I recently had to uplift the bandwidth of the > intranet pipe in one of our buildings from 4Mb to a full ATM pipe > of 34Mb just to accomodate a system 'upgrade' that now used XML. > That raised the network operations cost of that one building > from $10k per year to over $100k! - The software upgrade by > contrast was only a one-off cost of $10K] This is an example of the resource balancing act that computer people have been faced with since the beginning. The most scarce/expensive resource dictates the program's/system's design. In Alan's example high speed bandwidth is the limiting resource. A data transmission method that fails to minimize use of that resource is therefore a bad solution. Python itself is a result of this balancing act. Interpreted languages like Basic were invented to overcome the disadvantages of writing of programs in machine-readable, human-unfriendly formats. Compiled languages like C were invented to overcome the slow execution speed of interpreted programs. As processor speeds increased and execution times dropped , interpreted languages like Python once again became viable for large scale programs. > > So, I think XML has it's place but I will not fault anyone for > > trying to > > make it easier to get code to work. > > Absolutely agree with that. Just be careful how you use it and > think of the real cost impact you may be having if its your choice. > Your customers will thank you. So here's my off-topic question: Ajax is being touted as the 'best-known method' (BKM) for making dynamic browser-based applications, and XML is the BKM for transferring data in Ajax land. If XML is a bad idea for network data-transfer, what medium should be used instead? > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Mon Jun 12 19:14:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jun 2006 13:14:46 -0400 Subject: [Tutor] XML: Expletive Deleted (OT) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com> Message-ID: <448DA106.2030008@tds.net> Carroll, Barry wrote: > So here's my off-topic question: Ajax is being touted as the 'best-known > method' (BKM) for making dynamic browser-based applications, and XML is > the BKM for transferring data in Ajax land. If XML is a bad idea for > network data-transfer, what medium should be used instead? JSON is a popular alternative to XML for Ajax applications. It is much lighter-weight than XML and easier to parse in JavaScript. http://json.org/ Kent From Barry.Carroll at psc.com Mon Jun 12 19:35:24 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 12 Jun 2006 10:35:24 -0700 Subject: [Tutor] Python related mags Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B9@eugsrv400.psc.pscnet.com> Hello, Andrew: > -----Original Message----- > Date: Mon, 12 Jun 2006 07:53:05 -0400 > From: Andrew Robert > Subject: [Tutor] Python related mags > To: Python Tutor > Message-ID: <448D55A1.6010002 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi everyone, > > Does anyone know of any Python related magazines available that would be > worth subscribing to? > > Ideally, a free one, but I would not object to a reasonably priced one > either. > > I was able to find pyzine located at www.pyzine.com but it appears to be > defunct. Dr. Dobbs puts out a weekly Python related e-zine that be useful to you. I couldn't find the URL, but I get a link to it every week in the Python-announce-list: http://mail.python.org/mailman/listinfo/python-announce-list. HTH. Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From simplebob at gmail.com Mon Jun 12 21:08:17 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Mon, 12 Jun 2006 15:08:17 -0400 Subject: [Tutor] please remove this address from list: efoda@hotmail.com In-Reply-To: References: Message-ID: <6d87ecf40606121208o8510991h5909d6f550fb9507@mail.gmail.com> you will need to do it yourself. http://mail.python.org/mailman/listinfo/python-list On 6/12/06, graphic design wrote: > > not sure how i got on this list. please remove my email address from it. > > thank you. > > efoda at hotmail.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > sorry, -- Daniel McQuay simplebob at gmail.com boxster.homelinux.org H: 814.825.0847 M: 814-341-6233 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060612/ebfc62f7/attachment.html From doug.shawhan at gmail.com Mon Jun 12 21:46:06 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Mon, 12 Jun 2006 14:46:06 -0500 Subject: [Tutor] datetime: What happended yesterday? :-) Message-ID: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> I've been looking at datetime and cannot figure out what was a very simple operation with the time module. How does one add or subtract 24 (or any number) of hours from a given date and time using the datetime module? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060612/6531f220/attachment.htm From patriciap.gu at gmail.com Mon Jun 12 21:48:14 2006 From: patriciap.gu at gmail.com (patricia) Date: Mon, 12 Jun 2006 19:48:14 +0000 (UTC) Subject: [Tutor] Mod-python Message-ID: Hi! I have about 17 lines of text (about system information) that I need to pass to a remote web server AND I've been asked to send this data via Apache. I have to write a python script that will fetch a URL to pass this text. I understand that if I want to use the POST method, I would need to have a page with a submit button, and this is not the case. I also know that with GET, the length of the url is limited. What is the best way to send a long string? Hope anyone can point me to the right direction.. Thanks, Patricia From dustin at ywlcs.org Mon Jun 12 21:58:30 2006 From: dustin at ywlcs.org (Dustin Mitchell) Date: Mon, 12 Jun 2006 14:58:30 -0500 Subject: [Tutor] Mod-python In-Reply-To: References: Message-ID: <26b656a95a747a4effd024fce7ab319b@ywlcs.org> Well, POST or PUT are the normal ways to do that. You need to interact with the person running the web server to see how they need it delivered - if they're expecting a GET and you give them a POST, it isn't going to work very well :) Dustin On Jun 12, 2006, at 2:48 PM, patricia wrote: > Hi! > > I have about 17 lines of text (about system information) that I need > to pass to > a remote web server AND I've been asked to send this data via Apache. > I have to > write a python script that will fetch a URL to pass this text. I > understand that > if I want to use the POST method, I would need to have a page with a > submit > button, and this is not the case. I also know that with GET, the > length of the > url is limited. What is the best way to send a long string? > > Hope anyone can point me to the right direction.. > Thanks, > Patricia > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Jun 12 22:08:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jun 2006 16:08:57 -0400 Subject: [Tutor] datetime: What happended yesterday? :-) In-Reply-To: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> Message-ID: <448DC9D9.8040902@tds.net> doug shawhan wrote: > I've been looking at datetime and cannot figure out what was a very > simple operation with the time module. > > How does one add or subtract 24 (or any number) of hours from a given > date and time using the datetime module? Use a datetime.timedelta: In [1]: import datetime In [2]: now = datetime.datetime.now() In [3]: now Out[3]: datetime.datetime(2006, 6, 12, 16, 7, 47, 69000) In [4]: one_day = datetime.timedelta(hours=24) In [5]: now-one_day Out[5]: datetime.datetime(2006, 6, 11, 16, 7, 47, 69000) Kent From doug.shawhan at gmail.com Mon Jun 12 22:20:41 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Mon, 12 Jun 2006 15:20:41 -0500 Subject: [Tutor] datetime: What happended yesterday? :-) In-Reply-To: <448DC9D9.8040902@tds.net> References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> <448DC9D9.8040902@tds.net> Message-ID: <5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com> Heh. Your example would look very, very nice in the timedelta ( http://docs.python.org/lib/datetime-timedelta.html) section of the docs! :-) It makes perfect sense, the authors probably thought it was too easy to need an explaination ... On 6/12/06, Kent Johnson wrote: > > doug shawhan wrote: > > I've been looking at datetime and cannot figure out what was a very > > simple operation with the time module. > > > > How does one add or subtract 24 (or any number) of hours from a given > > date and time using the datetime module? > > Use a datetime.timedelta: > > In [1]: import datetime > > In [2]: now = datetime.datetime.now() > > In [3]: now > Out[3]: datetime.datetime(2006, 6, 12, 16, 7, 47, 69000) > > In [4]: one_day = datetime.timedelta(hours=24) > > In [5]: now-one_day > Out[5]: datetime.datetime(2006, 6, 11, 16, 7, 47, 69000) > > 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/20060612/7a16065d/attachment.html From kent37 at tds.net Mon Jun 12 22:34:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jun 2006 16:34:27 -0400 Subject: [Tutor] datetime: What happended yesterday? :-) In-Reply-To: <5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com> References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> <448DC9D9.8040902@tds.net> <5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com> Message-ID: <448DCFD3.9040302@tds.net> doug shawhan wrote: > Heh. Your example would look very, very nice in the timedelta > (http://docs.python.org/lib/datetime-timedelta.html) section of the > docs! :-) > > It makes perfect sense, the authors probably thought it was too easy to > need an explaination ... It is noted in the "Supported operations" for datetime, buried in the middle of this page: http://docs.python.org/lib/datetime-datetime.html Kent From pjlists at gmail.com Mon Jun 12 23:09:21 2006 From: pjlists at gmail.com (Peter Jessop) Date: Mon, 12 Jun 2006 23:09:21 +0200 Subject: [Tutor] Mod-python In-Reply-To: References: Message-ID: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> > > I have about 17 lines of text (about system information) that I need to pass to > a remote web server AND I've been asked to send this data via Apache. I have to > write a python script that will fetch a URL to pass this text. I understand that > if I want to use the POST method, I would need to have a page with a submit > button, and this is not the case. I also know that with GET, the length of the > url is limited. What is the best way to send a long string? When you say you that you want to send this data via Apache do you mean that the web server you are sending to is running Apache or that you are communicating from one server to another? If you simply want to emulate a a web page with a submit button that sends a Post you do it with code a bit like the following import urllib, urllib2 url = "http://www.somesite.com/somefolder/exampl1.cgi" dict = {} dict["field1"] = "value1" dict["field2"] = "value2" ... dict["fieldn"] = "valuen" urldata = urllib.urlencode(dict) req = urllib2.Request(url) req.add_header('User-agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0') fd = urllib2.urlopen(req,urldata) Regards Peter Jessop > > Hope anyone can point me to the right direction.. > Thanks, > Patricia > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From patriciap.gu at gmail.com Mon Jun 12 23:40:28 2006 From: patriciap.gu at gmail.com (Patricia G.) Date: Mon, 12 Jun 2006 17:40:28 -0400 Subject: [Tutor] Mod-python In-Reply-To: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> Message-ID: <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> Hi, > > When you say you that you want to send this data via Apache do you > mean that the web server you are sending to is running Apache Yes. If you simply want to emulate a a web page with a submit button that > sends a Post you do it with code a bit like the following > > import urllib, urllib2 > url = "http://www.somesite.com/somefolder/exampl1.cgi" > dict = {} > dict["field1"] = "value1" > dict["field2"] = "value2" > ... > dict["fieldn"] = "valuen" > urldata = urllib.urlencode(dict) > req = urllib2.Request(url) > req.add_header('User-agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT > 5.0') > fd = urllib2.urlopen(req,urldata) > > Regards > Peter Jessop I'll try this out. Thank you! Patricia > > > Hope anyone can point me to the right direction.. > > Thanks, > > Patricia > > > > _______________________________________________ > > 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/20060612/0a0e21de/attachment.htm From mahansen at adelphia.net Mon Jun 12 18:56:09 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Mon, 12 Jun 2006 10:56:09 -0600 Subject: [Tutor] Python related mags In-Reply-To: <448D55A1.6010002@gmail.com> References: <448D55A1.6010002@gmail.com> Message-ID: <6ba92c331537c6ac94e2bc18e2662757@adelphia.net> On Jun 12, 2006, at 5:53 AM, Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi everyone, > > Does anyone know of any Python related magazines available that would > be > worth subscribing to? > > Ideally, a free one, but I would not object to a reasonably priced one > either. > > I was able to find pyzine located at www.pyzine.com but it appears to > be > defunct. > > I don' think there's much out there. Sometime Linux Journal will have Python related articles, sometimes Dr. Dobbs. As popular as Python is, it's probably not popular enough to sustain a magazine devoted just to it. Mike From andrew.arobert at gmail.com Tue Jun 13 03:13:55 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 12 Jun 2006 21:13:55 -0400 Subject: [Tutor] Python related mags In-Reply-To: <6ba92c331537c6ac94e2bc18e2662757@adelphia.net> References: <448D55A1.6010002@gmail.com> <6ba92c331537c6ac94e2bc18e2662757@adelphia.net> Message-ID: <448E1153.1080106@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Now that is a real pity. Wish I were talented enough to do it myself. Mike Hansen wrote: > On Jun 12, 2006, at 5:53 AM, Andrew Robert wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hi everyone, >> >> Does anyone know of any Python related magazines available that would >> be >> worth subscribing to? >> >> Ideally, a free one, but I would not object to a reasonably priced one >> either. >> >> I was able to find pyzine located at www.pyzine.com but it appears to >> be >> defunct. >> >> > I don' think there's much out there. Sometime Linux Journal will have > Python related articles, sometimes Dr. Dobbs. As popular as Python is, > it's probably not popular enough to sustain a magazine devoted just to > it. > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEjhFTDvn/4H0LjDwRAq14AJ9RzCA4o5pNW6y47c1mM/Tzm0R3EACfZ0ec KxReJbvZERlj2gHx4Y+FB58= =kKr8 -----END PGP SIGNATURE----- From billburns at pennswoods.net Tue Jun 13 02:51:12 2006 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 12 Jun 2006 20:51:12 -0400 Subject: [Tutor] Wondering is there a pyQT list In-Reply-To: <200606120647.23493.jfabiani@yolo.com> References: <200606120647.23493.jfabiani@yolo.com> Message-ID: <448E0C00.6080607@pennswoods.net> johnf wrote: > Hi, > I was wondering if there is a pyqt list like the > wxPython-users at lists.wxwidgets.org list? > http://mats.imk.fraunhofer.de/mailman/listinfo/pykde From michael at espersunited.com Tue Jun 13 04:26:12 2006 From: michael at espersunited.com (Michael Sullivan) Date: Mon, 12 Jun 2006 21:26:12 -0500 Subject: [Tutor] Python related mags In-Reply-To: <448E1153.1080106@gmail.com> References: <448D55A1.6010002@gmail.com> <6ba92c331537c6ac94e2bc18e2662757@adelphia.net> <448E1153.1080106@gmail.com> Message-ID: <1150165573.10769.7.camel@camille.espersunited.com> On Mon, 2006-06-12 at 21:13 -0400, Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Now that is a real pity. > > Wish I were talented enough to do it myself. Someone could do something like Tux Magazine (http://www.tuxmagazine.org/) . Each month they put out a free Linux magazine in the form of a downloadable pdf file. It's supposed to be geared toward new Linux users. I particularly like the pdf format, because it doesn't take up space in my apartment, just on my hard drive... From treed at ultraviolet.org Tue Jun 13 07:07:31 2006 From: treed at ultraviolet.org (Tracy R Reed) Date: Mon, 12 Jun 2006 22:07:31 -0700 Subject: [Tutor] Python related mags In-Reply-To: <448D55A1.6010002@gmail.com> References: <448D55A1.6010002@gmail.com> Message-ID: <448E4813.2000206@ultraviolet.org> Andrew Robert wrote: > Does anyone know of any Python related magazines available that would be > worth subscribing to? > Why bother when there are many excellent websites with good python articles? I have found that my consumption of print media has fallen to practically zero not including things I print out myself in the years since I discovered the Internet. The vast majority of python users are on the net. It does not surprise me at all that there are no printed python magazines. It is much more efficient to put it all online. -- Tracy R Reed http://ultraviolet.org From emilia12 at mail.bg Tue Jun 13 08:30:40 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Tue, 13 Jun 2006 09:30:40 +0300 Subject: [Tutor] [tutor] debug process Message-ID: <1150180240.646e307959208@mail.bg> Hello, Is there a way to debug (trace) the python code line by line? emily ----------------------------- ??????? 666. ???? ? ??????. From kraus at hagen-partner.de Tue Jun 13 08:51:49 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 13 Jun 2006 08:51:49 +0200 Subject: [Tutor] [tutor] debug process In-Reply-To: <1150180240.646e307959208@mail.bg> References: <1150180240.646e307959208@mail.bg> Message-ID: emilia12 at mail.bg schrieb: > Hello, > > Is there a way to debug (trace) the python code line by line? > > emily > Hi emily! You can use The Python Debugger or pdb, see: http://www.python.org/doc/2.4.2/lib/module-pdb.html HTH, Wolfram From kent37 at tds.net Tue Jun 13 12:09:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jun 2006 06:09:02 -0400 Subject: [Tutor] [tutor] debug process In-Reply-To: <1150180240.646e307959208@mail.bg> References: <1150180240.646e307959208@mail.bg> Message-ID: <448E8EBE.9050101@tds.net> emilia12 at mail.bg wrote: > Hello, > > Is there a way to debug (trace) the python code line by > line? There is a simple debugger included with IDLE, the editor that comes with Python. winpdb is a nice debugger with a GUI. Pydev and Eric3 are Python development tools that include debuggers. http://www.digitalpeers.com/pythondebugger/ http://pydev.sourceforge.net/ http://www.die-offenbachs.de/detlev/eric3.html Kent From fiveholiday55 at hotmail.com Tue Jun 13 12:12:17 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Tue, 13 Jun 2006 11:12:17 +0100 Subject: [Tutor] Python related mags References: <448D55A1.6010002@gmail.com><6ba92c331537c6ac94e2bc18e2662757@adelphia.net><448E1153.1080106@gmail.com> <1150165573.10769.7.camel@camille.espersunited.com> Message-ID: ----- Original Message ----- From: "Michael Sullivan" To: "Andrew Robert" Cc: "Python Tutor" Sent: Tuesday, June 13, 2006 3:26 AM Subject: Re: [Tutor] Python related mags > On Mon, 2006-06-12 at 21:13 -0400, Andrew Robert wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Now that is a real pity. >> >> Wish I were talented enough to do it myself. > > Someone could do something like Tux Magazine > (http://www.tuxmagazine.org/) . Each month they put out a free Linux > magazine in the form of a downloadable pdf file. It's supposed to be > geared toward new Linux users. I particularly like the pdf format, > because it doesn't take up space in my apartment, just on my hard Am a tuxmagazine subscriber and the .pdf format is a very good idea, would be very pleased to have something like that for Python developers too. But then again, who is going to initiate the first move?? From bgailer at alum.rpi.edu Tue Jun 13 16:36:34 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 13 Jun 2006 07:36:34 -0700 Subject: [Tutor] [tutor] debug process In-Reply-To: <448E8EBE.9050101@tds.net> References: <1150180240.646e307959208@mail.bg> <448E8EBE.9050101@tds.net> Message-ID: <448ECD72.2020106@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060613/2bf7fea3/attachment.html From andy.koch at pc-doctor.com Tue Jun 13 16:42:11 2006 From: andy.koch at pc-doctor.com (Andy Koch) Date: Tue, 13 Jun 2006 07:42:11 -0700 Subject: [Tutor] die or exit function? Message-ID: Bkgd: I've been doing PHP for the last several years. Q: In PHP there are functions die and exit which terminate processing of a script with an optional string output. Is there something similar to this in Python? From dkuhlman at rexx.com Tue Jun 13 17:45:28 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 13 Jun 2006 08:45:28 -0700 Subject: [Tutor] [tutor] debug process In-Reply-To: References: <1150180240.646e307959208@mail.bg> Message-ID: <20060613154528.GA45543@cutter.rexx.com> On Tue, Jun 13, 2006 at 08:51:49AM +0200, Wolfram Kraus wrote: > emilia12 at mail.bg schrieb: > > Hello, > > > > Is there a way to debug (trace) the python code line by line? > > > > emily > > > > Hi emily! > > You can use The Python Debugger or pdb, see: > http://www.python.org/doc/2.4.2/lib/module-pdb.html > Also, put the following at the location in your code where you want to drop into the debugger: import pdb pdb.set_trace() and then, at the pdb prompt, type: (Pdb) help l (Pdb) help b etcetera. You can also do: import pdb pdb.help() which will show you documentation on pdb. And, this is not a debugger but ... If you have installed IPython, you can also easily embed a complete Python interpreter in your program. Although it does not give you breakpoints and other debugging features, it does enable you to do lots in the way of inspecting objects, evaluating objects, performing tests on objects, etc. If you have *not* installed IPython, I recommend it. It makes a great replacement for the standard Python interactive interpreter. To learn about IPython, see: IPython: http://ipython.scipy.org/ Embedding IPython: http://ipython.scipy.org/doc/manual/node9.html Using the Python debugger (pdb) (with IPython): http://ipython.scipy.org/doc/manual/node10.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From ingoogni at CUT.THIS.OUT.home.nl Tue Jun 13 18:49:15 2006 From: ingoogni at CUT.THIS.OUT.home.nl (ingo) Date: Tue, 13 Jun 2006 16:49:15 +0000 (UTC) Subject: [Tutor] Python related mags References: <1150165573.10769.7.camel@camille.espersunited.com> Message-ID: in news:BAY111-DAV2395C17A3AB158AFE4ACDAD8C0 at phx.gbl Evans Anyokwu wrote: > But then again, who is going to initiate the first move?? > Here's a name: Monthly Python From michael at espersunited.com Tue Jun 13 18:56:14 2006 From: michael at espersunited.com (Michael Sullivan) Date: Tue, 13 Jun 2006 11:56:14 -0500 Subject: [Tutor] Python related mags In-Reply-To: References: <1150165573.10769.7.camel@camille.espersunited.com> Message-ID: <1150217775.10769.24.camel@camille.espersunited.com> On Tue, 2006-06-13 at 16:49 +0000, ingo wrote: > in news:BAY111-DAV2395C17A3AB158AFE4ACDAD8C0 at phx.gbl Evans Anyokwu wrote: > > > But then again, who is going to initiate the first move?? > > > > Here's a name: Monthly Python Yes. They had a large influence in the birth of the language, but I'm not so sure if they still do... From emily.fortuna at nist.gov Tue Jun 13 18:59:47 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Tue, 13 Jun 2006 12:59:47 -0400 Subject: [Tutor] Interfaces in Python Message-ID: <448EEF03.30605@nist.gov> Hi friends, I am learning Python and relating to my knowledge of Java... What is (Is there?) the equivalent of Java interfaces in Python? How could I write my own? Emily From mhansen at cso.atmel.com Tue Jun 13 19:15:53 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 13 Jun 2006 11:15:53 -0600 Subject: [Tutor] die or exit function? In-Reply-To: Message-ID: <008701c68f0d$0696c9d0$28645f0a@mikehansen> > -----Original Message----- > From: tutor-bounces+mhansen=cso.atmel.com at python.org > [mailto:tutor-bounces+mhansen=cso.atmel.com at python.org] On > Behalf Of Andy Koch > Sent: Tuesday, June 13, 2006 8:42 AM > To: tutor at python.org > Subject: [Tutor] die or exit function? > > Bkgd: I've been doing PHP for the last several years. > > Q: In PHP there are functions die and exit which terminate > processing of > a script with an optional string output. Is there something > similar to > this in Python? > sys.exit("something bad happened") Although it's probably better to catch the exception and deal with it and then sys.exit() if need be. Mike http://users.adelphia.net/~mahansen/programming/ From marichar at csusb.edu Tue Jun 13 18:23:07 2006 From: marichar at csusb.edu (Matt Richardson) Date: Tue, 13 Jun 2006 09:23:07 -0700 Subject: [Tutor] debug process In-Reply-To: <448ECD72.2020106@alum.rpi.edu> References: <1150180240.646e307959208@mail.bg> <448E8EBE.9050101@tds.net> <448ECD72.2020106@alum.rpi.edu> Message-ID: <448EE66B.4060400@csusb.edu> Bob Gailer wrote: > Kent Johnson wrote: >> emilia12 at mail.bg wrote: >> >>> Hello, >>> >>> Is there a way to debug (trace) the python code line by >>> line? >>> I'll put in my $.02 for SPE. PyChecker and Tab Nanny are built in and run as you code, which saved me from making lots of silly mistakes. -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino work: (909)537-7598 fax: (909)537-5926 From dkuhlman at rexx.com Tue Jun 13 20:58:32 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 13 Jun 2006 11:58:32 -0700 Subject: [Tutor] Interfaces in Python In-Reply-To: <448EEF03.30605@nist.gov> References: <448EEF03.30605@nist.gov> Message-ID: <20060613185832.GA48838@cutter.rexx.com> On Tue, Jun 13, 2006 at 12:59:47PM -0400, Emily Fortuna wrote: > Hi friends, > I am learning Python and relating to my knowledge of Java... What is (Is > there?) the equivalent of Java interfaces in Python? How could I write > my own? > Emily > You may be interested in this article: http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html And, ... The following is more in the way of trying to keep the discussion going than it is a real solution. Using Zope interfaces, if you are not already using Zope, seems like more trouble than it is worth. Still, especially for someone who is interested in tutoring and teaching new Python programmers, possibly programmers who are familiar with Java, Zope interfaces may be worth thinking about. Although this is implemented in the Zope distribution, I believe that it is usable outside of Zope applications. See: http://www.zope.org/Wikis/Interfaces/FrontPage http://svn.zope.org/Zope3/trunk/src/zope/interface/README.txt?view=markup Here is a trivial example: from zope.interface import Interface, implements class IA(Interface): def show(self, level): """Show this object. """ class A: implements(IA) def show(self, msg): print '(A.show) msg: "%s"' % msg def test(): a = A() a.show('hello') print IA.implementedBy(A) test() In order for this to work, I believe you will need: my_zope_install/lib/python on your PYTHONPATH. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From francois.schnell at gmail.com Tue Jun 13 22:05:41 2006 From: francois.schnell at gmail.com (francois schnell) Date: Tue, 13 Jun 2006 22:05:41 +0200 Subject: [Tutor] die or exit function? In-Reply-To: <008701c68f0d$0696c9d0$28645f0a@mikehansen> References: <008701c68f0d$0696c9d0$28645f0a@mikehansen> Message-ID: <13a83ca10606131305m4db51745lc87566bc405cf826@mail.gmail.com> On 13/06/06, Mike Hansen wrote: > > > > > -----Original Message----- > > From: tutor-bounces+mhansen=cso.atmel.com at python.org Wait a minute, is that "atmel" in your e-mail address the one I think of ? http://en.wikipedia.org/wiki/Atmel If so please thank the AVR gurus for making the best quality/price microcontrollers in the world. I'm an happy user of an atmega8 and Python in this project: http://www.liberlab.net/ If by any chance your going to europython 2006 I'll be glad to show you that. I've just been looking at your blog and I've seen the "Perl, the language I love to hate". Personally I love this little cartoon about Perl : http://mirror5.escomposlinux.org/comic/ecol-13-e.png And if you have Perl working colleges you want to protect from I found this on the web ;) http://scott.weston.id.au/software/pymissile-20060126/ cheers francois > [mailto:tutor-bounces+mhansen=cso.atmel.com at python.org] On > > Behalf Of Andy Koch > > Sent: Tuesday, June 13, 2006 8:42 AM > > To: tutor at python.org > > Subject: [Tutor] die or exit function? > > > > Bkgd: I've been doing PHP for the last several years. > > > > Q: In PHP there are functions die and exit which terminate > > processing of > > a script with an optional string output. Is there something > > similar to > > this in Python? > > > > > sys.exit("something bad happened") > > Although it's probably better to catch the exception and deal with it and > then sys.exit() if need be. > > Mike > http://users.adelphia.net/~mahansen/programming/ > > _______________________________________________ > 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/20060613/d33b8f59/attachment.html From kent37 at tds.net Wed Jun 14 14:16:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jun 2006 08:16:59 -0400 Subject: [Tutor] Interfaces in Python In-Reply-To: <448EEF03.30605@nist.gov> References: <448EEF03.30605@nist.gov> Message-ID: <448FFE3B.4000804@tds.net> Emily Fortuna wrote: > Hi friends, > I am learning Python and relating to my knowledge of Java... What is (Is > there?) the equivalent of Java interfaces in Python? How could I write > my own? Explicit, formal interfaces are used much less frequently in Python than in Java, and for beginners they are not needed at all. In Python, interfaces are often implicit and defined only by usage and documentation. Sometimes the usage is called a protocol. Because Python is dynamic, there is not need to declare the type of an object, you just use it in the desired way. This is called "duck typing". http://c2.com/cgi/wiki?DuckTyping For example, the Python docs often talk about a "file-like object". A file-like object is any object that implements enough of the file protocol to act like a file. In some contexts, it might be enough to implement a read() method; in other contexts, the full file protocol might be needed. The StringIO module contains a class that implements a file-like wrapper around a memory buffer. An instance of StringIO can be passed to any function that expects an open file. StringIO doesn't inherit from any interface, it just implements the needed functions. Large Python projects seem to need something more formal than this. I think Zope, Twisted and PEAK have all invented ways to formalize this notion, and one of them may become part of Python in the future. But for small projects, duck typing and implicit protocols work pretty well. I hope someone else will explain this better than me... Kent From doug.shawhan at gmail.com Wed Jun 14 15:17:18 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 14 Jun 2006 08:17:18 -0500 Subject: [Tutor] die or exit function? In-Reply-To: References: Message-ID: <5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com> Hi Andy, Putting a try:/except: loop in your __main__() (or whatever you call your base function) with sys.exit("Message") is pretty much the way I always do it. try: gak = puke + die except: sys.exit("Oy!") If you would like sys.exit() to provide you with a bit more information (like what actually happened during the failure and where!) I found this handy function: def formatExceptionInfo(maxTBlevel=5): cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__["args"] except KeyError: excArgs = "" excArgsString = '' for item in excArgs: excArgsString = excArgsString + ' ' + str(item) excTb = traceback.format_tb(trbk, maxTBlevel) excTbString = '' for item in excTb: excTbString = excTbString + " " + str(item) report = "%s %s %s"%(excName, excArgsString, excTbString) return(report) This function now goes in most of what I do that requires error reporting. Hope this helps! On 6/13/06, Andy Koch wrote: > Bkgd: I've been doing PHP for the last several years. > > Q: In PHP there are functions die and exit which terminate processing of > a script with an optional string output. Is there something similar to > this in Python? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From andy.koch at pc-doctor.com Wed Jun 14 16:26:17 2006 From: andy.koch at pc-doctor.com (Andy Koch) Date: Wed, 14 Jun 2006 07:26:17 -0700 Subject: [Tutor] die or exit function? In-Reply-To: <5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com> References: <5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com> Message-ID: doug shawhan wrote: > Hi Andy, > > Putting a try:/except: loop in your __main__() (or whatever you call > your base function) with sys.exit("Message") is pretty much the way I > always do it. > > try: > gak = puke + die > except: > sys.exit("Oy!") > > If you would like sys.exit() to provide you with a bit more > information (like what actually happened during the failure and > where!) I found this handy function: > > > def formatExceptionInfo(maxTBlevel=5): > cla, exc, trbk = sys.exc_info() > excName = cla.__name__ > try: > excArgs = exc.__dict__["args"] > except KeyError: > excArgs = "" > > excArgsString = '' > for item in excArgs: > excArgsString = excArgsString + ' ' + str(item) > > excTb = traceback.format_tb(trbk, maxTBlevel) > excTbString = '' > for item in excTb: > excTbString = excTbString + " " + str(item) > > report = "%s %s %s"%(excName, excArgsString, excTbString) > return(report) > > This function now goes in most of what I do that requires error reporting. > > Hope this helps! > > On 6/13/06, Andy Koch wrote: >> Bkgd: I've been doing PHP for the last several years. >> >> Q: In PHP there are functions die and exit which terminate processing of >> a script with an optional string output. Is there something similar to >> this in Python? >> >> _______________________________________________ >> 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 > Hi Doug, copied and pasted, thanks although my reason for the die() was that I've started using Python to do DB maintenance. I find it very handy (ie IDLE) and the DB api's for all the different DB's I work with are nice and standardized (PHP could learn a thing there). One thing that has happened, though, is that I've clicked (via Winders Explorer) on a .py to open it for edit only to it have run, which is not what I want when the code could start modifying data. Thus far it hasn't caused any damage. So my safety check is to do a raw_input from a commonly included module which does the sys.exit() if running the code is not desired. A basic safety catch. From andrew.arobert at gmail.com Wed Jun 14 20:40:31 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 14 Jun 2006 14:40:31 -0400 Subject: [Tutor] If then else question Message-ID: <4490581F.8080901@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, In the middle of an if then else, I have the following line elif ch_val == '040' or ch_val == '011' or ch_val == '012': The line works but it is a little ungainly. Anyone have a better way of accomplishing the same thing? - -- Thank you, Andrew Robert -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys 4B/Q6g9m+3DW+PzcnCpki6k= =t0E4 -----END PGP SIGNATURE----- From mhansen at cso.atmel.com Wed Jun 14 20:48:08 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 14 Jun 2006 12:48:08 -0600 Subject: [Tutor] If then else question In-Reply-To: <4490581F.8080901@gmail.com> Message-ID: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Andrew Robert > Sent: Wednesday, June 14, 2006 12:41 PM > To: Python Tutor > Subject: [Tutor] If then else question > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Everyone, > > In the middle of an if then else, I have the following line > > elif ch_val == '040' or ch_val == '011' or ch_val == '012': > > > The line works but it is a little ungainly. > > Anyone have a better way of accomplishing the same thing? > > > - -- > Thank you, > Andrew Robert > Maybe... elif ch_val in ['040', '011', '012']: Mike http://users.adelphia.net/~mahansen/programming/ From jason.massey at gmail.com Wed Jun 14 20:50:00 2006 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 14 Jun 2006 13:50:00 -0500 Subject: [Tutor] If then else question In-Reply-To: <4490581F.8080901@gmail.com> References: <4490581F.8080901@gmail.com> Message-ID: <7e3eab2c0606141150u479044ddn64f46d548be5ec28@mail.gmail.com> How about: elif ch_val in ['040','011','012']: On 6/14/06, Andrew Robert wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Everyone, > > In the middle of an if then else, I have the following line > > elif ch_val == '040' or ch_val == '011' or ch_val == '012': > > > The line works but it is a little ungainly. > > Anyone have a better way of accomplishing the same thing? > > > - -- > Thank you, > Andrew Robert > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.1 (MingW32) > Comment: GnuPT 2.7.2 > > iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys > 4B/Q6g9m+3DW+PzcnCpki6k= > =t0E4 > -----END PGP SIGNATURE----- > _______________________________________________ > 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/20060614/3370a503/attachment.html From dustin at ywlcs.org Wed Jun 14 20:51:20 2006 From: dustin at ywlcs.org (Dustin Mitchell) Date: Wed, 14 Jun 2006 13:51:20 -0500 Subject: [Tutor] If then else question In-Reply-To: <4490581F.8080901@gmail.com> References: <4490581F.8080901@gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 How about .. elif ch_val in ('040', '011', '012'): .. On Jun 14, 2006, at 1:40 PM, Andrew Robert wrote: > In the middle of an if then else, I have the following line > > elif ch_val == '040' or ch_val == '011' or ch_val == '012': > > > The line works but it is a little ungainly. > > Anyone have a better way of accomplishing the same thing? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (Darwin) iD8DBQFEkFqydiVAPX8NFbERAl03AKCSkXjFB1bA0xUo4Tf8wNF462DllQCg37ir iu+TIlJst9AjjN0Qz3rijPU= =FF5s -----END PGP SIGNATURE----- From andrew.arobert at gmail.com Wed Jun 14 20:53:44 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 14 Jun 2006 14:53:44 -0400 Subject: [Tutor] If then else question In-Reply-To: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen> References: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen> Message-ID: <44905B38.5000504@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Excellent.. much better than testing each value independently. Thank you. Mike Hansen wrote: > > >> -----Original Message----- >> From: tutor-bounces at python.org >> [mailto:tutor-bounces at python.org] On Behalf Of Andrew Robert >> Sent: Wednesday, June 14, 2006 12:41 PM >> To: Python Tutor >> Subject: [Tutor] If then else question >> >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hi Everyone, >> >> In the middle of an if then else, I have the following line >> >> elif ch_val == '040' or ch_val == '011' or ch_val == '012': >> >> >> The line works but it is a little ungainly. >> >> Anyone have a better way of accomplishing the same thing? >> >> >> - -- >> Thank you, >> Andrew Robert >> > > Maybe... > > elif ch_val in ['040', '011', '012']: > > Mike > http://users.adelphia.net/~mahansen/programming/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEkFs3Dvn/4H0LjDwRApi/AJ4lyyJOoHWt1NzMBPF2gF7qQsA9WgCguYcd MmjCVxL4giSzpdA1pRKgnHc= =y80v -----END PGP SIGNATURE----- From kent37 at tds.net Wed Jun 14 20:56:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jun 2006 14:56:13 -0400 Subject: [Tutor] If then else question In-Reply-To: <4490581F.8080901@gmail.com> References: <4490581F.8080901@gmail.com> Message-ID: <44905BCD.9000202@tds.net> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Everyone, > > In the middle of an if then else, I have the following line > > elif ch_val == '040' or ch_val == '011' or ch_val == '012': > > > The line works but it is a little ungainly. > > Anyone have a better way of accomplishing the same thing? elif ch_val in [ '040', '011', '012' ]: or maybe you like elif ch_val in '040 011 012'.split(): Kent From alan.gauld at freenet.co.uk Thu Jun 15 02:06:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 15 Jun 2006 01:06:38 +0100 Subject: [Tutor] Interfaces in Python References: <448EEF03.30605@nist.gov> Message-ID: <001d01c6900f$92984640$0301a8c0@XPpro> > I am learning Python and relating to my knowledge of Java... What is > (Is there?) the equivalent of Java interfaces in Python? How could > I write my own? There is no direct equivalent. Interfaces are implicit in Python, they are only really necessary in statically typed languages. Dynamically typed languages rely on "Duck typing" and therefore the concept of an interface is not required. ( Interfaces are a serious impediment to good OO design IMHO, they imply an element of fore knowledge of how a class will be used and involve additional work that often is not needed. They are basically a flexibility point introduced to mitigate against change in a static typing environment) A good example of duck typing is the concept of a "file like object" which is used in several places in Python. It basically means any object which has the same message protocol as a file. This is the saqme style of OOP used in SmallTalk, Lisp and ObjectiveC (although the latter also supports statically typed interfaces too) [ It is possible to create abstract classes in Python however using some sneaky tricks but the easiest way is probably just to throw an exception in the init method! Abstract classes are an alternative way to view interfaces - interaces are cut-down abstract classes...] Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jun 15 02:15:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 15 Jun 2006 01:15:46 +0100 Subject: [Tutor] Interfaces in Python References: <448EEF03.30605@nist.gov> <448FFE3B.4000804@tds.net> Message-ID: <004301c69010$d94d8310$0301a8c0@XPpro> > Large Python projects seem to need something more formal than this. > I think Zope, Twisted and PEAK have all invented ways to formalize > this notion, and one of them may become part of Python in the > future. I think thats more to do with the background of the programmers involved. > small projects, duck typing and implicit protocols work pretty well. Even for large projects. Lisp, SmallTalk and ObjectiveC all use duck typing and some very large projects (several 100K of code, and a few million line plus projects) have been built using those languages. The important point is that duck typing needs to be combined with exception handling and exceptions have to be written to catch the Attribute errors that result from incorrect protocol behaviour. Provided that is done duck typing is no worse than static typed interfaces, its just a different approach. > I hope someone else will explain this better than me... I thought you did pretty good Kent! Alan G. (Just back from the Enterprise Architecture 2006 conference...) From govilakanksha at yahoo.com Thu Jun 15 12:04:10 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Thu, 15 Jun 2006 03:04:10 -0700 (PDT) Subject: [Tutor] Need info regd Singleton class implementation Message-ID: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com> hi, I need to implement a singleton class in python. Please give me some refernce sites which can help me with the same. Also i want to know to call a destructor for a singleton class. Thanks Akanksha __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060615/ed4c6f58/attachment.html From andre.roberge at gmail.com Thu Jun 15 12:25:29 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 15 Jun 2006 07:25:29 -0300 Subject: [Tutor] Need info regd Singleton class implementation In-Reply-To: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com> References: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com> Message-ID: <7528bcdd0606150325p71fc7a4u5e5b9c99c72a1a9f@mail.gmail.com> On 6/15/06, Akanksha Govil wrote: > hi, > > I need to implement a singleton class in python. > Please give me some refernce sites which can help me with the same. The online Python Cookbook is a good reference site. Here's the result from a search: http://aspn.activestate.com/ASPN/search?query=singleton&x=0&y=0§ion=PYTHONCKBK&type=Subsection I use the following from the printed edition of the Python Cookbook: class Singleton(object): """From the 2nd edition of the Python cookbook. Ensures that only one instance is created per running script""" def __new__(cls, *args, **kwargs): if '_inst' not in vars(cls): cls._inst = object.__new__(cls, *args, **kwargs) return cls._inst Andr? > > Also i want to know to call a destructor for a singleton class. > > Thanks > Akanksha > > > > __________________________________________________ > 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 kent37 at tds.net Thu Jun 15 14:05:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jun 2006 08:05:30 -0400 Subject: [Tutor] Need info regd Singleton class implementation In-Reply-To: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com> References: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com> Message-ID: <44914D0A.5030806@tds.net> Akanksha Govil wrote: > I need to implement a singleton class in python. > Please give me some refernce sites which can help me with the same. Singletons are not used that much in Python, perhaps because the general culture of "we're all adults here" is biased against enforcing usage patterns. If you want to have a master reference to an object you can just make it a module attribute. Then any client that needs access to the object just imports the module. Why do you need a singleton? Is this homework? > Also i want to know to call a destructor for a singleton class. In Python, destructors (__del__() methods) are called on an object when it is garbage-collected. The details of when this happens vary between different Python implementations. In CPython (the standard Python from python.org), an object is garbage-collected when its reference count goes to 0 - when there are no names that refer to the object. So if you want the __del__() method of an object to be called, you have to ensure that there are no references to the object. In the case of a singleton, this would mean deleting or assigning None to the name that holds the master reference, and ensuring that no users of the singleton retain references to it. Kent From tinoloc at gmail.com Thu Jun 15 15:20:23 2006 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 15 Jun 2006 09:20:23 -0400 Subject: [Tutor] Question about network server in python Message-ID: Hi there, I am wondering if somebody to could answer a question about sockets. I have a socket that is listening, and a client program connects to it. The client program transfers a name over, and then disconnects from the socket. Now, how that is done is using a socket.close() call to shut down the entire socket. My question is: Is there a way to have the socket close the connection, yet stay open for the next client that comes along and connects to the server? I have my already written code below for further documentation. Thanks! while 1: s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((self.ipAddr,self.port)) s.listen(5) print "The port is: ", self.port client,addr=s.accept() while 1: try: if addr[0] == self.remoteIpAddr: client.send("Connected to the server\n") msg=client.recv(1024) msg=msg.strip() if msg in 'exit': s.close() #Is there a different way to write this? time.sleep(30) print "exiting" break if len(msg) > 0: -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060615/d00d3a39/attachment.htm From pjlists at gmail.com Thu Jun 15 16:17:37 2006 From: pjlists at gmail.com (Peter Jessop) Date: Thu, 15 Jun 2006 16:17:37 +0200 Subject: [Tutor] Question about network server in python In-Reply-To: References: Message-ID: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com> I think the problem here is the 'break' statement. Does it not put you outside the while loop whereas in order to keep the server socket open you need it to loop forever. I also think that the s.accept should be inside the while loop. From pjlists at gmail.com Thu Jun 15 16:42:33 2006 From: pjlists at gmail.com (Peter Jessop) Date: Thu, 15 Jun 2006 16:42:33 +0200 Subject: [Tutor] Question about network server in python In-Reply-To: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com> References: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com> Message-ID: <7a8d5a0c0606150742i18e5f897ycff4bb8edf47321d@mail.gmail.com> import socket host = '' port = 57000 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host,port)) s.listen(5) while 1: client,addr=s.accept() client.send("Connected to the server\n") #if someCondition: # cliente.close() From kent37 at tds.net Thu Jun 15 16:45:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jun 2006 10:45:38 -0400 Subject: [Tutor] Question about network server in python In-Reply-To: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com> References: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com> Message-ID: <44917292.6010001@tds.net> Peter Jessop wrote: > I think the problem here is the 'break' statement. > Does it not put you outside the while loop whereas in order to keep > the server socket open you need it to loop forever. > > I also think that the s.accept should be inside the while loop. There are two loops, I think you missed the outer loop. Kent From kent37 at tds.net Thu Jun 15 16:54:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jun 2006 10:54:26 -0400 Subject: [Tutor] Question about network server in python In-Reply-To: References: Message-ID: <449174A2.5040906@tds.net> Tino Dai wrote: > Hi there, > > I am wondering if somebody to could answer a question about > sockets. I have a socket that > is listening, and a client program connects to it. The client program > transfers a name over, and then disconnects from the socket. Now, how > that is done is using a socket.close() call to shut down the entire > socket. My question is: Is there a way to have the socket close the > connection, yet stay open for the next client that comes along and > connects to the server? I have my already written code below for further > documentation. Thanks! > > while 1: > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) > s.bind((self.ipAddr,self.port)) > s.listen(5) > print "The port is: ", self.port > client,addr=s.accept() > while 1: > try: > if addr[0] == self.remoteIpAddr: > client.send("Connected to the server\n") > msg=client.recv(1024) > msg=msg.strip() > if msg in 'exit': > s.close() #Is there a different > way to write this? I think you want to close the client socket - client.close() - rather than the master socket. You might be interested in the SocketServer library which helps to write simple socket servers such as this. One advantage of using SocketServer is it makes it trivial to convert your server to a threaded or forked server. Here are some examples: http://www.amk.ca/python/simple/fingerd.py.html http://examples.oreilly.com/pythonian/ see example 19-5 Kent > time.sleep(30) > print "exiting" > break > if len(msg) > 0: > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From learner404 at gmail.com Thu Jun 15 21:09:00 2006 From: learner404 at gmail.com (learner404) Date: Thu, 15 Jun 2006 21:09:00 +0200 Subject: [Tutor] WinXP IDLE -> open file : how-to change default directory ? Message-ID: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com> Hello, On WinXP IDLE will always 'open' in Python24 folder at startup. A beginner friend of mine hate that (personally I use SPE) and I tried 'quickly' to find a way to configure that for him. I found all the .cfg files in idlelib and also the .idlerc folder in the "Documents and settings" but I don't see how to give IDLE a default directory at startup (or kipping in memory the last one opened). How to do that or is it just not possible ? Thanks learner404 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060615/1802c3e6/attachment.htm From learner404 at gmail.com Thu Jun 15 22:48:20 2006 From: learner404 at gmail.com (learner404) Date: Thu, 15 Jun 2006 22:48:20 +0200 Subject: [Tutor] WinXP IDLE -> open file : how-to change default directory ? In-Reply-To: <001001c690b7$eab7b240$0200a8c0@kookaburra> References: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com> <001001c690b7$eab7b240$0200a8c0@kookaburra> Message-ID: <13a83ca10606151348g602b6cc3jc25d16f7a124811e@mail.gmail.com> On 15/06/06, Matthew Webber wrote: > > Try right-clicking on the shortcut, select properties, and change the > "start > in" value. > Matthew Scary, I didn't know that windows had that ... Thanks very much Matthew ! P.S. When posting to the list, please use plain text format. > > ________________________________ > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] > On > Behalf Of learner404 > Sent: 15 June 2006 20:09 > To: tutor at python.org > Subject: [Tutor] WinXP IDLE -> open file : how-to change default > directory ? > > > Hello, > > On WinXP IDLE will always 'open' in Python24 folder at startup. > > A beginner friend of mine hate that (personally I use SPE) and I > tried 'quickly' to find a way to configure that for him. > > I found all the .cfg files in idlelib and also the .idlerc folder > in > the "Documents and settings" but I don't see how to give IDLE a default > directory at startup (or kipping in memory the last one opened). > > How to do that or is it just not possible ? > > Thanks > > learner404 > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060615/77674507/attachment-0001.html From alan.gauld at btinternet.com Fri Jun 16 01:05:41 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Jun 2006 00:05:41 +0100 Subject: [Tutor] XML: Expletive Deleted (OT) References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com> Message-ID: Just picked this up after being out for most of the week... "Carroll, Barry" wrote in message > One reason to for choosing a human-readable format is the desire to > visually confirm the correctness of the stored data and format. Thats a very dangerous asumption, how do you detect unprintable characters, tabs instead of spaces, trailing spaces on a line etc etc. Whole text representations are helpful you should never rely on the human eye to validate a data file. > can be invaluable when troubleshooting a bug involving stored data. > If > there is a tool between the user and the data, one must then rely > upon > the correctness of the tool to determine the correctness of the > data. Or the correctness of the eye. I know which one i prefer - a tested tool. The human eye is not a dta parser, but it flatters to deceive by being nearly good enough. > In a case like this, nothing beats the evidence of one's eyes, IMHO. Almost anything beats the human eye IME :-) Actually if you must use eyes do so on a hex dump of the file, that is usually reliable enough if you can read hex... > In their book, "The Pragmatic Programmer: From Journeyman to Master" > (Addison Wesley Professional), Andrew Hunt and David Thomas give > another > reason for storing data in human readable form: > > The problem with most binary formats is that the context > necessary > to understand the data is separate from the data itself. You are > artificially divorcing the data from its meaning. The data may > as well be encrypted; it is absolutely meaningless without the > application logic to parse it. With plain text, however, you can > achieve a self-describing data stream that is independent of the > application that created it. But at a very high risk. I do not dislike text files BTW and am not suggesting that text should not be used but its parsing is best left to machines, the eye is only a rough and unreliable guide. And if your data volumes are high go with binary, you'll need tools to parse a lot of data anyway, you might as well save the space! The Hunt/Thomas book is excellent BTW - I recommend it highly. Even though I disagree witrh several of their suggestions(*) I agree with far more. (*)They recommend sticking with one text editor whereas I use about 5 or 6 on a regular basis depending on the job I'm doing and the platform I'm working on. Emacs on X Windows for new files but vim for quick fix ups, vim on Windows for most things, ed or ex for text based email or over a phone line. > This is an example of the resource balancing act that computer > people > have been faced with since the beginning. The most scarce/expensive > resource dictates the program's/system's design. In Alan's example > high > speed bandwidth is the limiting resource. A data transmission > method > that fails to minimize use of that resource is therefore a bad > solution. Unfortunately the software industry is full of people who by and large don't understand networks so they just ignoire them. At least thats my experience! SOA using SOAP/XML is probably the most inefficient and unreliable set of data networking technologies you could possible come up with. But the focus is on cutting developer cost because the people inventing it are developers! In almost every sizewable project the cost of development will be significantly less than the cost of deployment - in most of my projects it usually works out something like: development - 15% deployment - 30% support - 15% training - 25% documentation - 5% management overhead - 10% Saving 25% of development costs rediuced total cost by around 4% but if that puts deployment costs up by 10% the net gain is only 1%! And in XML case it often puts deployment costs up by 100% - a net loss of 24%!! Now those figures come from a typical project that I work on which probably has a total budget of betwen $10-100 million. If your budget is smaller, say less than $1 million then the balance may well change. But over 50% of the IT industry works on projects with >$1m budgets according to both Datamation and Infoweek. [ The only SOA/XML book that addresses this side of XML usage is the excellent "SOA - A Field Guide" by Peter Erls. Erls also suggests some mitigating strategies to get round it.] > So here's my off-topic question: Ajax is being touted as the > 'best-known > method' (BKM) for making dynamic browser-based applications, and XML > is > the BKM for transferring data in Ajax land. If XML is a bad idea > for > network data-transfer, what medium should be used instead? The example I gave of having to upgrade the sites network was actually an early adopter of XML/Ajax architecture! There are lots of other data formats around - some are even self describing (CSV and TLV are cases) Others simply hold the definition in an accessible library so you only have to transport it once - eg IDL and ASN.1 - or optionally compile it into your code for maximum efficiency. ASN./1 is typically around 50 times more compact than XML - that makes a big difference over a DSL line and even bigger over dial-up modem or GPRS link.... XML has its place but that place has to be guaged very carefully. Unfortunately I don't see much acknowledgement of its weaknesses in the industry at large, instead it is being deployed with wild abandon! Alan g. From cspears2002 at yahoo.com Fri Jun 16 02:29:01 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 15 Jun 2006 17:29:01 -0700 (PDT) Subject: [Tutor] lambda and creating GUIs Message-ID: <20060616002901.90354.qmail@web51607.mail.yahoo.com> I have been reading though the PyGTK tutorial. Can anyone explain how lambda is being used in this statement: button.connect("clicked", lambda w: gtk.main_quit()) This code might put the statement in context: # Create "Quit" button 66 button = gtk.Button("Quit") 67 68 # When the button is clicked, we call the main_quit function 69 # and the program exits 70 button.connect("clicked", lambda w: gtk.main_quit()) 71 72 # Insert the quit button into the both lower quadrants of the table 73 table.attach(button, 0, 2, 1, 2) 74 75 button.show() The complete script is located at http://www.pygtk.org/pygtk2tutorial/sec-TablePackingExample.html. From john at fouhy.net Fri Jun 16 03:22:02 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 16 Jun 2006 13:22:02 +1200 Subject: [Tutor] lambda and creating GUIs In-Reply-To: <20060616002901.90354.qmail@web51607.mail.yahoo.com> References: <20060616002901.90354.qmail@web51607.mail.yahoo.com> Message-ID: <5e58f2e40606151822y116e0526j5fb63ef6e0a6c6ca@mail.gmail.com> (resending to include Tutor -- sorry for the dupe, Christopher) On 16/06/06, Christopher Spears wrote: > I have been reading though the PyGTK tutorial. > Can anyone explain how lambda is being used in this > statement: > > button.connect("clicked", lambda w: gtk.main_quit()) Do you understand what lambda does in general? Does it help if I rewrite the code like this: def onQuit(w): gtk.main_quit() button.connect("clicked", onQuit) ? Provided you get your indentation correct ("def onQuit" and "button.connect" should be at the same level), and provided you aren't using the name "onQuit" somewhere else in that method, this code should be a dropin replacement for the line you quote. -- John. From sean.x.lee at gmail.com Fri Jun 16 09:24:12 2006 From: sean.x.lee at gmail.com (Sean Lee) Date: Fri, 16 Jun 2006 02:24:12 -0500 Subject: [Tutor] detect 64-bit windows Message-ID: In Python, how to do that ? sys.platform only gives 'win32', no info about 32-bit or 64 bit ? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060616/0652b867/attachment.html From Matthew at CuneiformSoftware.com Thu Jun 15 22:11:40 2006 From: Matthew at CuneiformSoftware.com (Matthew Webber) Date: Thu, 15 Jun 2006 21:11:40 +0100 Subject: [Tutor] WinXP IDLE -> open file : how-to change default directory ? In-Reply-To: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com> Message-ID: <001001c690b7$eab7b240$0200a8c0@kookaburra> Try right-clicking on the shortcut, select properties, and change the "start in" value. Matthew P.S. When posting to the list, please use plain text format. ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of learner404 Sent: 15 June 2006 20:09 To: tutor at python.org Subject: [Tutor] WinXP IDLE -> open file : how-to change default directory ? Hello, On WinXP IDLE will always 'open' in Python24 folder at startup. A beginner friend of mine hate that (personally I use SPE) and I tried 'quickly' to find a way to configure that for him. I found all the .cfg files in idlelib and also the .idlerc folder in the "Documents and settings" but I don't see how to give IDLE a default directory at startup (or kipping in memory the last one opened). How to do that or is it just not possible ? Thanks learner404 From alan.gauld at freenet.co.uk Fri Jun 16 12:16:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Jun 2006 11:16:53 +0100 Subject: [Tutor] lambda and creating GUIs References: <20060616002901.90354.qmail@web51607.mail.yahoo.com> Message-ID: <001001c6912e$139e6a70$0301a8c0@XPpro> >I have been reading though the PyGTK tutorial. > Can anyone explain how lambda is being used in this > statement: > > button.connect("clicked", lambda w: gtk.main_quit()) lambda is being used to create an anonymous function. The code could be rewritten like this: def f(w): gtk.main_quit() button.connect("clicked", f) lambda simply saves cluttering up the code with lots of tiny function derfinitions which are never referred to apart from in the binding operation. You can read about lambdas in the functional programming topic in my tutor HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jun 16 12:23:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Jun 2006 11:23:00 +0100 Subject: [Tutor] XML: Expletive Deleted (OT) References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com> Message-ID: <001c01c6912e$d86aaa30$0301a8c0@XPpro> > [ The only SOA/XML book that addresses this side of XML usage > is the excellent "SOA - A Field Guide" by Peter Erls. Erls also > suggests some mitigating strategies to get round it.] Oops, don't rely on memory... That is Thomas Erl not Peter Erls. And of course there may be other SOAP/XML books deal with these issues, but Erl's book is the only one I've read that does so! Alan G. From kieran.flanagan at gmail.com Fri Jun 16 15:47:56 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Fri, 16 Jun 2006 14:47:56 +0100 Subject: [Tutor] Writing to a remote file Message-ID: Hi I want to run a script on one machine and log output messages to a remote file located on another machine. Is there any easy method of doing this ?. Thanks Kieran -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060616/0b70a262/attachment.htm From kent37 at tds.net Fri Jun 16 16:54:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jun 2006 10:54:34 -0400 Subject: [Tutor] Writing to a remote file In-Reply-To: References: Message-ID: <4492C62A.5070302@tds.net> kieran flanagan wrote: > Hi > > I want to run a script on one machine and log output messages to a > remote file located on another machine. Is there any easy method of > doing this ?. Depends on the details, I suppose... If the remote file is on a network file system accessible to the machine running the script it should be easy - just open the file and write to it. For example on Windows you should be able to write f = open(r'\\server\path\to\logfile.txt', 'w') print >>f, 'This is a very serious matter' or configure the file path in your logging properties or whatever... If the remote file system is *not* accessible from the local machine, then you need some way to talk to the remote machine. Kent From amresh.kulkarni at gmail.com Fri Jun 16 17:26:34 2006 From: amresh.kulkarni at gmail.com (Amresh Kulkarni) Date: Fri, 16 Jun 2006 10:26:34 -0500 Subject: [Tutor] Delete directories recursively Message-ID: Hi, I need to delete a directory and its sub directories. However all dir's, sub dir;s and files have read only access. How do i do this efficeintly using the os.walk command. I cannot run this command on the dir as it gives me an error due to the read only attribute. Is there any other way to do this? -- ~~AMRESH~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060616/7d787a1c/attachment.htm From kent37 at tds.net Fri Jun 16 17:39:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jun 2006 11:39:37 -0400 Subject: [Tutor] Delete directories recursively In-Reply-To: References: Message-ID: <4492D0B9.8040704@tds.net> Amresh Kulkarni wrote: > Hi, > > I need to delete a directory and its sub directories. However all dir's, > sub dir;s and files have read only access. How do i do this efficeintly > using the os.walk command. > I cannot run this command on the dir as it gives me an error due to the > read only attribute. Is there any other way to do this? Maybe I'm missing something, but I don't understand how you expect to delete a directory if you don't have delete permission? Kent From mwhite3 at ttsd.k12.or.us Fri Jun 16 17:40:04 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Fri, 16 Jun 2006 08:40:04 -0700 Subject: [Tutor] Delete directories recursively In-Reply-To: References: Message-ID: <20060616154004.GN12754@ttsd.k12.or.us> You must change the directory and file permissions before attempting to remove them; even if you are using a python script. Take a look at os.chmod() -mtw On Fri, Jun 16, 2006 at 10:26:34AM -0500, Amresh Kulkarni (amresh.kulkarni at gmail.com) wrote: > Hi, > > I need to delete a directory and its sub directories. However all dir's, sub > dir;s and files have read only access. How do i do this efficeintly using > the os.walk command. > I cannot run this command on the dir as it gives me an error due to the read > only attribute. Is there any other way to do this? > > -- > ~~AMRESH~~ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lkvam at venix.com Fri Jun 16 18:24:45 2006 From: lkvam at venix.com (Lloyd Kvam) Date: Fri, 16 Jun 2006 12:24:45 -0400 Subject: [Tutor] Writing to a remote file In-Reply-To: References: Message-ID: <1150475085.27979.136.camel@www.venix.com> On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote: > Hi > > I want to run a script on one machine and log output messages to a > remote file located on another machine. Is there any easy method of > doing this ?. http://docs.python.org/lib/module-logging.html If the remote machine is a file server, you can use the logging module to write to a file on the remote machine Also the logging module can be used to easily log to a syslog handler. If this remote file is a "normal" log file managed by a syslog process then you should find the python part pretty easy. The syslog process still needs to be configured to accept your logging messages, but that should not be too difficult. Scanning the logging module docs, it looks like you can use it to write your own process to run on the remote machine to handle "logging messages". Then use the logging module on the local machine to send "logging messages" to the remote machine. > Thanks > Kieran > > -- > "Behind every great man, there is a great woman. Behind that woman is > Mr.T." > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 From kent37 at tds.net Fri Jun 16 19:21:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jun 2006 13:21:59 -0400 Subject: [Tutor] Writing to a remote file In-Reply-To: <1150475085.27979.136.camel@www.venix.com> References: <1150475085.27979.136.camel@www.venix.com> Message-ID: <4492E8B7.9080306@tds.net> Lloyd Kvam wrote: > On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote: >> Hi >> >> I want to run a script on one machine and log output messages to a >> remote file located on another machine. Is there any easy method of >> doing this ?. > Scanning the logging module docs, it looks like you can use it to write > your own process to run on the remote machine to handle "logging > messages". Then use the logging module on the local machine to send > "logging messages" to the remote machine. Cool. There's even a complete example in the docs: http://docs.python.org/lib/network-logging.html Kent From Barry.Carroll at psc.com Fri Jun 16 19:33:37 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 16 Jun 2006 10:33:37 -0700 Subject: [Tutor] Machine Vs. Human Parsing (Was: XML: Expletive Deleted) (Way OT!) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36C7@eugsrv400.psc.pscnet.com> Greetings: > -----Original Message----- > Date: Fri, 16 Jun 2006 00:05:41 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] XML: Expletive Deleted (OT) > To: tutor at python.org > Message-ID: > > Just picked this up after being out for most of the week... > > "Carroll, Barry" wrote in message > > > One reason to for choosing a human-readable format is the desire to > > visually confirm the correctness of the stored data and format. > > Thats a very dangerous asumption, how do you detect unprintable > characters, tabs instead of spaces, trailing spaces on a line etc etc. > Whole text representations are helpful you should never rely on the > human eye to validate a data file. > > > can be invaluable when troubleshooting a bug involving stored data. > > If > > there is a tool between the user and the data, one must then rely > > upon > > the correctness of the tool to determine the correctness of the > > data. > > Or the correctness of the eye. I know which one i prefer - a tested > tool. > The human eye is not a dta parser, but it flatters to deceive by being > nearly good enough. > > > In a case like this, nothing beats the evidence of one's eyes, IMHO. > > Almost anything beats the human eye IME :-) > Actually if you must use eyes do so on a hex dump of the file, that > is usually reliable enough if you can read hex... > <> > > Alan g. If I gave the impression that the human eye is the only useful means of examining and verifying stored data, I apologize. I indented to say that the human eye, and the brain that goes with it, is an invaluable tool in evaluating data. I stand by that statement. The most sophisticated tool is only as good as the developer(s) who made it. Since software is ultimately written by humans, it is fallible. It contains mistakes, gaps, holes, imperfections. When the tool gives bad, or erroneous, or incomplete results, what do you do? You look at the data. A case in point. I used to test audio subsystems on PC motherboards. The codec vendor released a new version of their chip with new driver software. Suddenly our tests began to fail. The vendor insisted their HW and SW were correct. The test owner insisted his SW was correct. Somebody was mistaken. I used an audio editing program to display the waveform of the data in the capture buffer. The first several hundred samples were not a waveform, but apparently random noise. I now knew why the test is failing, but why was there noise in the buffer? It wasn't there before. The editing SW was no help there. So I switched tools, and displayed the capture buffer with simple file dump program. The first 2K of the buffer was filled with text! The story goes on, but that's enough to illustrate my point. Neither the audio driver, nor the test SW, nor the editing tool could show the real problem. All of them were 'tested tools', but when presented with data they were not designed to handle, they produced incorrect or incomplete results. I could cite other examples from other disciplines, but this one suffices: no SW tool should be relied upon to be correct in all cases. I trust my eyes to see things tools can't, not because they can detect nonprintable characters in a HEX dump (I can read HEX dumps, and binary when necessary, but I usually just print out '\t', '[SP]', etc) but because they are not bound by anyone else's rules as to what is correct and incorrect. The programmer's two most valuable tools are her/his eyes and brain. They are always useful, sometimes indispensable. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From john.corry at ntlworld.com Fri Jun 16 19:55:56 2006 From: john.corry at ntlworld.com (John Corry) Date: Fri, 16 Jun 2006 18:55:56 +0100 Subject: [Tutor] Delete directories recursively In-Reply-To: Message-ID: Amresh, I had this problem a few months back. I approached it backwards. Maybe not the right way to do it. I removed all the files and directories and then had my exception handle the file if it was read only. The exception handler changes the file from read-only to not read only and then calls the function again. Is there a better way to do it? Would appreciate feedback on the code below. import shutil import os def zaps(self): try: shutil.rmtree('f:/m2m') except OSError, inst: print OSError os.chmod(inst.filename, 0666) self.zaps() Regards, John. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Amresh Kulkarni Sent: 16 June 2006 16:27 To: tutor at python.org Subject: [Tutor] Delete directories recursively Hi, I need to delete a directory and its sub directories. However all dir's, sub dir;s and files have read only access. How do i do this efficeintly using the os.walk command. I cannot run this command on the dir as it gives me an error due to the read only attribute. Is there any other way to do this? -- ~~AMRESH~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060616/ee8a0842/attachment.htm From kent37 at tds.net Fri Jun 16 20:04:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jun 2006 14:04:26 -0400 Subject: [Tutor] Delete directories recursively In-Reply-To: References: Message-ID: <4492F2AA.4000700@tds.net> John Corry wrote: > > Amresh, > > I had this problem a few months back. I approached it backwards. Maybe > not the right way to do it. I removed all the files and directories and > then had my exception handle the file if it was read only. The > exception handler changes the file from read-only to not read only and > then calls the function again. > > Is there a better way to do it? Would appreciate feedback on the code > below. > > import shutil > import os > > def zaps(self): > > try: > shutil.rmtree('f:/m2m') > > > except OSError, inst: > print OSError > os.chmod(inst.filename, 0666) > self.zaps() I imagine this could be expensive if you have a deep directory hierarchy with lots of read-only files - you have to start the traversal from scratch each time you get an error. If you have more than 1000 read-only files you will get a stack overflow from the recursion. shutil.rmtree() actually takes an optional error handler argument. According to the docs, "If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo. The first parameter, function, is the function which raised the exception; it will be os.listdir(), os.remove() or os.rmdir()." So something like this should work and be faster because the directory traversal doesn't restart each time (UNTESTED!!): def handle_error(fn, path, excinfo): if fn is os.rmdir: # handle readonly dir os.chmod(path, 0666) # ?? not sure if this is correct for a dir os.rmdir(path) # try again elif fn is os.remove: os.chmod(path, 0666) os.remove(path) shutil.rmtree(top, onerror=handle_error) Kent From amresh.kulkarni at gmail.com Fri Jun 16 20:56:17 2006 From: amresh.kulkarni at gmail.com (Amresh Kulkarni) Date: Fri, 16 Jun 2006 13:56:17 -0500 Subject: [Tutor] Delete directories recursively In-Reply-To: <4492F2AA.4000700@tds.net> References: <4492F2AA.4000700@tds.net> Message-ID: Thanks guys, Error handling seems to be a nice idea to approach this problem. i checked Kent's code and it works fine. I was using a more crude method. def removeDir(dirName) : #Remove any read-only permissions on file. removePermissions(dirName) for name in os.listdir(dirName): file = os.path.join(dirName, name) if not os.path.islink(file) and os.path.isdir(file): removeDir(file) else: removePermissions(file) os.remove(file) os.rmdir(dirName) return def removePermissions(filePath) : #if (os.access(filePath, os.F_OK)) : #If path exists if (not os.access(filePath, os.W_OK)) : os.chmod(filePath, 0666) return however shutil seems to be more simple and efficient here! Regards, Amresh On 6/16/06, Kent Johnson wrote: > > John Corry wrote: > > > > Amresh, > > > > I had this problem a few months back. I approached it backwards. Maybe > > not the right way to do it. I removed all the files and directories and > > then had my exception handle the file if it was read only. The > > exception handler changes the file from read-only to not read only and > > then calls the function again. > > > > Is there a better way to do it? Would appreciate feedback on the code > > below. > > > > import shutil > > import os > > > > def zaps(self): > > > > try: > > shutil.rmtree('f:/m2m') > > > > > > except OSError, inst: > > print OSError > > os.chmod(inst.filename, 0666) > > self.zaps() > > I imagine this could be expensive if you have a deep directory hierarchy > with lots of read-only files - you have to start the traversal from > scratch each time you get an error. If you have more than 1000 read-only > files you will get a stack overflow from the recursion. > > shutil.rmtree() actually takes an optional error handler argument. > According to the docs, "If onerror is provided, it must be a callable > that accepts three parameters: function, path, and excinfo. The first > parameter, function, is the function which raised the exception; it will > be os.listdir(), os.remove() or os.rmdir()." > > So something like this should work and be faster because the directory > traversal doesn't restart each time (UNTESTED!!): > > def handle_error(fn, path, excinfo): > if fn is os.rmdir: > # handle readonly dir > os.chmod(path, 0666) # ?? not sure if this is correct for a dir > os.rmdir(path) # try again > elif fn is os.remove: > os.chmod(path, 0666) > os.remove(path) > > shutil.rmtree(top, onerror=handle_error) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ~~AMRESH~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060616/2a888e96/attachment.htm From alan.gauld at freenet.co.uk Fri Jun 16 21:13:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Jun 2006 20:13:10 +0100 Subject: [Tutor] Delete directories recursively References: Message-ID: <002701c69178$e87ee090$0301a8c0@XPpro> > I need to delete a directory and its sub directories. However all > dir's, sub > dir;s and files have read only access. How do i do this efficeintly > using > the os.walk command. You can'ty since the reasoin the files are read-only is to prevent them being over-written or deleted! You need to convert them from read-only and then delete them. Its not too hard provided you have the relevant access rights to change mode. > I cannot run this command on the dir as it gives me an error due to > the read > only attribute. Is there any other way to do this? You can only do from Python what you can do from the OS. If you don't have access to the files from the OS you won't have access from Python - thats why access rights are there! For more on how to do it we need to know your OS, since this is almost certainly a job for the OS rather than Python, unless you want to do more than just delete the files. If you do have access rights then you can find out all the needed steps in the OS topic in my tutor. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jun 16 21:37:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Jun 2006 20:37:56 +0100 Subject: [Tutor] Machine Vs. Human Parsing (Was: XML: Expletive Deleted)(Way OT!) References: <2BBAEE949D384D40A2B851287ADB6A432C36C7@eugsrv400.psc.pscnet.com> Message-ID: <003301c6917c$5e4b8e60$0301a8c0@XPpro> > > Almost anything beats the human eye IME :-) > > Actually if you must use eyes do so on a hex dump of the file, > > that > > is usually reliable enough if you can read hex... > If I gave the impression that the human eye is the only useful means > of > examining and verifying stored data, I apologize. I indented to say > that the human eye, and the brain that goes with it, is an > invaluable > tool in evaluating data. I stand by that statement. > > The most sophisticated tool is only as good as the developer(s) who > made it. Of course and thats why i said I trusted a *tested* tool. You have to be sure the tool is functioning correctly before you can use it confidently. > Since software is ultimately written by humans Not always, but that's a whole other OT debate :-) > You look at the data. I agree, thats part of testing/debugging the tool. Most specifically you find known data, whether that be the data causing the problem or a reference data source with which you can compare. > A case in point. I used to test audio subsystems on PC > motherboards. > ... > I used an audio editing program to display the waveform ie a Tool. > The editing SW was no help there. So I switched tools, > and displayed the capture buffer with simple file dump program. Again a tool. Why because your eyes couldn't parse the audio data. Your eyes could parse the tool output which was intended for human consumption. > The story goes on, but that's enough to illustrate my point. And mine. You needed the right tools to interpret the raw data in the file before your eyes and brain could diagnose the problem. The issue I was raising was that textual data on disk is notoriously difficult to accurately interpret. Once it has passsed through a tool that presents it in an unambiguous format the human eye is entirely appropriate. > the audio driver, nor the test SW, nor the editing tool could > show the real problem. All of them were 'tested tools', The need for the *right* tool does not obviate the need for a tool designed to interpret the raw data. Arguably the editing SW did highlight the real problem - the corruption at the start of the file. Its representation was good enough to poiunt you at the hex editor. > data they were not designed to handle, they produced incorrect > or incomplete results. Just like the human eye when reading raw data out of a text file! > I could cite other examples from other disciplines, > but this one suffices: no SW tool should be relied upon to be > correct > in all cases. Indeed, diagnosing data problems is always fraught with difficulty. Its one of the hardest problem types to track down. My point was merely that the human eye is not reliable when reading raw text files and other, better tools exist. I did not mean to imply that any magic tool exists that works for any kind of data, but the eye is no better than any other kind of tool in this regard. It is very good when presented with data that is formatted for it but not si good when presented with "nearly right" data. > I trust my eyes to see things tools can't And I trust tools to see what my eyes can't! Neither is infallible and I need both. If I'm looking at a text file I'll fire it up in a text editor first for the obvious checks. But if it looks OK I'll then either load it in a hex editor or some other tool designed to read that data format. > when necessary, but I usually just print out '\t', '[SP]', etc) I'm curious how you do that? Presumably a tool? (Not joking, how do you get that kind of display without a specialist tool?) > and incorrect. The programmer's two most valuable tools are her/his > eyes and brain. They are always useful, sometimes indispensable. I completely agree (see my chapter on denbugging in my paper book for a confirmation of that claim!). I was simply pointing out that belief that text files are somehow easy to analyse with the human eye is a dangerous fallacy, and I've spent enough man-days debugging plain-text to be very, very wary. OTOH I detest the modern tendency to use binary formats where plain text makes more sense such as in configuration files! But thats a very different use than for bulk data. Alan G. From cspears2002 at yahoo.com Sat Jun 17 02:05:07 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 16 Jun 2006 17:05:07 -0700 (PDT) Subject: [Tutor] lambda and creating GUIs In-Reply-To: <001001c6912e$139e6a70$0301a8c0@XPpro> Message-ID: <20060617000507.22905.qmail@web51611.mail.yahoo.com> I understand this: > > def f(w): gtk.main_quit() > button.connect("clicked", f) > > lambda simply saves cluttering up the code with lots > of tiny function > derfinitions which are never referred to apart from > in the binding > operation. > Now my question is what is "w"? What is being passed to the function? From john at fouhy.net Sat Jun 17 04:53:23 2006 From: john at fouhy.net (John Fouhy) Date: Sat, 17 Jun 2006 14:53:23 +1200 Subject: [Tutor] lambda and creating GUIs In-Reply-To: <20060617000507.22905.qmail@web51611.mail.yahoo.com> References: <001001c6912e$139e6a70$0301a8c0@XPpro> <20060617000507.22905.qmail@web51611.mail.yahoo.com> Message-ID: <5e58f2e40606161953i7322c02cx7723b0099879e24a@mail.gmail.com> On 17/06/06, Christopher Spears wrote: > I understand this: > > > > def f(w): gtk.main_quit() > > button.connect("clicked", f) > > > Now my question is what is "w"? What is being passed > to the function? I don't know GTK, but I would guess some kind of event class. Other GUIs I've used (Tkinter, wxPython) pass event objects to callbacks, which contain information like - which mouse button was clicked - the exact mouse coordinates (relative to the corner of the screen or the corner of the widget) - which key was pressed etc. You may know some of the information, some of it may not apply, you may not care about the rest of it, but you usually get it anyway :-) In this case, the program doesn't care about any of the extra information, so it accepts the event, but it does nothing with it. Try this: def show(e): print e print 'Class:', e.__class__ print 'Members:' for attr in dir(e): print '%s: %s' % (attr, getattr(e, attr)) button.connect("clicked", show) -- John. From alan.gauld at freenet.co.uk Sat Jun 17 10:40:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 17 Jun 2006 09:40:42 +0100 Subject: [Tutor] lambda and creating GUIs References: <20060617000507.22905.qmail@web51611.mail.yahoo.com> Message-ID: <000301c691e9$b86879e0$0301a8c0@XPpro> >I understand this: >> >> def f(w): gtk.main_quit() >> button.connect("clicked", f) >> > > Now my question is what is "w"? What is being passed > to the function? That will be defined by GTk. The framework will define what each of its event hamdler callback functions looks like in terms of parameters. I don;t know GTk but going on the basis of other frameworkls I'll guess that its the widget where the event occured - a bit like self in OOP. Thus you can add the same handler function to several widgets and at run time manipulate the specific widget that was clicked or whatever. But thats a guess based on experience - and the fact that the original programmer opted to call it w! HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brian at daviesinc.com Sat Jun 17 22:44:19 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 17 Jun 2006 16:44:19 -0400 Subject: [Tutor] I Give Up. In-Reply-To: <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> Message-ID: <449469A3.5060101@daviesinc.com> I have had it. I give up. Python's documentation sucks beyond belief. all I want to do is parse a *SIMPLE* config file of name = value pairs and have python objects named by the name holding the value signified by value , and I want it to be able to work *WITHOUT* someone having to download and install additional modules, etc, so I looked up ConfigParser OK, cool, at least it appears capable. however: *section of code relevant to issue* from ConfigParser import SafeConfigParser cfg = SafeConfigParser("/etc/local-config/myconfig.cfg") mystuff = cfg.items("Parameters",)#kept giving me an exception that 2 values required print mystuff [brian at NixServer python_snips]$ ./pymon.py Traceback (most recent call last): File "./pymon.py", line 20, in ? main() File "./pymon.py", line 15, in main myname = cfg.items("Parameters",) File "/usr/lib/python2.3/ConfigParser.py", line 532, in items d = self._defaults.copy() OK.. so items doesnt appear to work (the above is my tenth attempt to get it working) So.. "RTSL!" (Read The Source, Luke) - I grokked /usr/lib/python2.3/ConfigParser.py" to have a look see at how it does what it does, and found additional stuff that isnt documented *AT ALL* .. So.. [brian at NixServer python_snips]$ ./pymon.py Traceback (most recent call last): File "./pymon.py", line 20, in ? main() File "./pymon.py", line 15, in main myname = cfg.section() AttributeError: SafeConfigParser instance has no attribute 'section' OK Obviously I have no clue how the heck this is all supposed to work, and I have wasted 3 hours of development time on this thing (it aint the first time I have had issues with Python's Documentation) Whatever. I give up.. I'll just go write it in Perl. Maybe some day when Python actually has well structured documentation with *actual working code examples* I might take another look at trying to learn more of it, but at this point, time is money, and I can develop the same application in Perl (probably would have it *done* by now, it's really simple).. I just needed to vent - I cannot believe how Python ever managed to get *anywhere* with the state of documentation at python.org If you want an example of what I would call quality online documentation - need look no further than php.net (or dev.mysql.com) .. or even cpan.org (or heck, just run perldoc in commandline.. ) I tried pydoc.. it just doesnt cut the mustard.. OK.. /end rant Now can someone explan how exactly (preferrably with an actual real world example) that I can read a configuration file in , say /etc/local-config/myconfig.cfg into my python script running in /usr/bin/localscripts , and able to actually use the names as variables (objects) with the configured values assigned to them? This drove me nuts the past couple hours, and truthfully, as much as I like python (I really LIKE python) .. the documentation sucks *SO* bad, I just cannot justify attempting to learn more and use it for more projects because of situations like this that do nothing but waste my time. From python at venix.com Sat Jun 17 23:56:03 2006 From: python at venix.com (Python) Date: Sat, 17 Jun 2006 17:56:03 -0400 Subject: [Tutor] I Give Up. In-Reply-To: <449469A3.5060101@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> Message-ID: <1150581363.27979.247.camel@www.venix.com> On Sat, 2006-06-17 at 16:44 -0400, Brian Gustin wrote: > I have had it. I give up. > > Python's documentation sucks beyond belief. A lot of it is excellent. The ConfigParser, that you are complaining about is woefully short on examples and does not make clear that you *must read* the other sections. > > all I want to do is parse a *SIMPLE* config file of name = value pairs > and have python objects named by the name holding the value signified by > value , and I want it to be able to work *WITHOUT* someone having to > download and install additional modules, etc, so I looked up ConfigParser > > OK, cool, at least it appears capable. however: > *section of code relevant to issue* > > from ConfigParser import SafeConfigParser > cfg = SafeConfigParser("/etc/local-config/myconfig.cfg") The initialization is your default values! cfg = SafeConfigParser() cfg.read("/etc/local-config/myconfig.cfg") > mystuff = cfg.items("Parameters",)#kept giving me an exception that 2 > values required > print mystuff >>> help(cfg.items) Help on method items in module ConfigParser: items(self, section, raw=False, vars=None) method of ConfigParser.SafeConfigParser instance Return a list of tuples with (name, value) for each option in the section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. > > > [brian at NixServer python_snips]$ ./pymon.py > Traceback (most recent call last): > File "./pymon.py", line 20, in ? > main() > File "./pymon.py", line 15, in main > myname = cfg.items("Parameters",) > File "/usr/lib/python2.3/ConfigParser.py", line 532, in items > d = self._defaults.copy() > OK.. so items doesnt appear to work (the above is my tenth attempt to > get it working) So.. "RTSL!" (Read The Source, Luke) - I grokked > /usr/lib/python2.3/ConfigParser.py" to have a look see at how it does > what it does, and found additional stuff that isnt documented *AT ALL* > .. So.. > > > [brian at NixServer python_snips]$ ./pymon.py > Traceback (most recent call last): > File "./pymon.py", line 20, in ? > main() > File "./pymon.py", line 15, in main > myname = cfg.section() > AttributeError: SafeConfigParser instance has no attribute 'section' > myname = cfg.sections() ^ Will work for you and provide a list of sections. You will need those sections to feed into the items call. > OK Obviously I have no clue how the heck this is all supposed to work, > and I have wasted 3 hours of development time on this thing (it aint the > first time I have had issues with Python's Documentation) > > Whatever. I give up.. No don't! You are almost there. > > I'll just go write it in Perl. Maybe some day when Python actually has > well structured documentation with *actual working code examples* I > might take another look at trying to learn more of it, but at this > point, time is money, and I can develop the same application in Perl > (probably would have it *done* by now, it's really simple).. I came to Python after Perl and lot's of other languages. I think Python is better, but it helps to have someone to talk to when things are going badly. > > I just needed to vent - I cannot believe how Python ever managed to get > *anywhere* with the state of documentation at python.org > I liked the old layout better, but presumably you found this: http://docs.python.org/lib/RawConfigParser-objects.html > If you want an example of what I would call quality online documentation > - need look no further than php.net (or dev.mysql.com) .. or even > cpan.org (or heck, just run perldoc in commandline.. ) I tried pydoc.. > it just doesnt cut the mustard.. > > OK.. > /end rant > > Now can someone explan how exactly (preferrably with an actual real > world example) that I can read a configuration file in , say > /etc/local-config/myconfig.cfg into my python script running in > /usr/bin/localscripts , and able to actually use the names as variables > (objects) with the configured values assigned to them? > > This drove me nuts the past couple hours, and truthfully, as much as I > like python (I really LIKE python) .. the documentation sucks *SO* bad, > I just cannot justify attempting to learn more and use it for more > projects because of situations like this that do nothing but waste my time. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From python at venix.com Sun Jun 18 00:30:16 2006 From: python at venix.com (Python) Date: Sat, 17 Jun 2006 18:30:16 -0400 Subject: [Tutor] I Give Up. In-Reply-To: <449469A3.5060101@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> Message-ID: <1150583416.27979.263.camel@www.venix.com> On Sat, 2006-06-17 at 16:44 -0400, Brian Gustin wrote: > Now can someone explan how exactly (preferrably with an actual real > world example) that I can read a configuration file in , say > /etc/local-config/myconfig.cfg into my python script running in > /usr/bin/localscripts , and able to actually use the names as > variables > (objects) with the configured values assigned to them? This was done from the Python prompt. Sorry for the crummy names. If you saw all the typos that have been removed, you'd understand why I kept the names short. >>> print open('sample.config').read() [sect_1] a = 1 b = 2 >>> cfg = cp.SafeConfigParser() >>> cfg.read('sample.config') >>> cfg.sections() ['sect_1'] >>> for s in cfg.sections(): ... print cfg.items(s) ... [('a', '1'), ('b', '2')] >>> class A: ... pass ... >>> a = A() >>> for s in cfg.sections(): ... setattr(a,s,A()) ... as = getattr(a,s) ... for k,v in cfg.items(s): ... setattr(as,k,v) ... >>> a <__main__.A instance at 0xb7f0256c> >>> a.sect_1 <__main__.A instance at 0xb7eda3ac> >>> a.sect_1.a '1' >>> a.sect_1.b '2' >>> Hope this helps. Note that you can build a section dictionary by: sect_dict = dict(cfg.items('section-name')) You can create a class to turn dict references (d.get('key')) into object references (o.key) with this trick: >>> class Better(object): ... def __init__(self, **kwds): ... self.__dict__.update(kwds) sect_obj = Better( **sect_dict) -- Lloyd Kvam Venix Corp From brian at daviesinc.com Sun Jun 18 01:37:40 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 17 Jun 2006 19:37:40 -0400 Subject: [Tutor] I Give Up. In-Reply-To: <1150581363.27979.247.camel@www.venix.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> <1150581363.27979.247.camel@www.venix.com> Message-ID: <44949244.7060602@daviesinc.com> Thanks- I had to sit back and with the perl script running nicely, I took another shot at this to see if I could get it right.. so far so good, at least no more exceptions being raised.. The perl script runs on a cron, I am thinking I will write this in python and then wrap it up into a main function, and run it as a daemon, eliminating the cron.. So, I guess I'll keep trying, now that the project is done, and the script working, and client happy , and me paid, I have a little free time to mess around with this.. I am thinking very seriously about building a new set of python documentation with capability for user contributions and notes, etc, and putting it online (with searchability to boot) .. maybe a project for another day.. The one amazing thing I found ridiculously funny: Python "official" forums- and they actually run phpBB forums? You mean to tell me no one has written a solid, stable forum software in Python? OK.. maybe another project to tackle.. I guess I just need to start building the python documentation the way I think it outta be done... and see how it goes over.. >>>>help(cfg.items) > > > Help on method items in module ConfigParser: > > items(self, section, raw=False, vars=None) method of > ConfigParser.SafeConfigParser instance > Return a list of tuples with (name, value) for each option > in the section. > > All % interpolations are expanded in the return values, based on the > defaults passed into the constructor, unless the optional argument > `raw' is true. Additional substitutions may be provided using the > `vars' argument, which must be a dictionary whose contents overrides > any pre-existing defaults. > > The section DEFAULT is special. > This is still not 100% clear, and I had to experiement a little bit to get it to work, but finally got it working. It does *NOT* say that you must send arguments of the function as strings, (or as object variables defined elsewhere) , and for the life of me, I have not been able to get interpolation to work, despite the examples I have seen.. it is quite unclear. It would seem all of this python documentation is written assuming that the reader thinks exactly the same way as the author, and is already familiar with the function and objects and documentation is written as if it's just a "reminder of how stuff works"... Example: I had no idea as to how to do this, and if I had not already done similar parsing of config files (.ini for example) in other languages (perl and php both) I would not even have been able to find this module class on google search , unless I was really lucky .. It seems sad that the only way I can look up "what kind of function or module might there be to do x task in Python" has to be found via a google search.. In the PHP documentation, I can just search out a "similar" function (say, I want to know how to take two arrays and combine them, rejecting non-uniques.. I might go to php.net and search the function list for array() and then I have a list of *all* array functions that may be used, and able to pick out, for example, array_merge() .. With python, I dont see any way of doing that, so lots of really cool stuff that can be done in python is not found.. > > myname = cfg.sections() > ^ > Will work for you and provide a list of sections. You will need those > sections to feed into the items call. > Yeah - serves me right for not paying attention to spelling.. :) > > > No don't! > > You are almost there. > Close.. we'll see how it goes from here, now that Im not under pressure to get this script done :) > I came to Python after Perl and lot's of other languages. I think > Python is better, but it helps to have someone to talk to when things > are going badly. > Very true.. and sometimes talking about teh issue the solution suddenly becomes evident :) > > I liked the old layout better, but presumably you found this: > http://docs.python.org/lib/RawConfigParser-objects.html > Actually, no I didnt find that.. another area where Documentation sucks- It's so very easy to miss some important thing in the way this stuff is categorized and structured.. In fact, I actually searched for python.org Documentation ConfigParser.read and still didnt see anything come up for python.org documentation.... Oh well. I'll see if I can get this thing to work like the perl script I just wrote... From kent37 at tds.net Sun Jun 18 03:17:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jun 2006 21:17:26 -0400 Subject: [Tutor] I Give Up. In-Reply-To: <44949244.7060602@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> <1150581363.27979.247.camel@www.venix.com> <44949244.7060602@daviesinc.com> Message-ID: <4494A9A6.3060006@tds.net> Brian Gustin wrote: > I am thinking very seriously about building a new set of python > documentation with capability for user contributions and notes, etc, and > putting it online (with searchability to boot) .. maybe a project for > another day.. Maybe something like this: http://pyref.infogami.com/ Kent From ismaelgf at adinet.com.uy Sun Jun 18 05:39:50 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 18 Jun 2006 00:39:50 -0300 Subject: [Tutor] I Give Up. In-Reply-To: <449469A3.5060101@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> Message-ID: <4494CB06.3070705@adinet.com.uy> Brian Gustin wrote: > I'll just go write it in Perl. Maybe some day when Python actually has > well structured documentation with *actual working code examples* > Indeed. I have always thought that the docs lacked working examples. I usually do a google search, hoping to find some script showing off how to use whatever I'm searching for. I think there was an annotated docs proyect, but I can't find it. Does anybody know where it was? I'm willing to go and add examples :) (at least, for the things I know) Ismael From ismaelgf at adinet.com.uy Sun Jun 18 07:27:01 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 18 Jun 2006 02:27:01 -0300 Subject: [Tutor] Performance of classes Message-ID: <4494E425.1040605@adinet.com.uy> Hello I'm writing a program to find an appropiate combination of resistances to obtain a desired value of resistance. The program takes into account how many resistances you have available and their resistance in ohms. A short review of physics: resistors can be arranged in series or in parallel. To obtain the equivalent resistance (that is, you could replace those resistors with only one that had this resistance): if in series: sum ohms; if in parallel 1/Req = 1/R1 + 1/R2. Since this problem (as far as I can tell) requires to generate all possible combinations (eliminating those that are impossible -ie: requires 3 resistances of type A and you only have 2-), I'm trying to make it run as fast as possible. So far I discovered that: - Calling functions that return a value (ie: just "return self.something") is slower than just grabbing the value from the class - If you've got recursions, and you call them multiple times, you better remember what they returned last time, otherwise it can consume a lot of time (or to put it another way: don't go down the same road twice :) - Psyco is nice :) - The Python Profiler is really useful in these cases :) Now, I was reading about decorators and noticed that some classes can inherit from object. I thought it should make no difference in speed, but, just because, I tried changing my class to inherit from object. Big surprise, it *does* change things. I was wondering if somebody could explain why it does? I find it quite weird! Profiling normal: 4772989 function calls (3817173 primitive calls) in 54.433 CPU seconds Profiling all clases inherit from object: 4772989 function calls (3817173 primitive calls) in 51.151 CPU seconds But what's really really strange is that if one class inherits from object but the other does not, the amount of calls varies! Both "normal" classes: 1051803 4.609 0.000 4.609 0.000 resistPsyco.py:65(__cmp__) 78803 0.372 0.000 0.372 0.000 resistPsyco.py:85(__cmp__) Resistencia inherits from object: 86306 0.402 0.000 0.402 0.000 resistPsyco.py:65(__cmp__) 1044300 4.879 0.000 4.879 0.000 resistPsyco.py:85(__cmp__) Why does this happen? I have attached the code, I hope that's fine. If you have any further optimization suggestions I would be very glad to hear them :) About the code: - generarPos generates all possible resistances - generarResist generates all possible from the initial resistances - unico makes sure that there are no duplicates (equal resistance) - This method was posted on the ASPN Cookbook - ResistenciaB is the basic resistance, the ones you have available. - Resistencia is composed of two resistances - checkPosible checks that you can actually build this resistor - getBasicasIni tells you how many resistors of x type you have used. - resorig are the resistors you begin with - rescant is the amount of each basic resistors you have - Don't put many different resistors or a big amount of resistors, otherwise the program may take veeeryyy long to run. Please forgive any broken English. It's been too long since I last wrote in it. Thanks for your time! Ismael -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: resistPsyco.py Url: http://mail.python.org/pipermail/tutor/attachments/20060618/84c6ab5d/attachment-0001.pot From learner404 at gmail.com Sun Jun 18 10:46:11 2006 From: learner404 at gmail.com (learner404) Date: Sun, 18 Jun 2006 10:46:11 +0200 Subject: [Tutor] I Give Up. In-Reply-To: <44949244.7060602@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> <1150581363.27979.247.camel@www.venix.com> <44949244.7060602@daviesinc.com> Message-ID: <13a83ca10606180146p1e01c281hb9f293d9d1030d76@mail.gmail.com> On 18/06/06, Brian Gustin wrote: > > > > The one amazing thing I found ridiculously funny: > > Python "official" forums- and they actually run phpBB forums? You mean > to tell me no one has written a solid, stable forum software in Python? > > OK.. maybe another project to tackle.. I guess I just need to start > building the python documentation the way I think it outta be done... > and see how it goes over.. I also was very surprised with that and I'd really love to see a "pynBB" :) The only things I saw for "forums" in Python are: pyBB but it seems dead and my south-korean sucks : http://bbs.pythonworld.net:9080/pybbs.py Zyons which look promising on a Django base but which still is in an alpha state: http://zyons.com/forum/ Concerning basic Perl/Python I also found that (but not complete) : http://pleac.sourceforge.net/pleac_python/index.html "In this document, you'll find an implementation of the Solutions of the Perl Cookbook in the Python language." Ooops and I also found that on perl ;) http://mirror5.escomposlinux.org/comic/ecol-13-e.png learner404 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060618/d701fb5e/attachment.html From btatum at cddn.com Sun Jun 18 12:58:38 2006 From: btatum at cddn.com (Bill Tatum) Date: Sun, 18 Jun 2006 05:58:38 -0500 Subject: [Tutor] Beginner question(s) Message-ID: <20060618105838.0DB326318@mem01.ecsis.net> Hi, I'm working through Python Programming for the Absolute Beginner. One of the challenges at the end of chapter 4 is to get a message from the user and then print it out backwards. I have. message = raw_input("Enter your message:") count = len(message) print count which gives me the number of characters in the message. I tried to use a for loop: for i in range(len(message)-1,-1, -1): print i, but I just get the numeric values of the string. Can anyone help? Also, does anyone know of a PDA that would run python? TIA -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6898d895/attachment.html From ground.contro at pobox.com Sun Jun 18 14:33:38 2006 From: ground.contro at pobox.com (gc) Date: Sun, 18 Jun 2006 22:33:38 +1000 Subject: [Tutor] socket.recvfrom() not getting data Message-ID: <44954822.8020407@pobox.com> I've hit the wall trying to receive some data from a socket and hope potential cross posting won't upset too many of you. In summary, I'm playing with a DHCP client written in python just to get a feel for it before getting down to serious work (see the PS for more info) This segment of code sends a packet, using tcpdump i can see a response coming from server running on another PC but i never see any data back from socket.recvfrom() - it just blocks: sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) sock.bind( (socket.gethostname(), CLI_PORT) ) sock.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1) cSent = sock.sendto( data, 0, ( '', SRV_PORT ) ) print 'sent: ', cSent, ', from', sock.getsockname() print 'status:', sock.getsockopt( socket.SOL_SOCKET, socket.SO_ERROR ) (rcvd, add) = sock.recvfrom( 512 ) print 'Got', len( rcvd ), 'bytes back' netstat tells me that the socket is still there - as long as the script is running. BTW the script runs with root privileges - the ports used are 67 and 68. The server response that i see with tcpdump looks healthy. My suspicion is that the protocol stack never passes the packet up to the socket but don't know why (the normal DHCP client daemon isn't running on this machine). Is there a way to turn on some debugging with sockets? Calling sock.setsockopt( socket.SOL_SOCKET, socket.SO_DEBUG, 1) didn't do much for me. Any pointers appreciated. TIA PS For the curious, the DHCP client is really meant to be implemented in C/C++ on a networked embedded device (needless to say, running a proprietary OS); there'll be lots of them and configuring IP address, netmask, gateway etc manually is a pain. So the python code is just a proof of concept. From kent37 at tds.net Sun Jun 18 15:06:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jun 2006 09:06:37 -0400 Subject: [Tutor] Performance of classes In-Reply-To: <4494E425.1040605@adinet.com.uy> References: <4494E425.1040605@adinet.com.uy> Message-ID: <44954FDD.8050608@tds.net> Ismael Garrido wrote: > Hello > > I'm writing a program to find an appropiate combination of resistances > to obtain a desired value of resistance. The program takes into account > how many resistances you have available and their resistance in ohms. > > Since this problem (as far as I can tell) requires to generate all > possible combinations (eliminating those that are impossible -ie: > requires 3 resistances of type A and you only have 2-), I'm trying to > make it run as fast as possible. So far I discovered that: > - Calling functions that return a value (ie: just "return > self.something") is slower than just grabbing the value from the class Yes, there is a cost to calling a function. > - If you've got recursions, and you call them multiple times, you better > remember what they returned last time, otherwise it can consume a lot of > time (or to put it another way: don't go down the same road twice :) This is the basic idea behind dynamic programming algorithms. > - Psyco is nice :) > - The Python Profiler is really useful in these cases :) > > Now, I was reading about decorators and noticed that some classes can > inherit from object. I thought it should make no difference in speed, > but, just because, I tried changing my class to inherit from object. Big > surprise, it *does* change things. I was wondering if somebody could > explain why it does? I find it quite weird! Inheriting from object makes your class a "new-style class" which changes some of the details of how the class works, so it's not really surprising that there is a performance difference. > I have attached the code, I hope that's fine. If you have any further > optimization suggestions I would be very glad to hear them :) generarResist() is doing a lot more work than necessary. Because i and j both iterate the entire list, you will generate all pairs twice. Since Resistencia(i,j) is equivalent to Resistencia(j,i) you would be better off having j just go through the part of the list starting from i. You can do this by iterating over indices instead of values. Second, Resistencia(i,j).posible is going to be the same as Resistencia(i,j, False).posible because they use the same resistors. So there is no need to try Resistencia(i,j, False) if Resistencia(i,j).posible is False. def generarResist(listaRes): resultado = [] for i in listaRes: for j in listaRes: r = Resistencia(i,j) if r.posible: resultado.append(r) r = Resistencia(i,j, False) if r.posible: resultado.append(r) return unico(resultado) Kent From michael at espersunited.com Sun Jun 18 15:18:13 2006 From: michael at espersunited.com (Michael Sullivan) Date: Sun, 18 Jun 2006 08:18:13 -0500 Subject: [Tutor] Beginner question(s) In-Reply-To: <20060618105838.0DB326318@mem01.ecsis.net> References: <20060618105838.0DB326318@mem01.ecsis.net> Message-ID: <1150636693.12107.12.camel@camille.espersunited.com> On Sun, 2006-06-18 at 05:58 -0500, Bill Tatum wrote: > Hi, > > > > I?m working through Python Programming for the Absolute Beginner. One > of the challenges at the end of chapter 4 is to get a message from the > user and then print it out backwards. I have? > > > > message = raw_input("Enter your message:") > > count = len(message) > > print count > > > > which gives me the number of characters in the message. I tried to > use a for loop: > > > > for i in range(len(message)-1,-1, -1): > > print i, > > > > but I just get the numeric values of the string. Can anyone help? > I'm a python beginner myself, but shouldn't that last "print i" be "print message[i]? As it stands, you're only printing the numeric value 'i'. -Michael Sullivan- From ismaelgf at adinet.com.uy Sun Jun 18 17:02:48 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 18 Jun 2006 12:02:48 -0300 Subject: [Tutor] Performance of classes In-Reply-To: <44954FDD.8050608@tds.net> References: <4494E425.1040605@adinet.com.uy> <44954FDD.8050608@tds.net> Message-ID: <44956B18.8030103@adinet.com.uy> Kent Johnson wrote: > Ismael Garrido wrote: > >> I have attached the code, I hope that's fine. If you have any further >> optimization suggestions I would be very glad to hear them :) >> > > generarResist() is doing a lot more work than necessary. Because i and j > both iterate the entire list, you will generate all pairs twice. Since > Resistencia(i,j) is equivalent to Resistencia(j,i) you would be better > off having j just go through the part of the list starting from i. You > can do this by iterating over indices instead of values. > > Second, Resistencia(i,j).posible is going to be the same as > Resistencia(i,j, False).posible because they use the same resistors. So > there is no need to try Resistencia(i,j, False) if > Resistencia(i,j).posible is False. > Thanks for your reply! You're *very* right about that! :D Do you have any idea about the difference in calls to the compares? Should I always inherit from object in my classes? Thanks Ismael From kieran.flanagan at gmail.com Sun Jun 18 21:11:35 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Sun, 18 Jun 2006 20:11:35 +0100 Subject: [Tutor] Writing to a remote file In-Reply-To: <1150475085.27979.136.camel@www.venix.com> References: <1150475085.27979.136.camel@www.venix.com> Message-ID: Hi Thanks for the help. I took a quick scan through the logging module and I can't see any mention of writing to a remote file ? Could you please direct me to the part you mentioned ?. I went through some of the examples and the one related to remote logging is via the console (tcp port). I cannot see any information given regarding remote logging. Just to give some more info on what I am doing. I have a large script that is running and outputting messages to a logfile I am storing. I want these messages to be output to a remote file instead which can be viewed on a browser to provide realtime data as the script processes. So this logfile is not handled by syslog. This is being done on a Linux machine. Thanks for the help Kieran On 6/16/06, Lloyd Kvam wrote: > > On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote: > > Hi > > > > I want to run a script on one machine and log output messages to a > > remote file located on another machine. Is there any easy method of > > doing this ?. > > http://docs.python.org/lib/module-logging.html > > If the remote machine is a file server, you can use the logging module > to write to a file on the remote machine > > Also the logging module can be used to easily log to a syslog handler. > If this remote file is a "normal" log file managed by a syslog process > then you should find the python part pretty easy. The syslog process > still needs to be configured to accept your logging messages, but that > should not be too difficult. > > Scanning the logging module docs, it looks like you can use it to write > your own process to run on the remote machine to handle "logging > messages". Then use the logging module on the local machine to send > "logging messages" to the remote machine. > > > > Thanks > > Kieran > > > > -- > > "Behind every great man, there is a great woman. Behind that woman is > > Mr.T." > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 320-210-3409 > > -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6cb8343c/attachment.htm From dkuhlman at rexx.com Sun Jun 18 21:46:36 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 18 Jun 2006 12:46:36 -0700 Subject: [Tutor] I Give Up. In-Reply-To: <44949244.7060602@daviesinc.com> References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> <1150581363.27979.247.camel@www.venix.com> <44949244.7060602@daviesinc.com> Message-ID: <20060618194636.GA22079@cutter.rexx.com> On Sat, Jun 17, 2006 at 07:37:40PM -0400, Brian Gustin wrote: [snip] > > OK.. maybe another project to tackle.. I guess I just need to start > building the python documentation the way I think it outta be done... > and see how it goes over.. At the top of the table of contents of the library reference, it says: Python Library Reference Guido van Rossum Python Software Foundation Email: docs at python.org Fred L. Drake, Jr., editor So, another thing you could do is to send an email to Fred Drake at docs at python.org in which you provide an example with a bit of commentary and ask him to include it in the ConfigParser section. Another suggestion: Go to the Python Wiki at http://wiki.python.org/moin/, then search for ConfigParser. There are already several related pages there, but I could not find a page that gives examples. So, you could add a ConfigParserExamples page that has one or more of the examples provided in this thread, or some of your own code, with a bit of explanation, and then link to it from the main ConfigParser page. In defense of the standard docs -- Since, the standard Python documentation (language reference, library reference, etc) are reference docs, they do not replace tutorial books like "Learning Python" or "Learn to Program Using Python" (by Alan Gauld, who also posts on this list). Still I've found so much of what I need in those documents, that I have a hard time complaining. And, my thanks to Fred Drake. Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From jj_frap at hotmail.com Sun Jun 18 22:57:32 2006 From: jj_frap at hotmail.com (Josh F) Date: Sun, 18 Jun 2006 20:57:32 +0000 Subject: [Tutor] Beginner Question In-Reply-To: Message-ID: re. Beginner Question I'm still in the fairly early stages of learning Python, but I have an intermediate level of HTML, CSS, and VB6 knowledge along with the fundamentals of C and C++ and a very little bit of PERL.. But enough about me...Here's the solution. message = raw_input("Enter your message:") print message[-1::-1] Slicing a string takes three arguments, all of which are optional: The first character to be sliced, the last character to be sliced, and tio slice every nth character. In Python strings, -1 refers to the last character in the string and thus becomes the first argument. You don't specify the second argument because you're printing the string from end to beginning. Finallly, the -1 in the 3rd argument indicates that you want the string to be printed in reverse order (i.e. iterate backwards by one character). >Message: 1 >Date: Sun, 18 Jun 2006 05:58:38 -0500 >From: "Bill Tatum" >Subject: [Tutor] Beginner question(s) >To: >Message-ID: <20060618105838.0DB326318 at mem01.ecsis.net> >Content-Type: text/plain; charset="us-ascii" > >Hi, > > > >I'm working through Python Programming for the Absolute Beginner. One of >the challenges at the end of chapter 4 is to get a message from the user >and >then print it out backwards. I have. > > > >message = raw_input("Enter your message:") > >count = len(message) > >print count > > > >which gives me the number of characters in the message. I tried to use a >for loop: > > > >for i in range(len(message)-1,-1, -1): > > print i, > > > >but I just get the numeric values of the string. Can anyone help? > > > >Also, does anyone know of a PDA that would run python? > > > >TIA From alan.gauld at freenet.co.uk Mon Jun 19 00:15:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 18 Jun 2006 23:15:35 +0100 Subject: [Tutor] I Give Up. References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com> <20060618194636.GA22079@cutter.rexx.com> Message-ID: <001c01c69324$b90a6610$0301a8c0@XPpro> > reference docs, they do not replace tutorial books like "Learning > Python" or "Learn to Program Using Python" (by Alan Gauld, who Thanks for the plug, but I'd be first to admit my tutor is way too basic to go near the ConfigParser modules etc. I had actually hoped that Mertz' "Text Processing in Python" would cover that kind of stuff but instead it goes off into the 3rd party mx modules after giving only the briefest of examples of using ConfigParser... > thanks to Fred Drake. In the few emails I've exchanged with Fred, mainly about links to my tutors and the various translations, he has been most helpful. I'll add my thanks to the list. :-) Alan G From alan.gauld at freenet.co.uk Mon Jun 19 00:18:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 18 Jun 2006 23:18:29 +0100 Subject: [Tutor] Beginner question(s) References: <20060618105838.0DB326318@mem01.ecsis.net> Message-ID: <002801c69325$20e48cc0$0301a8c0@XPpro> > message = raw_input("Enter your message:") > for i in range(len(message)-1,-1, -1): > print i, > > but I just get the numeric values of the string. Can anyone help? As an alternative approach consider converting to a list and using the reverse method... > Also, does anyone know of a PDA that would run python? There was a project called pippy, but I haven't heard anything of it recently so I don't know if its still around or if it runs on modern PDAs - I think it was PalmOS anyhow... There was rumours of a Pocket Windows version too but I've never really been interested in that one... Alan G. From ismaelgf at adinet.com.uy Mon Jun 19 00:34:10 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun, 18 Jun 2006 19:34:10 -0300 Subject: [Tutor] Beginner question(s) In-Reply-To: <002801c69325$20e48cc0$0301a8c0@XPpro> References: <20060618105838.0DB326318@mem01.ecsis.net> <002801c69325$20e48cc0$0301a8c0@XPpro> Message-ID: <4495D4E2.6060303@adinet.com.uy> Alan Gauld wrote: >> Also, does anyone know of a PDA that would run python? >> > > There was a project called pippy, but I haven't heard anything of it > recently so I don't know if its still around or if it runs on modern > PDAs - I think it was PalmOS anyhow... > > Pippy is quite dead. No development done recently. It supposedly runs fine, but runs only Python 1.5. If you want it, it's at: http://sourceforge.net/projects/pippy Ismael From simplebob at gmail.com Mon Jun 19 00:39:03 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Sun, 18 Jun 2006 18:39:03 -0400 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: <6d87ecf40606181539r30ee95dcl4ce3d1b13635cfba@mail.gmail.com> On 6/18/06, Josh F wrote: > > re. Beginner Question > > I'm still in the fairly early stages of learning Python, but I have an > intermediate level of HTML, CSS, and VB6 knowledge along with the > fundamentals of C and C++ and a very little bit of PERL.. > > But enough about me...Here's the solution. > > message = raw_input("Enter your message:") > print message[-1::-1] just another noob here. but wouldn't his way work like this: >>>message = "foobar" >>>for i in range(len(message)-1,-1,-1): ... print message[i], ... r a b o o f i guess there's lots of ways to do it. that's my 2 cents. Slicing a string takes three arguments, all of which are optional: The first > character to be sliced, the last character to be sliced, and tio slice > every > nth character. > > In Python strings, -1 refers to the last character in the string and thus > becomes the first argument. > > You don't specify the second argument because you're printing the string > from end to beginning. > > Finallly, the -1 in the 3rd argument indicates that you want the string to > be printed in reverse order (i.e. iterate backwards by one character). > > > > > > > > >Message: 1 > >Date: Sun, 18 Jun 2006 05:58:38 -0500 > >From: "Bill Tatum" > >Subject: [Tutor] Beginner question(s) > >To: > >Message-ID: <20060618105838.0DB326318 at mem01.ecsis.net> > >Content-Type: text/plain; charset="us-ascii" > > > >Hi, > > > > > > > >I'm working through Python Programming for the Absolute Beginner. One of > >the challenges at the end of chapter 4 is to get a message from the user > >and > >then print it out backwards. I have. > > > > > > > >message = raw_input("Enter your message:") > > > >count = len(message) > > > >print count > > > > > > > >which gives me the number of characters in the message. I tried to use a > >for loop: > > > > > > > >for i in range(len(message)-1,-1, -1): > > > > print i, > > > > > > > >but I just get the numeric values of the string. Can anyone help? > > > > > > > >Also, does anyone know of a PDA that would run python? > > > > > > > >TIA > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay simplebob at gmail.com boxster.homelinux.org H: 814.825.0847 M: 814-341-6233 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6d6486a1/attachment.htm From john at fouhy.net Mon Jun 19 01:02:41 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 19 Jun 2006 11:02:41 +1200 Subject: [Tutor] Beginner question(s) In-Reply-To: <20060618105838.0DB326318@mem01.ecsis.net> References: <20060618105838.0DB326318@mem01.ecsis.net> Message-ID: <5e58f2e40606181602g69a4d714ub59d5ac20de031b6@mail.gmail.com> > Also, does anyone know of a PDA that would run python? Some of the new Nokias run python: http://www.forum.nokia.com/python -- John. From python at venix.com Mon Jun 19 14:40:19 2006 From: python at venix.com (Python) Date: Mon, 19 Jun 2006 08:40:19 -0400 Subject: [Tutor] Writing to a remote file In-Reply-To: References: <1150475085.27979.136.camel@www.venix.com> Message-ID: <1150720819.27979.299.camel@www.venix.com> On Sun, 2006-06-18 at 20:11 +0100, kieran flanagan wrote: > Hi > > Thanks for the help. I took a quick scan through the logging module > and I can't see any mention of writing to a remote file ? Could you > please direct me to the part you mentioned ?. I had 3 suggestions: use the remote computer as a file server, use the remote server as a syslog server, write your own logging server on the remote computer. 1. If the remote system is a file server, the logging module does not know it is writing to a remote computer. The remote computer is simply mounted into your local file system. You'd use linux commands something like: mkdir logfiles mount -t smbfs //remote/logs ./logfiles That assumes the remote computer is running samba. The Python code would be something like: import logging, logging.handlers logger = logging.getLogger('') logger.addHandler(logging.handlers.FileHandler('logfiles/myapp.log')) (all this is untested, but, hopefully, close to being correct) 2. You eliminate the remote syslog option below. 3. Write your own logging server to run on the remote computer. Have your local program use the remote logging server. The example code is here: http://docs.python.org/lib/network-logging.html > I went through some of the examples and the one related to remote > logging is via the console (tcp port). I cannot see any information > given regarding remote logging. > Just to give some more info on what I am doing. I have a large script > that is running and outputting messages to a logfile I am storing. I > want these messages to be output to a remote file instead which can be > viewed on a browser to provide realtime data as the script processes. > So this logfile is not handled by syslog. > > This is being done on a Linux machine. > > Thanks for the help > Kieran > > > > > On 6/16/06, Lloyd Kvam wrote: > On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote: > > Hi > > > > I want to run a script on one machine and log output > messages to a > > remote file located on another machine. Is there any easy > method of > > doing this ?. > > http://docs.python.org/lib/module-logging.html > > If the remote machine is a file server, you can use the > logging module > to write to a file on the remote machine > > Also the logging module can be used to easily log to a syslog > handler. > If this remote file is a "normal" log file managed by a syslog > process > then you should find the python part pretty easy. The syslog > process > still needs to be configured to accept your logging messages, > but that > should not be too difficult. > > Scanning the logging module docs, it looks like you can use it > to write > your own process to run on the remote machine to handle > "logging > messages". Then use the logging module on the local machine > to send > "logging messages" to the remote machine. > > > > Thanks > > Kieran > > > > -- > > "Behind every great man, there is a great woman. Behind that > woman is > > Mr.T." > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 320-210-3409 > > > > > -- > "Behind every great man, there is a great woman. Behind that woman is > Mr.T." -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 -- Lloyd Kvam Venix Corp From frank.hoffsummer at gmail.com Mon Jun 19 15:38:43 2006 From: frank.hoffsummer at gmail.com (frank h.) Date: Mon, 19 Jun 2006 15:38:43 +0200 Subject: [Tutor] local day names in ascii Message-ID: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> Hello List, i am trying to convert local Swedish daynames to ASCII "M?ndag" should become "Mandag" "L?rdag" should become "Lordag" "S?ndag" should become "Sondag" here is my session import locale locale.setlocale(locale.LC_ALL, 'sv_Se') datetime.date(2006, 06, 19).strftime("%A") 'M\xc3\xa5ndag' datetime.date(2006, 06, 19).strftime("%A").decode('utf8').encode('ascii','ignore') 'Mndag' Somehow, the Swedish character "?" gets dropped in the conversion to ascii. how can I accomplish the conversion '?' --> 'a' etc.? should I use a dictionary? thanks for any insight -frank -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060619/6a38f2b2/attachment.html From andre.roberge at gmail.com Mon Jun 19 15:50:17 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 19 Jun 2006 10:50:17 -0300 Subject: [Tutor] local day names in ascii In-Reply-To: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> Message-ID: <7528bcdd0606190650y7f4a0d01n9592c905f029553a@mail.gmail.com> May I suggest you look at this http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871 including the comments. (The last comment in particular looks intriguing...) Andr? On 6/19/06, frank h. wrote: > Hello List, > i am trying to convert local Swedish daynames to ASCII > > "M?ndag" should become "Mandag" > "L?rdag" should become "Lordag" > "S?ndag" should become "Sondag" > > here is my session > > import locale > locale.setlocale(locale.LC_ALL, 'sv_Se') > datetime.date(2006, 06, 19).strftime("%A") > 'M\xc3\xa5ndag' > datetime.date(2006, 06, > 19).strftime("%A").decode('utf8').encode('ascii','ignore') > 'Mndag' > > Somehow, the Swedish character "?" gets dropped in the conversion to ascii. > how can I accomplish the conversion '?' --> 'a' etc.? should I use a > dictionary? > thanks for any insight > -frank > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From andre.roberge at gmail.com Mon Jun 19 16:55:49 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 19 Jun 2006 11:55:49 -0300 Subject: [Tutor] Fwd: local day names in ascii In-Reply-To: <60fae7c30606190706k24d6cdebq711b9b1340130f7a@mail.gmail.com> References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> <7528bcdd0606190650y7f4a0d01n9592c905f029553a@mail.gmail.com> <60fae7c30606190706k24d6cdebq711b9b1340130f7a@mail.gmail.com> Message-ID: <7528bcdd0606190755x4c949cc6x65096e50c04ff5e9@mail.gmail.com> Message forwarded to the list for information. Andr? ---------- Forwarded message ---------- From: frank h. Date: Jun 19, 2006 11:06 AM Subject: Re: [Tutor] local day names in ascii To: Andre Roberge Andr?, thank you so much for this spot-on pointer. the last comment indeed nails it. excellent!! -frank On 6/19/06, Andre Roberge < andre.roberge at gmail.com> wrote: > May I suggest you look at this > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871 > including the comments. (The last comment in particular looks intriguing...) > > Andr? > > On 6/19/06, frank h. < frank.hoffsummer at gmail.com> wrote: > > Hello List, > > i am trying to convert local Swedish daynames to ASCII > > > > "M?ndag" should become "Mandag" > > "L?rdag" should become "Lordag" > > "S?ndag" should become "Sondag" > > > > here is my session > > > > import locale > > locale.setlocale(locale.LC_ALL, 'sv_Se') > > datetime.date(2006, 06, 19).strftime("%A") > > 'M\xc3\xa5ndag' > > datetime.date(2006, 06, > > 19).strftime("%A").decode('utf8').encode('ascii','ignore') > > 'Mndag' > > > > Somehow, the Swedish character "?" gets dropped in the conversion to ascii. > > how can I accomplish the conversion '?' --> 'a' etc.? should I use a > > dictionary? > > thanks for any insight > > -frank > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From josipl2000 at yahoo.com Mon Jun 19 16:39:11 2006 From: josipl2000 at yahoo.com (josip) Date: Mon, 19 Jun 2006 07:39:11 -0700 (PDT) Subject: [Tutor] projects for beginners Message-ID: <20060619143911.50179.qmail@web60818.mail.yahoo.com> Hi! I have read learning python and mede some smaller examples. Now I want to make smoe project, I'm thinking about text editor. Can someone give me pointers like (where and how to start, etc.)? Or maybe another project suitable for beginners. --------------------------------- Sneak preview the all-new Yahoo.com. It's not radically different. Just radically better. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060619/0f73248f/attachment.html From anushbadii at gmail.com Mon Jun 19 17:52:45 2006 From: anushbadii at gmail.com (anush badii) Date: Mon, 19 Jun 2006 08:52:45 -0700 Subject: [Tutor] local day names in ascii In-Reply-To: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com> Message-ID: Why don't you use the extended ASCII characters where Swedish characters are included. On 6/19/06, frank h. wrote: > > Hello List, > i am trying to convert local Swedish daynames to ASCII > > "M?ndag" should become "Mandag" > "L?rdag" should become "Lordag" > "S?ndag" should become "Sondag" > > here is my session > > import locale > locale.setlocale(locale.LC_ALL, 'sv_Se') > datetime.date(2006, 06, 19).strftime("%A") > 'M\xc3\xa5ndag' > datetime.date(2006, 06, > 19).strftime("%A").decode('utf8').encode('ascii','ignore') > 'Mndag' > > Somehow, the Swedish character "?" gets dropped in the conversion to > ascii. > how can I accomplish the conversion '?' --> 'a' etc.? should I use a > dictionary? > thanks for any insight > > -frank > > > _______________________________________________ > 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/20060619/de4149a2/attachment.htm From mhansen at cso.atmel.com Mon Jun 19 18:34:30 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon, 19 Jun 2006 10:34:30 -0600 Subject: [Tutor] projects for beginners In-Reply-To: <20060619143911.50179.qmail@web60818.mail.yahoo.com> Message-ID: <005801c693be$3d2fcd10$28645f0a@mikehansen> _____ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of josip Sent: Monday, June 19, 2006 8:39 AM To: tutor at python.org Subject: [Tutor] projects for beginners Hi! I have read learning python and mede some smaller examples. Now I want to make smoe project, I'm thinking about text editor. Can someone give me pointers like (where and how to start, etc.)? Or maybe another project suitable for beginners. http://pyfaq.infogami.com/tutor-im-learning-python-what-should-i-program Has a couple of ideas for projects. Mike http://users.adelphia.net/~mahansen/programming/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060619/777c796a/attachment.html From lists at mostrom.pp.se Mon Jun 19 18:52:05 2006 From: lists at mostrom.pp.se (lists at mostrom.pp.se) Date: Mon, 19 Jun 2006 18:52:05 +0200 Subject: [Tutor] local day names in ascii Message-ID: <20060619185205.ezomdmdfi8wwkcw4@webbmail42.loopia.se> Reply to anush badii 06-06-19 08:52: > Why don't you use the extended ASCII characters where Swedish characters are > included. Not to be be picky but "extended ASCII" isn't a character set and have never been. He should be using ISO-8859-1 (or as it's sometimes called Latin 1). jem From david at graniteweb.com Mon Jun 19 20:06:20 2006 From: david at graniteweb.com (David Rock) Date: Mon, 19 Jun 2006 13:06:20 -0500 Subject: [Tutor] Beginner question(s) In-Reply-To: <4495D4E2.6060303@adinet.com.uy> References: <20060618105838.0DB326318@mem01.ecsis.net> <002801c69325$20e48cc0$0301a8c0@XPpro> <4495D4E2.6060303@adinet.com.uy> Message-ID: <20060619180620.GA28264@wdfs.graniteweb.com> * Ismael Garrido [2006-06-18 19:34]: > Alan Gauld wrote: > >> Also, does anyone know of a PDA that would run python? > >> > > > > There was a project called pippy, but I haven't heard anything of it > > recently so I don't know if its still around or if it runs on modern > > PDAs - I think it was PalmOS anyhow... > > > > > > Pippy is quite dead. No development done recently. It supposedly runs > fine, but runs only Python 1.5. Last I used it, it worked fine, but it was limited. -- David Rock david at graniteweb.com From tinoloc at gmail.com Mon Jun 19 22:35:18 2006 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 19 Jun 2006 16:35:18 -0400 Subject: [Tutor] More network server questions Message-ID: Hi Everybody, I took Kent's advice, and used SocketServer instead of rolling my own sockets. It works pretty good except for the fact that when I exit and restart the program, I get a Address in use. And I remember that Danny told me about allow_reuse_address. So, that's where I got stuck. I put in that statement, but no change. What am I missing? class FtpServer ( SocketServer.StreamRequestHandler): def handle(self): self.allow_reuse_address = 1 self.filename=self.rfile.readline(512) self.filename=string.strip(self.filename) while (self.filename != 'exit'): secQueue.put(self.filename) Listener.sema.release() self.filename=self.rfile.readline(512) self.filename=string.strip(self.filename) class Listener( threading.Thread ): sema = threading.Semaphore() def __init__(self): self.port=4242 self.ipAddr='140.147.241.58' self.wholeFilenameList=[] threading.Thread.__init__(self) #print "Done with init" def run(self): server=SocketServer.TCPServer(('',self.port), FtpServer) print "The port is: ", self.port Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060619/57dc6a29/attachment.htm From ulandreman at msn.com Tue Jun 20 06:57:03 2006 From: ulandreman at msn.com (URBAN LANDREMAN) Date: Mon, 19 Jun 2006 23:57:03 -0500 Subject: [Tutor] Writing an "Alt-Enter" Message-ID: I'm trying to write a .csv file which I can subsequently load into Excel. The part that's tripping me up is I want to include an "Alt-Enter" between two of the fields so that when Excel reads the file, it will enter the two fields into the same cell, but on separate lines. Is there a way to do it with chr(x) or \nnn or something similar? My close-to-working code is listed below. Thanks. states = {} states["MN"] = ("Minnesota","St. Paul") states["WI"] = ("Wisconsin","Madison") states["OH"] = ("Ohio","Columbus") oFileName = "c:\PythonExport.csv" ofile = open(oFileName,"w") ofile.write("State Code,State info"+"\n") for stateCode in states.keys(): stateInfo=states[stateCode] ofile.write(stateCode+","+stateInfo[0]+"???"+stateInfo[1]+"\n") ofile.close() Urban Landreman From john at fouhy.net Tue Jun 20 07:13:46 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 20 Jun 2006 17:13:46 +1200 Subject: [Tutor] Writing an "Alt-Enter" In-Reply-To: References: Message-ID: <5e58f2e40606192213q5f0e4306vcd7a0e8ac4560516@mail.gmail.com> On 20/06/06, URBAN LANDREMAN wrote: > I'm trying to write a .csv file which I can subsequently load into Excel. > The part that's tripping me up is I want to include an "Alt-Enter" between > two of the fields so that when Excel reads the file, it will enter the two > fields into the same cell, but on separate lines. Hi, You could try printing a carriage return: '\r'. But, also --- have you looked into the csv module? It's designed for writing (and reading) csv files, and it knows about Excel. It might be that you can feed it strings with newlines in them and it will produce the output you want. -- John. From janos.juhasz at VELUX.com Tue Jun 20 09:59:30 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 20 Jun 2006 09:59:30 +0200 Subject: [Tutor] Warehouse system in python In-Reply-To: Message-ID: Dear All, have seen someone any simple warehouse management framework in python with receive, issue, inventory ? Yours sincerely, ______________________________ Janos Juhasz From kent37 at tds.net Tue Jun 20 12:03:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 06:03:20 -0400 Subject: [Tutor] Writing an "Alt-Enter" In-Reply-To: References: Message-ID: <4497C7E8.6050609@tds.net> URBAN LANDREMAN wrote: > I'm trying to write a .csv file which I can subsequently load into Excel. > The part that's tripping me up is I want to include an "Alt-Enter" between > two of the fields so that when Excel reads the file, it will enter the two > fields into the same cell, but on separate lines. > > Is there a way to do it with chr(x) or \nnn or something similar? An easy experiment answers this. I created an Excel worksheet in this format and saved it as csv. The resulting file has a newline in the field and it is quoted so the newline is interpreted as part of the data rather than the end of a record. Here is the data from the csv file: A,"B C",D E,F,G One way to write a csv file is with the csv module. It takes care of adding quotes around any fields that need them. Here is code to write your data using the csv module: import csv states = [ ("MN", "Minnesota","St. Paul"), ("WI", "Wisconsin","Madison"), ("OH", "Ohio","Columbus"), ] oFileName = "c:\PythonExport.csv" ofile = open(oFileName,"wb") ocsv = csv.writer(ofile) ocsv.writerow(["State Code","State info"]) for stateCode, state, city in states: stateInfo=[stateCode, state + '\n' + city] ocsv.writerow(stateInfo) ofile.close() Notice that the argument to writerow() is a list of strings, and the file must be opened in binary mode ("wb"). Kent From ewald.ertl at hartter.com Tue Jun 20 12:30:21 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue, 20 Jun 2006 12:30:21 +0200 Subject: [Tutor] More network server questions In-Reply-To: References: Message-ID: <4497CE3D.1010507@hartter.com> Hello, after looking into the docs of ServerSocket, the class TCPServer notes the following class attributes: Class variables that may be overridden by derived classes or instances: - address_family - socket_type - request_queue_size (only for stream sockets) - allow_reuse_address so, I think you've to set the allow_reuse_address for the TCPServer and not for the RequestHandler, because this class is newly instantiated for each request of your server. The socket itself is bound by the TCPServer. HTH Ewald Tino Dai wrote: > Hi Everybody, > > I took Kent's advice, and used SocketServer instead of rolling my > own sockets. It works pretty good except for the fact that when I exit > and restart the program, I get a Address in use. And I remember that > Danny told me about allow_reuse_address. So, that's where I got stuck. I > put in that statement, but no change. What am I missing? > > class FtpServer ( SocketServer.StreamRequestHandler): > def handle(self): > self.allow_reuse_address = 1 > self.filename=self.rfile.readline(512) > self.filename=string.strip (self.filename) > while (self.filename != 'exit'): > secQueue.put(self.filename) > Listener.sema.release() > self.filename=self.rfile.readline (512) > self.filename=string.strip(self.filename) > > class Listener( threading.Thread ): > sema = threading.Semaphore() > def __init__(self): > self.port=4242 > self.ipAddr='140.147.241.58' > self.wholeFilenameList=[] > threading.Thread.__init__(self) > #print "Done with init" > > def run(self): > server=SocketServer.TCPServer(('',self.port), FtpServer) > print "The port is: ", self.port > > > Thanks, > Tino > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 paul.kraus at gmail.com Tue Jun 20 14:30:40 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Tue, 20 Jun 2006 08:30:40 -0400 Subject: [Tutor] Python Challange - ord chr incrementing alphabet Message-ID: <4e2aea430606200530v27e76491g6d5fc5e9521f0e43@mail.gmail.com> I just started doing the python challenges and was doing the one where the hint is 3 letters each shifted two places to the right. No big deal just ord / chr and some tests to handle looping past z. I got my answer. Then reading the solutions i see that they suggest that the best way would be to use string.maketrans() I just can't figure this out. What does this do and how would it help with this problem? Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060620/c3ca0d35/attachment.html From alan.gauld at freenet.co.uk Tue Jun 20 15:01:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Jun 2006 14:01:15 +0100 Subject: [Tutor] Writing an "Alt-Enter" References: Message-ID: <001601c69469$9d68b600$0301a8c0@XPpro> > I'm trying to write a .csv file which I can subsequently load into > Excel. > The part that's tripping me up is I want to include an "Alt-Enter" > between two of the fields so that when Excel reads the file, it will > enter the two fields into the same cell, but on separate lines. Create an Excel spreadsheet with one cell. Save as CSV. See what Excel writes out for that character. It might work.... Alan G. From alan.gauld at freenet.co.uk Tue Jun 20 15:03:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Jun 2006 14:03:20 +0100 Subject: [Tutor] Warehouse system in python References: Message-ID: <001c01c69469$ea028b30$0301a8c0@XPpro> > have seen someone any simple warehouse management framework in > python > with receive, issue, inventory ? Thats a pretty uncommon and specific requirement. I certainly haven't but have you tried Google search, a visit to SourceForge or a search on Freshmeat? Best I can think of. Alan G. From adam.jtm30 at gmail.com Tue Jun 20 15:35:19 2006 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 20 Jun 2006 14:35:19 +0100 Subject: [Tutor] Python Challange - ord chr incrementing alphabet In-Reply-To: <4e2aea430606200530v27e76491g6d5fc5e9521f0e43@mail.gmail.com> References: <4e2aea430606200530v27e76491g6d5fc5e9521f0e43@mail.gmail.com> Message-ID: On 20/06/06, Paul D. Kraus wrote: > > I just started doing the python challenges and was doing the one where the > hint is 3 letters each shifted two places to the right. > No big deal just ord / chr and some tests to handle looping past z. > > I got my answer. Then reading the solutions i see that they suggest that > the best way would be to use string.maketrans() > I just can't figure this out. What does this do and how would it help with > this problem? > > Paul > Here's what I came up with for that challenge: def pyc_map():#1 import string t = string.maketrans("abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab") s = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." print s.translate(t) print 'map'.translate(t) string.maketrans() translates the letters with the same index so a=c b=d etc. s.translate needs a translation table which is what string.maketrans() returns so you just use s.translate with t the translation table and it gives you the proper translation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060620/5c1e011c/attachment.htm From matti at niemelat.net Tue Jun 20 15:56:52 2006 From: matti at niemelat.net (=?ISO-8859-1?Q?Matti_Niemel=E4?=) Date: Tue, 20 Jun 2006 16:56:52 +0300 Subject: [Tutor] Universal error handler Message-ID: <4497FEA4.4030709@niemelat.net> Hi! Just started learning Python, and I was wondering if there is a way to catch an error or errors (like EOFError) whenever it occures during the script? The script (the program) wouldn't have any handling for that error itself, but a seperate block would handle that at the start or the end of the file. For a simple 200 line script I made the whole thing into a function, and at the end put: def main(): # Do the program itself.. # The very end try: main() except EOFError: # Tell something went horribly wrong I find this way of doing it disfunctional when having lots of code. Any ideas? - Matti Finland (Heh, first post to any newsgroup or any equivalent ever.. Hope this works!) From carroll at tjc.com Tue Jun 20 16:27:49 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 20 Jun 2006 07:27:49 -0700 (PDT) Subject: [Tutor] Unicode filenames (Windows) Message-ID: Is it possible to process files with Unicode filenames in Windows? Ultimately, I want to read in a series of filenames, and rename them (to remove the unicode characters). In this test, I have one file whose name is XXXX.test, where "XXXX" are unicode characters. First attempt: >>> import os >>> file_list = [x for x in os.listdir('.') if x.endswith('test')] >>> oldname = file_list[0] >>> newname = "spam.test" >>> print oldname ????.test >>> os.rename(oldname,newname) Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 22] Invalid argument >>> PEP 277, http://www.python.org/dev/peps/pep-0277/ , suggests that Windows Unicode filename support was added in Python 2.3 (I'm on 2.4), using the posix module, but no joy: no posix module on my Windows XP install. >>> import posix Traceback (most recent call last): File "", line 1, in ? ImportError: No module named posix >>> From kieran.flanagan at gmail.com Tue Jun 20 16:31:01 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Tue, 20 Jun 2006 15:31:01 +0100 Subject: [Tutor] Question on Logging Module Message-ID: Hi, I have written a number of scripts which write to a remote log. I am using the logging module to produce detailed output. Two questions on this module: 1. One of the scripts loops around for a specified period of time. Previously it would print a message to the console detailing how long it had been waiting for. I used the \r to ensure each message just printed over the previous message, so I didnt get a hundreds of similiar lines with just a short time increase specified. I am not sure how to do this now that I am using the logging module. I just want to print this line to the remote file but just write over the previous log message. Any ideas ? Thanks Kieran -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060620/699a9984/attachment.html From geon at post.cz Tue Jun 20 15:45:36 2006 From: geon at post.cz (Pavel Kosina) Date: Tue, 20 Jun 2006 15:45:36 +0200 Subject: [Tutor] Python Challange - ord chr incrementing alphabet In-Reply-To: References: <4e2aea430606200530v27e76491g6d5fc5e9521f0e43@mail.gmail.com> Message-ID: <4497FC00.3070605@post.cz> Adam napsal(a): > > Here's what I came up with for that challenge: > def pyc_map():#1 > [....] oops, you shouldnt do that. Its against the pychalenge rules. You give here complete solution. I thing that this link should do it all : http://wiki.pythonchallenge.com/index.php?title=Main_Page -- geon Pavel Kosina From tinoloc at gmail.com Tue Jun 20 16:47:43 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 20 Jun 2006 10:47:43 -0400 Subject: [Tutor] More network server questions In-Reply-To: <4497CE3D.1010507@hartter.com> References: <4497CE3D.1010507@hartter.com> Message-ID: > so, I think you've to set the allow_reuse_address for the TCPServer and > not for the RequestHandler, because this class is newly instantiated for > each request of your server. > The socket itself is bound by the TCPServer. > > HTH Ewald Hi there Ewald, I tried that, and still no joy. Now I have: class Listener( threading.Thread ): sema = threading.Semaphore() def __init__(self): self.port=xxxx self.ipAddr='xxx.xxx.xxx.xxx' self.wholeFilenameList=[] threading.Thread.__init__(self) #print "Done with init" def run(self): server=SocketServer.TCPServer(('',self.port), FtpServer) server.allow_reuse_address = 1 <- I moved the server.allow_reuse_adddress from the FtpServer, which was SocketServer.StreamRequestHandler print "The port is: ", self.port server.serve_forever() Any clue on what I am missing? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060620/4b0903ce/attachment.htm From kent37 at tds.net Tue Jun 20 17:39:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 11:39:45 -0400 Subject: [Tutor] More network server questions In-Reply-To: References: <4497CE3D.1010507@hartter.com> Message-ID: <449816C1.1070203@tds.net> Tino Dai wrote: > > so, I think you've to set the allow_reuse_address for the TCPServer and > not for the RequestHandler > Hi there Ewald, > > I tried that, and still no joy. Now I have: > > class Listener( threading.Thread ): > sema = threading.Semaphore() > def __init__(self): > self.port=xxxx > self.ipAddr='xxx.xxx.xxx.xxx' > self.wholeFilenameList=[] > threading.Thread.__init__(self) > #print "Done with init" > > > def run(self): > server=SocketServer.TCPServer(('',self.port), FtpServer) > server.allow_reuse_address = 1 <- I moved the > server.allow_reuse_adddress from the FtpServer, which was > SocketServer.StreamRequestHandler > print "The port is: ", self.port > server.serve_forever() > > > Any clue on what I am missing? Looking at the source code for SocketServer, you have to set allow_reuse_address *before* instantiating the server, because the value is used by the __init__() method. allow_reuse_address is actuall a class attribute, not an instance attribute. One way to do this is to set the class attribute directly: SocketServer.TCPServer.allow_reuse_address = 1 This will change the behaviour of any TCPServer created after this assignment. If you want to just change the one server you create, make your own server subclass and set allow_reuse_address there: class MyServer(SocketServer.TCPServer): allow_reuse_address = True then instantiate MyServer instead of TCPServer. Kent From kent37 at tds.net Tue Jun 20 17:52:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 11:52:54 -0400 Subject: [Tutor] Unicode filenames (Windows) In-Reply-To: References: Message-ID: <449819D6.5000606@tds.net> Terry Carroll wrote: > Is it possible to process files with Unicode filenames in Windows? > > Ultimately, I want to read in a series of filenames, and rename them (to > remove the unicode characters). > > In this test, I have one file whose name is XXXX.test, where "XXXX" are > unicode characters. > > First attempt: > >>>> import os >>>> file_list = [x for x in os.listdir('.') if x.endswith('test')] >>>> oldname = file_list[0] >>>> newname = "spam.test" >>>> print oldname > ????.test >>>> os.rename(oldname,newname) > Traceback (most recent call last): > File "", line 1, in ? > OSError: [Errno 22] Invalid argument > > PEP 277, http://www.python.org/dev/peps/pep-0277/ , suggests that Windows > Unicode filename support was added in Python 2.3 (I'm on 2.4), using the > posix module, but no joy: no posix module on my Windows XP install. I'm guessing that when PEP 277 refers to the posix module maybe it means the os module. What happens if you pass a Unicode string to listdir(), e.g. os.listdir(u'.')? Hmm, looks promising: In [3]: os.listdir(u'.') Out[3]: [u'enterData.py', u'test.py', u'SPY2.csv', u'\xe1\xe9\xed\xf3\xfa'] In [4]: p=_[3] In [5]: p Out[5]: u'\xe1\xe9\xed\xf3\xfa' In [6]: os.rename(p, u'foo') In [7]: os.listdir(u'.') Out[7]: [u'enterData.py', u'test.py', u'SPY2.csv', u'foo'] Kent From kent37 at tds.net Tue Jun 20 18:02:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 12:02:09 -0400 Subject: [Tutor] Universal error handler In-Reply-To: <4497FEA4.4030709@niemelat.net> References: <4497FEA4.4030709@niemelat.net> Message-ID: <44981C01.5030700@tds.net> Matti Niemel? wrote: > Hi! > > Just started learning Python, and I was wondering if there is a way to > catch an error or errors (like EOFError) whenever it occures during the > script? The script (the program) wouldn't have any handling for that > error itself, but a seperate block would handle that at the start or the > end of the file. For beginners, often the best solution is not to catch the errors at all, but let the runtime catch it and give you a stack trace and error message. This is much better than catching it yourself and printing a generic error message because it will show you exactly where and what the error is. It is also much easier to get help here if you have a stack trace to show. If you really want to trap the errors, your approach below is fine, there is nothing wrong with encapsulating your main code in a function. The more code you have the more likely that this is a reasonable way to structure the code anyway. OK, if you really have to have a global way to configure the error handler, look at sys.excepthook. This lets you install your own error handler for uncaught exceptions. If the docs are completely confusing, you probably shouldn't be using it... :-) Kent > > For a simple 200 line script I made the whole thing into a function, and > at the end put: > > def main(): > # Do the program itself.. > > # The very end > try: > main() > except EOFError: > # Tell something went horribly wrong > > > I find this way of doing it disfunctional when having lots of code. Any > ideas? From alan.gauld at freenet.co.uk Tue Jun 20 19:36:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Jun 2006 18:36:53 +0100 Subject: [Tutor] Universal error handler References: <4497FEA4.4030709@niemelat.net> Message-ID: <003a01c69490$1eaaa860$0301a8c0@XPpro> > Just started learning Python, and I was wondering if there is a way > to catch an error or errors (like EOFError) whenever it occures > during the script? The script (the program) wouldn't have any > handling for that error itself, but a seperate block would handle > that at the start or the end of the file. Thats pretty much a description of try/except handling style but... > For a simple 200 line script I made the whole thing into a function, > and at the end put: > > def main(): > # Do the program itself.. > > # The very end > try: > main() > except EOFError: > # Tell something went horribly wrong > I find this way of doing it disfunctional when having lots of code. It looks a lot like what you asked for! What do you find disfunctional? Is it the call to the main function? You could just write the code: try: # contents of main here except EOFError: # error code here But I assume you realised that, son what exactly do you find amiss? I'm a wee bit confused. But your post worked - it got a response, cxongratulations, welcome to the community :-) Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From paul.kraus at gmail.com Tue Jun 20 19:49:20 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Tue, 20 Jun 2006 13:49:20 -0400 Subject: [Tutor] string formatting currency Message-ID: <4e2aea430606201049r4ff10bcdj39f9d14228a4c76f@mail.gmail.com> How can i print a float as a currency with commas. 1222333.4 -> 1,222,333.40 if i '%0.2f'%number i get 1222333.40 Thanks, Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060620/be1099fa/attachment.htm From python at venix.com Tue Jun 20 20:03:50 2006 From: python at venix.com (Python) Date: Tue, 20 Jun 2006 14:03:50 -0400 Subject: [Tutor] Warehouse system in python In-Reply-To: References: Message-ID: <1150826630.10267.3.camel@www.venix.com> On Tue, 2006-06-20 at 09:59 +0200, J?nos Juh?sz wrote: > Dear All, > > have seen someone any simple warehouse management framework in python > with receive, issue, inventory ? I have not used it, so I don't know the scope of what they do, but tinyerp includes stock management. http://www.tinyerp.com/ > > > Yours sincerely, > ______________________________ > Janos Juhasz > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From emily.fortuna at nist.gov Tue Jun 20 20:06:08 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Tue, 20 Jun 2006 14:06:08 -0400 Subject: [Tutor] Universal error handler In-Reply-To: <4497FEA4.4030709@niemelat.net> References: <4497FEA4.4030709@niemelat.net> Message-ID: <44983910.7000706@nist.gov> Hi Matti! Chances are you may have already seen this, but here are a list of the different Python errors you can catch: http://www.python.org/doc/1.5.2p2/api/standardExceptions.html > Just started learning Python, and I was wondering if there is a way to > catch an error or errors (like EOFError) whenever it occures during the > script? The script (the program) wouldn't have any handling for that > error itself, but a seperate block would handle that at the start or the > end of the file. Perhaps you have some other reason for putting the try/except pair outside of the main function, (Other discussion welcome on this; I am sure there are much more experienced programmers and software design enthusiasts than I.) but I might suggest that you consider just putting the specific lines that you think will catch the error in the try block, rather than the whole main function. This way you will know much more specifically what is causing the error, and you can handle different errors more specifically. HTH, Emily From kent37 at tds.net Tue Jun 20 20:13:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 14:13:23 -0400 Subject: [Tutor] string formatting currency In-Reply-To: <4e2aea430606201049r4ff10bcdj39f9d14228a4c76f@mail.gmail.com> References: <4e2aea430606201049r4ff10bcdj39f9d14228a4c76f@mail.gmail.com> Message-ID: <44983AC3.4080906@tds.net> Paul D. Kraus wrote: > How can i print a float as a currency with commas. > > 1222333.4 -> 1,222,333.40 > > if i '%0.2f'%number > > i get > 1222333.40 Use locale.format(): In [1]: import locale In [2]: f=1222333.4 In [6]: locale.setlocale(locale.LC_ALL, "") Out[6]: 'English_United States.1252' In [7]: locale.format('%.2f', f, True) Out[7]: '1,222,333.40' Kent From andrew.arobert at gmail.com Tue Jun 20 20:37:42 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 20 Jun 2006 14:37:42 -0400 Subject: [Tutor] Universal error handler In-Reply-To: <003a01c69490$1eaaa860$0301a8c0@XPpro> References: <4497FEA4.4030709@niemelat.net> <003a01c69490$1eaaa860$0301a8c0@XPpro> Message-ID: <44984076.7020504@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 You may also want to try a error handling like this. It is platform clean and uses the system standard logging routines. import os, logging, logging.handlers def eventlogger(level,message): """ Sent trapped events to NT application event logger """ if os.name == "nt": logger = logging.getLogger("") logger.setLevel(logging.DEBUG) ntl = logging.handlers.NTEventLogHandler("Program Event Logger Message") logger.addHandler(ntl) try: method = getattr(logger,level) message = "%s message: %s" % (level.capitalize(),message) method(message) sys.exit(0) except AttributeError: method = logger.critical message = "Uncoded event level" method(message) sys.exit(1) else : import syslog, time timestamp = time.asctime(time.localtime(time.time())) logmsg = "Event Logger - %s - %s :: $s " % (timestamp, level.capitalize(),message) syslogg.syslog(logmsg) You then call it as a function from wherever an error gets raised. msg="OH NO - blue screen of death" eventlogger("error",msg) msg="OH NO - system slow - scary but you will live" eventlogger("warning",msg) msg="Shh - don't tell anyone but it worked" eventlogger("info",msg) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEmEB2Dvn/4H0LjDwRAhlmAKCzch2JVynMsNcCY9Cnu8crMqN5fQCfQJWu ZT8frQiRZXKJZMLeGnyeFbM= =zCBc -----END PGP SIGNATURE----- From python at venix.com Tue Jun 20 20:47:05 2006 From: python at venix.com (Python) Date: Tue, 20 Jun 2006 14:47:05 -0400 Subject: [Tutor] string formatting currency In-Reply-To: <4e2aea430606201049r4ff10bcdj39f9d14228a4c76f@mail.gmail.com> References: <4e2aea430606201049r4ff10bcdj39f9d14228a4c76f@mail.gmail.com> Message-ID: <1150829225.10267.8.camel@www.venix.com> On Tue, 2006-06-20 at 13:49 -0400, Paul D. Kraus wrote: > How can i print a float as a currency with commas. > > 1222333.4 -> 1,222,333.40 > > if i '%0.2f'%number > > i get > 1222333.40 import locale >>> locale.setlocale(locale.LC_ALL,"") 'en_US.UTF-8' >>> currency_symbol = locale.localeconv()['currency_symbol'] >>> num = 1222333.4 >>> print currency_symbol + locale.format("%.2f", num, 1) # insert commas $1,222,333.40 > > Thanks, > Paul > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From matti at niemelat.net Tue Jun 20 22:33:03 2006 From: matti at niemelat.net (=?ISO-8859-1?Q?Matti_Niemel=E4?=) Date: Tue, 20 Jun 2006 23:33:03 +0300 Subject: [Tutor] Universal error handler In-Reply-To: <003a01c69490$1eaaa860$0301a8c0@XPpro> References: <4497FEA4.4030709@niemelat.net> <003a01c69490$1eaaa860$0301a8c0@XPpro> Message-ID: <44985B7F.9060705@niemelat.net> Thank you all for your replies. > It looks a lot like what you asked for! What do you find > disfunctional? Is it the call to the main function? I'm just trying to find a way not to indent the code more then necessary. Makes it messy. That's just me :) > Chances are you may have already seen this, but here are a list of the different Python errors you can catch: > http://www.python.org/doc/1.5.2p2/api/standardExceptions.html Thank you Emily Fortuna for the error types list, just what I was also after (no doubt Google wouldn't have told me those, but thanks anyways =D ) Kent > For beginners, often the best solution is not to catch the errors at > all, but let the runtime catch it and give you a stack trace and error > message. No problem there. Somewhat 5 years of PHP now, so normal debuggin etc. is all routine for me. And since I tend to aim for perfection and the gratest simplicity, I indeed want to handle the errors properly :) I'm propably going to clean up my contacts script (what I was talking about originally) and put it here, since I'd like to get some feedback on the way I write Python. Thank you all, - Matti Finland From carroll at tjc.com Wed Jun 21 00:16:05 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 20 Jun 2006 15:16:05 -0700 (PDT) Subject: [Tutor] Unicode filenames (Windows) In-Reply-To: <449819D6.5000606@tds.net> Message-ID: On Tue, 20 Jun 2006, Kent Johnson wrote: > What happens if you pass a Unicode string to listdir(), > e.g. os.listdir(u'.')? Doh! I should've thought of that. Works great. Of course, in the meantime I went through and manually renamed 100 files by hand, but this is good to know for the next time! Thanks, Kent! From cspears2002 at yahoo.com Wed Jun 21 02:54:23 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 20 Jun 2006 17:54:23 -0700 (PDT) Subject: [Tutor] critique my script! Message-ID: <20060621005423.81416.qmail@web51614.mail.yahoo.com> Here is a little gui I created: #!/usr/bin/python import os, pygtk pygtk.require('2.0') import gtk class GetCwd: def getcwd(self, widget, data=None): print os.getcwd() def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Get Current Working Dir") self.window.set_border_width(10) self.window.connect("delete_event", self.delete_event) self.box = gtk.HBox(False, 0) self.window.add(self.box) self.button = gtk.Button("Current Working Directory") self.button.connect("clicked", self.getcwd) self.box.pack_start(self.button, True, True, 0) self.button.show() self.box.show() self.window.show() def main(self): gtk.main() if __name__ == "__main__": gui = GetCwd() gui.main() What do you think? One of my main areas of confusion is that I have seemed similar scripts written without 'self.button' or 'self.box'. The programmer simply uses 'button' or 'box' instead. From rstoos at rochester.rr.com Wed Jun 21 03:20:40 2006 From: rstoos at rochester.rr.com (Ralph H. Stoos Jr.) Date: Tue, 20 Jun 2006 21:20:40 -0400 Subject: [Tutor] Help? Making Variables out of the header row in a CSV file Message-ID: <44989EE8.8090109@rochester.rr.com> All, Please forgive the long question, but duty calls me to get something done with Python that I don't want somebody to do with Microsloth Excel or Miserable Basic. The part I can't seem to get going has to do with making variables out of the header row in the CSV file. The way it needs to work is that the first row may be of differing lengths (extra fields). I want to have the standalone Python script to make the variables and then allow the user to sort the data based on the contents of the columns (i.e. pull out the records that match one or more criteria). The final product would allow me to select the input file, specify some thing like the value of the "PPM" or "Grain" (and combinations thereof), and write the output to a new CSV file. The last bit would be some math on the contents of a couple of the fields. Here is a snippet of the data so you can see what I am dealing with. Machine,PurgeSuccess,PurgePrepared,PurgeStarted,PurgeCauseFaultID,PurgeModId,PurgeStopModId,ModIdJobCfg,NameJobCfg,Full_cfg,FinisherCfg,plex,PPM,PropID,AtreeNodeID,JobID,MediaID,Width,Height,Color,Weight,Caliper,Drilled,Finish,Grain,CoatingFront,CoatingBack,SW,additional_info,debuglog 1125785731,N,Y,Y,927,6,5,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Simplex,120,44366,1228,392,527,279400,431800,white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_24.07_48_00 1125785731,Y,Y,N,1003,6,,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Duplex,120,69206,75,408,29,279400,431800,white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_31.14_33_25A Regards, Ralph From rabidpoobear at gmail.com Wed Jun 21 04:06:58 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 20 Jun 2006 21:06:58 -0500 Subject: [Tutor] Help? Making Variables out of the header row in a CSV file In-Reply-To: <44989EE8.8090109@rochester.rr.com> References: <44989EE8.8090109@rochester.rr.com> Message-ID: <4498A9C2.3050006@gmail.com> Ralph H. Stoos Jr. wrote: > All, > > Please forgive the long question, but duty calls me to get something > done with Python that I don't want somebody to do with Microsloth Excel or Miserable > Basic. > I am sympathetic to your cause. > The part I can't seem to get going has to do with making variables out > of the header row in the CSV file. The way it needs to work is that the > first row may be of differing lengths (extra fields). I want to have > the standalone Python script to make the variables and then allow the user > to sort the data based on the contents of the columns (i.e. pull out the > records that match one or more criteria). > #test.py f = file("FOO.CSV","r") txt = f.readlines() f.close() headers = txt[0].strip().split(",") infotable = {} txt.pop(0) for x in range(len(headers)): infotable[headers[x]] = [y.split(",")[x].strip() for y in txt] print infotable #end of test.py #output {'PurgeModId': ['6', '6'], 'SW': ['RV0.6.5.27', 'RV0.6.5.27'], 'JobID': ['392', '408'], 'Machine': ['1125785731', '1125785731'], 'Width': ['279400', '279400'], 'CoatingFront': ['none', 'none'], 'AtreeNodeID': ['1228', '75'], 'Finish': ['regular', 'regular'], 'PurgeSuccess': ['N', 'Y'], 'PPM': ['120', '120'], 'additional_info': ['', ''], 'CoatingBack': ['none', 'none'], 'PropID': ['44366', '69206'], 'Full_cfg': ['_SFM20_IOT7_SFM7_BFM20_BFM2', '_SFM20_IOT7_SFM7_BFM20_BFM2'], 'MediaID': ['527', '29'], 'PurgeStarted': ['Y', 'N'], 'NameJobCfg': ['_SFM20_IOT7_SFM7_BFM20_BFM2', '_SFM20_IOT7_SFM7_BFM20_BFM2'], 'PurgeStopModId': ['5', ''], 'plex': ['Simplex', 'Duplex'], 'Grain': ['y', 'y'], 'debuglog': ['DebugMsgLog.2006_05_24.07_48_00', 'DebugMsgLog.2006_05_31.14_33_25A'], 'ModIdJobCfg': ['_2_3_4_5_6', '_2_3_4_5_6'], 'Weight': ['75', '75'], 'Color': ['white', 'white'], 'PurgeCauseFaultID': ['927', '1003'], 'Caliper': ['104', '104'], 'Height': ['431800', '431800'], 'PurgePrepared': ['Y', 'Y'], 'FinisherCfg': ['DUAL_BFM', 'DUAL_BFM'], 'Drilled': ['FALSE', 'FALSE']} > The final product would allow me to select the input file, specify some thing > like the value of the "PPM" or "Grain" (and combinations thereof), and > write the output to a new CSV file. The last bit would be some math on the contents of a couple of the fields. > You mean you want to be able to make a new CSV file using the contents of the old one, or create an entirely new one using just stuff you need? Please clarify here. > Ralph Luke From dyoo at hkn.eecs.berkeley.edu Wed Jun 21 04:10:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Jun 2006 19:10:30 -0700 (PDT) Subject: [Tutor] critique my script! In-Reply-To: <20060621005423.81416.qmail@web51614.mail.yahoo.com> References: <20060621005423.81416.qmail@web51614.mail.yahoo.com> Message-ID: On Tue, 20 Jun 2006, Christopher Spears wrote: > Here is a little gui I created: [gui code cut] Hi Christopher, Looks ok so far. One approach that has a lot of popularity behind it is called the "model-view-controller" approach. The idea is that we should be able to build up the graphical part, the part that does all the windows and buttons and textboxes. We should be able to develop this "view" independently of the part that does the real work, the model. We should then be able to control these two parts and explicitely link them together. Concretely, we can take the program you showed us, and make it temporarily less useful. *grin* Here's an example of this: ################################################################## class View: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Get Current Working Dir") self.window.set_border_width(10) self.window.connect("delete_event", self.delete_event) self.box = gtk.HBox(False, 0) self.window.add(self.box) self.button = gtk.Button("Current Working Directory") self.button.connect("clicked", self.button_pressed) self.box.pack_start(self.button, True, True, 0) def do_nothing(): pass self.on_button_pressed = do_nothing self.button.show() self.box.show() self.window.show() def button_pressed(self, widget, data=None): self.on_button_pressed() def delete_event(self, widget, event, data=None): gtk.main_quit() return False def main(self): gtk.main() ################################################################## It's basically your program, minus any of the useful stuff that does getcwd(). There's a small level of indirection here: the button is hooked up to button_pressed, which calls on_button_pressed, which does_nothing. And of course, this is useless! We can bring up this view, and press its buttons, but nothing happens. However, we can fix that: we can rewire up the view so that on_button_pressed doesn't do_nothing(), but does something more interesting, something like: ######################################### view = View() view.on_button_pressed = os.getcwd ######################################### If we do then, then we can patch up our main entry point and get back the original behavior of the program: ###################################### if __name__ == '__main__': view = View() view.on_button_pressed = os.getcwd view.main() ###################################### But why bother with this? The advantage of this approach is that it becomes easy to rewire this same view with different models. For example: ###### view = View() def say_hello(): print "hello world" view.on_button_pressed = say_hello ###### Bam. Now we have a GUI that should say hello when we press the button. Of course, the title bars and button text are all wrong. But that's something that can be fixed by making the View more general and passing in the explicit text strings into the constructor. ############################################################### class OneButtonView: def __init__(self, title, button_text): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title(title) self.window.set_border_width(10) self.window.connect("delete_event", self.delete_event) self.box = gtk.HBox(False, 0) self.window.add(self.box) self.button = gtk.Button(button_text) self.button.connect("clicked", self.button_pressed) self.box.pack_start(self.button, True, True, 0) def do_nothing(): pass self.on_button_pressed = do_nothing self.button.show() self.box.show() self.window.show() def button_pressed(self, widget, data=None): self.on_button_pressed() def delete_event(self, widget, event, data=None): gtk.main_quit() return False def main(self): gtk.main() ############################################################## And now we can either have the original program: ############################################################### def cwd_gui_program(): view = OneButtonView("Get Current Working Directory", "Current Working Directory") view.on_button_pressed = os.getcwd view.main() ############################################################### Or we can have a happy hello world gui: ############################################################### def hello_world_gui_program(): view = OneButtonView("Hello World", "Press me please") def say_hello(): print "hello happy world" view.on_button_pressed = say_hello view.main() ############################################################### The point is that if we break things up like this, we now have a general OneButtonView GUI that shows up a button, and lets the user press it to activate a function. Does this make sense? Best of wishes! From kent37 at tds.net Wed Jun 21 04:12:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jun 2006 22:12:44 -0400 Subject: [Tutor] Help? Making Variables out of the header row in a CSV file In-Reply-To: <44989EE8.8090109@rochester.rr.com> References: <44989EE8.8090109@rochester.rr.com> Message-ID: <4498AB1C.1070201@tds.net> Ralph H. Stoos Jr. wrote: > All, > > Please forgive the long question, but duty calls me to get something > done with Python that I don't want somebody to do with Microsloth Excel or Miserable > Basic. It's not such a long question. > The part I can't seem to get going has to do with making variables out > of the header row in the CSV file. The way it needs to work is that the > first row may be of differing lengths (extra fields). I want to have > the standalone Python script to make the variables and then allow the user > to sort the data based on the contents of the columns (i.e. pull out the > records that match one or more criteria). > > The final product would allow me to select the input file, specify some thing > like the value of the "PPM" or "Grain" (and combinations thereof), and > write the output to a new CSV file. The last bit would be some math on the contents of a couple of the fields. > > Here is a snippet of the data so you can see what I am dealing with. > > Machine,PurgeSuccess,PurgePrepared,PurgeStarted,PurgeCauseFaultID,PurgeModId,PurgeStopModId,ModIdJobCfg,NameJobCfg,Full_cfg,FinisherCfg,plex,PPM,PropID,AtreeNodeID,JobID,MediaID,Width,Height,Color,Weight,Caliper,Drilled,Finish,Grain,CoatingFront,CoatingBack,SW,additional_info,debuglog > 1125785731,N,Y,Y,927,6,5,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Simplex,120,44366,1228,392,527,279400,431800,white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_24.07_48_00 > 1125785731,Y,Y,N,1003,6,,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Duplex,120,69206,75,408,29,279400,431800,white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_31.14_33_25A The csv module will do what you need as far as reading and writing the data. You can use a DictReader to read each row of data into a dictionary whose keys are the row names. Then you can process the rows as needed and write them out using csv.DictWriter. Here is a short example: In [1]: import csv This is your sample data. Normally you would read from an open file, for the example I read from a simple list. In [2]: data = '''Machine,PurgeSuccess,PurgePrepared,PurgeStarted,PurgeCauseFaultID,PurgeModId,PurgeStopModId,ModIdJobCfg,NameJobCfg,Full_cfg,Finisher Cfg,plex,PPM,PropID,AtreeNodeID,JobID,MediaID,Width,Height,Color,Weight,Caliper,Drilled,Finish,Grain,CoatingFront,CoatingBack,SW,additional_info,debug log ...: 1125785731,N,Y,Y,927,6,5,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Simplex,120,44366,1228,392,527,279400,431 800,white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_24.07_48_00 ...: 1125785731,Y,Y,N,1003,6,,_2_3_4_5_6,_SFM20_IOT7_SFM7_BFM20_BFM2,_SFM20_IOT7_SFM7_BFM20_BFM2,DUAL_BFM,Duplex,120,69206,75,408,29,279400,431800, white,75,104,FALSE,regular,y,none,none,RV0.6.5.27,,DebugMsgLog.2006_05_31.14_33_25A ...: ...: ...: '''.splitlines() Oops, got some extra blank lines in there too: In [3]: len(data) Out[3]: 5 Make a DictReader from the data. It will read the column names from the first row. In [4]: r=csv.DictReader(data) This reads the rows from the DictReader into a list. Each item in the list is a dictionary with values from one row of input. In [5]: rows = [ row for row in r ] Here is one of the dicts: In [6]: rows[0] Out[6]: {'AtreeNodeID': '1228', 'Caliper': '104', 'CoatingBack': 'none', 'CoatingFront': 'none', 'Color': 'white', 'Drilled': 'FALSE', 'Finish': 'regular', 'FinisherCfg': 'DUAL_BFM', 'Full_cfg': '_SFM20_IOT7_SFM7_BFM20_BFM2', 'Grain': 'y', 'Height': '431800', 'JobID': '392', 'Machine': '1125785731', 'MediaID': '527', 'ModIdJobCfg': '_2_3_4_5_6', 'NameJobCfg': '_SFM20_IOT7_SFM7_BFM20_BFM2', 'PPM': '120', 'PropID': '44366', 'PurgeCauseFaultID': '927', 'PurgeModId': '6', 'PurgePrepared': 'Y', 'PurgeStarted': 'Y', 'PurgeStopModId': '5', 'PurgeSuccess': 'N', 'SW': 'RV0.6.5.27', 'Weight': '75', 'Width': '279400', 'additional_info': '', 'debuglog': 'DebugMsgLog.2006_05_24.07_48_00', 'plex': 'Simplex'} Now process the list of dicts as you like, for example pulling out the PPM values: In [7]: [ row['PPM'] for row in rows ] Out[7]: ['120', '120'] To allow users to write ad-hoc queries is more difficult. If you can restrict them to a few kinds of query it will be easier. I hope this gets you started, Kent From dyoo at hkn.eecs.berkeley.edu Wed Jun 21 04:13:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Jun 2006 19:13:15 -0700 (PDT) Subject: [Tutor] critique my script! In-Reply-To: References: <20060621005423.81416.qmail@web51614.mail.yahoo.com> Message-ID: > doesn't do_nothing(), but does something more interesting, something like: > > ######################################### > view = View() > view.on_button_pressed = os.getcwd > ######################################### Gaaa. Quick revision: ################################## def print_cwd(): print os.getcwd() view = View() view.on_button_pressed = print_cwd ################################## Anywhere in my previous message that uses os.getcwd() as the model should be fixed to use print_cwd(). Sorry about that! From rabidpoobear at gmail.com Wed Jun 21 04:16:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 20 Jun 2006 21:16:44 -0500 Subject: [Tutor] Help? Making Variables out of the header row in a CSV file In-Reply-To: <4498AB1C.1070201@tds.net> References: <44989EE8.8090109@rochester.rr.com> <4498AB1C.1070201@tds.net> Message-ID: <4498AC0C.3070001@gmail.com> Kent Johnson wrote: [snip better solution than mine] Yeah. I didn't know what CSV files were and I should've researched it a bit. Didn't know there was a CSV module. Good explanation Kent. -Luke From cspears2002 at yahoo.com Wed Jun 21 05:11:54 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 20 Jun 2006 20:11:54 -0700 (PDT) Subject: [Tutor] critique my script! In-Reply-To: Message-ID: <20060621031154.5660.qmail@web51611.mail.yahoo.com> I made the changes that Danny suggested to my script: #!/usr/bin/python import os, pygtk pygtk.require('2.0') import gtk class View: def delete_event(self, widget, event, data=None): gtk.main_quit() return False def button_pressed(self, widget, data=None): self.on_button_pressed() def __init__(self,title, button_text): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title(title) self.window.set_border_width(10) self.window.connect("delete_event", self.delete_event) def do_nothing(): pass self.on_button_pressed = do_nothing self.box = gtk.HBox(False, 0) self.window.add(self.box) self.button = gtk.Button(button_text) self.button.connect("clicked", self.button_pressed) self.box.pack_start(self.button, True, True, 0) self.button.show() self.box.show() self.window.show() def main(self): gtk.main() if __name__ == "__main__": view = View("Hello World!", "Press me please!") #def print_getcwd(): #print os.getcwd() def say_hello(): print "Hello World!" view.on_button_pressed = say_hello view.main() I can apparently call the functions sometimes without (). Why is that? From kieran.flanagan at gmail.com Wed Jun 21 13:33:14 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Wed, 21 Jun 2006 12:33:14 +0100 Subject: [Tutor] Writing over a line in a text file Message-ID: Hi I have a question regarding writing text to a file. I am directing output to a logfile. During one of the loops, I have a command that will issue a message on how long it is waiting for by doing something like this while something: print "\rNow waiting %s seconds .. " % seconds, sys.stdout.flush() print "\r ", I am trying to change my scripts so all info can be accessed via logfiles. Is there any way I can direct the output to a logfile, as above, without creating a new line for each print statement. I have tried changing the sys.stdout to the logfile in question but the print commands just force a new line for each print statement. Any ideas would be welcome. Cheers Kieran -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060621/69081006/attachment.html From govilakanksha at yahoo.com Wed Jun 21 14:06:13 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Wed, 21 Jun 2006 05:06:13 -0700 (PDT) Subject: [Tutor] Need python 2.4 rpm for Suse 9.1 Message-ID: <20060621120613.8579.qmail@web36511.mail.mud.yahoo.com> Hi, I searched the sites but was unable to find Python 2.4 rpm for Suse 9.1. Please send me a link where I can download this. Thanks Akanksha --------------------------------- Yahoo! Sports Fantasy Football ?06 - Go with the leader. Start your league today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060621/b6b5efcc/attachment.html From kent37 at tds.net Wed Jun 21 14:15:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Jun 2006 08:15:29 -0400 Subject: [Tutor] Writing over a line in a text file In-Reply-To: References: Message-ID: <44993861.1050408@tds.net> kieran flanagan wrote: > Hi > > I have a question regarding writing text to a file. I am directing > output to a logfile. During one of the loops, I have a command that will > issue a message on how long it is waiting for by doing something like this > > while something: > > print "\rNow waiting %s seconds .. " % seconds, > sys.stdout.flush() > print "\r ", > > I am trying to change my scripts so all info can be accessed via > logfiles. Is there any way I can direct the output to a logfile, as > above, without creating a new line for each print statement. I have > tried changing the sys.stdout to the logfile in question but the print > commands just force a new line for each print statement. > > Any ideas would be welcome. Printing to a file will normally append to the file. To overwrite something in a file you have to seek to the location where you want to write and write the new information there. Here is a sketch which is probably wrong (!) because I don't ever have to do this... f = open('log.txt', 'w') print >>f, 'This line doesn\'t change' where = f.tell() # remember the current location in f for i in range(10): f.seek(where) print >>f, 'Counting...', i This will break if the rewrite is not at the end of the file (overwrites in the middle of a file can't change the length of the file) or if another thread is also writing the file. I wonder if a log file is the right mechanism for what you are trying to do? From your previous messages I guess you are doing a remote log. Maybe you should be monitoring log messages some other way? Or use tail to view the remote file so you just see the last line of the file? Kent From rabidpoobear at gmail.com Wed Jun 21 14:24:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 21 Jun 2006 07:24:22 -0500 Subject: [Tutor] Writing over a line in a text file In-Reply-To: References: Message-ID: <44993A76.5030305@gmail.com> kieran flanagan wrote: > Hi > > I have a question regarding writing text to a file. I am directing > output to a logfile. During one of the loops, I have a command that > will issue a message on how long it is waiting for by doing something > like this > > while something: > > print "\rNow waiting %s seconds .. " % seconds, > sys.stdout.flush() > print "\r ", > > I am trying to change my scripts so all info can be accessed via > logfiles. Is there any way I can direct the output to a logfile, as > above, without creating a new line for each print statement. I have > tried changing the sys.stdout to the logfile in question but the print > commands just force a new line for each print statement. I don't understand what the commas atthe end of your print commands are for. Nor do I understand what you're trying to do. Are you trying to redirect stdout to a file? why bother doing this? why not just do from time import sleep from random import randint f = file("log.txt","a") while x < y: f.write("\nNow waiting %s seconds\n" % randint(0,4)) f.close() Or do I misunderstand what your objective is? Also, I believe \r is windows-only, and you should use \n all the time, or \r\n. From kieran.flanagan at gmail.com Wed Jun 21 15:09:53 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Wed, 21 Jun 2006 14:09:53 +0100 Subject: [Tutor] Writing over a line in a text file In-Reply-To: <44993A76.5030305@gmail.com> References: <44993A76.5030305@gmail.com> Message-ID: Thanks for both your replies Yes I think you may have misunderstood my orginal post Luke. The portion of code I gave will ensure each time this line is written it just writes over the previous line ( when printed to the console and \r is not windows specific). As I said, I have tried numerous ways to write these commands to a logfile so the line will just be written over ( the method you gave will just create a newline per iteration of the loop), as it is if I direct the output to the console. The section of code I gave is contained within a while loop, which is constantly checking for something to appear on a website. It simple prints out a line, letting the user know how long it has been waiting for. On the console this will just appear as one line ( each iteration writing the line over the previous one). In the logfile, this wil be a new line for each iteration of the while loop. To answer Kents questions, I previously had these outputs going to a logfile which could just be tailed. I now want to change the way I display the logs created. I firstly create a logfile within an apache server, this logfile appears as a link on a frontend website beside a corresponding test name. I then want to output all log messages to this one file. For what I am doing, it would be extremely useful for any number of users to just click on a link and have access to what is currently being run on the backend, in realtime. Using both logging and plain write messages, the output provides information on what function, script etc is running. There is one very large script, that runs a large number of other scripts to test and change data on a website. So my problem is I want to be able to have this one logfile accessible from the web and not have a huge amount of one line messages appearing ( within the various while loops), which just let the user know how long the script has been waiting. Kent, I will try your method and I hope this explains my objective a little better. Thanks Kieran On 6/21/06, Luke Paireepinart wrote: > > kieran flanagan wrote: > > Hi > > > > I have a question regarding writing text to a file. I am directing > > output to a logfile. During one of the loops, I have a command that > > will issue a message on how long it is waiting for by doing something > > like this > > > > while something: > > > > print "\rNow waiting %s seconds .. " % seconds, > > sys.stdout.flush() > > print "\r ", > > > > I am trying to change my scripts so all info can be accessed via > > logfiles. Is there any way I can direct the output to a logfile, as > > above, without creating a new line for each print statement. I have > > tried changing the sys.stdout to the logfile in question but the print > > commands just force a new line for each print statement. > I don't understand what the commas atthe end of your print commands are > for. > Nor do I understand what you're trying to do. > Are you trying to redirect stdout to a file? > why bother doing this? > why not just do > > from time import sleep > from random import randint > f = file("log.txt","a") > while x < y: > f.write("\nNow waiting %s seconds\n" % randint(0,4)) > f.close() > > Or do I misunderstand what your objective is? > Also, I believe \r is windows-only, and you should use \n all the time, > or \r\n. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060621/afc009b6/attachment.html From bgailer at alum.rpi.edu Wed Jun 21 17:58:53 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 21 Jun 2006 08:58:53 -0700 Subject: [Tutor] Writing over a line in a text file In-Reply-To: References: Message-ID: <44996CBD.8090902@alum.rpi.edu> kieran flanagan wrote: > Hi > > I have a question regarding writing text to a file. I am directing > output to a logfile. During one of the loops, I have a command that > will issue a message on how long it is waiting for by doing something > like this > > while something: > > print "\rNow waiting %s seconds .. " % seconds, > sys.stdout.flush() > print "\r ", > > I am trying to change my scripts so all info can be accessed via > logfiles. Is there any way I can direct the output to a logfile, as > above, without creating a new line for each print statement. I have > tried changing the sys.stdout to the logfile in question but the print > commands just force a new line for each print statement. Writing to any file appends characters. The \r does NOT back up. You might be able to use the tell() method of sys.stdout to determine the position just before the first print and the seek() method to reposition the file prior to each subsequent print. See "2.3.9 File Objects" in the Library Refernce. > > Any ideas would be welcome. > > Cheers > Kieran > > > -- > "Behind every great man, there is a great woman. Behind that woman is > Mr.T." > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From Senthil_OR at Dell.com Wed Jun 21 21:46:34 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Thu, 22 Jun 2006 01:16:34 +0530 Subject: [Tutor] Need python 2.4 rpm for Suse 9.1 In-Reply-To: <20060621120613.8579.qmail@web36511.mail.mud.yahoo.com> Message-ID: <187018842B504549BECE195E7EDCC587051D3A@blrx3m03.blr.amer.dell.com> try at rpmfind.net or google it. but the immediate thought which comes up in my mind is: "use the source, luke" -- Senthil ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Akanksha Govil Sent: Wednesday, June 21, 2006 5:36 PM To: tutor at python.org Subject: [Tutor] Need python 2.4 rpm for Suse 9.1 Hi, I searched the sites but was unable to find Python 2.4 rpm for Suse 9.1. Please send me a link where I can download this. Thanks Akanksha ________________________________ Yahoo! Sports Fantasy Football '06 - Go with the leader. Start your league today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060622/5c24da85/attachment-0001.html From kent37 at tds.net Thu Jun 22 03:15:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Jun 2006 21:15:10 -0400 Subject: [Tutor] critique my script! In-Reply-To: <20060621031154.5660.qmail@web51611.mail.yahoo.com> References: <20060621031154.5660.qmail@web51611.mail.yahoo.com> Message-ID: <4499EF1E.1060806@tds.net> Christopher Spears wrote: > I can apparently call the functions sometimes without > (). Why is that? There is an important difference between f and f() - f is a reference to the function object itself, while f() is a *call* of the function. (Call is actually an operator, written (). You can write your own callable objects!) Functions are "first-class objects" in Python. That means that functions are values. They can be assigned to names, passed to functions, stored in data structures, etc. This is very useful in many ways, and requires that there be a way to get the function value. For example, here is a simple function: In [1]: def f(): ...: print 'f here' ...: return 3 ...: Calling f has a side effect - it prints - and it also returns a value - 3. In [2]: f() f here Out[2]: 3 This calls the function and assigns the return value to the variable x. In [3]: x = f() f here In [4]: x Out[4]: 3 The bare name 'f' is a reference to a function object: In [5]: f Out[5]: This can also be assigned: In [6]: y = f Now the name 'y' is a reference to the same function: In [7]: y Out[7]: Calling y is the same as calling f because it refers to the same function. In [8]: y() f here Out[8]: 3 I hope that helps! In an earlier email you wrote, > One of my main areas of confusion > is that I have seemed similar scripts written without > 'self.button' or 'self.box'. The programmer simply > uses 'button' or 'box' instead. When you write self.button, you are storing the value as an attribute of the class instance the method was called on. This attribute will persist as long as the instance does (unless you delete it yourself) and can be used in other instance method. If you write just button, the value is stored in a local variable and will be discarded when the method exits. For example, here is a simple class: In [9]: class F(object): ...: def __init__(self, a, b): ...: self.x = a ...: y = b ...: def show(self): ...: print 'F.x =', self.x ...: ...: In [11]: f=F(1,2) The parameter passed as a is saved as f.x: In [12]: f.x Out[12]: 1 There is no f.y, the variable y only exists within the __init__() method: In [13]: f.y -------------------------------------------------- exceptions.AttributeError D:\ AttributeError: 'F' object has no attribute 'y' f.x is accessible in other methods: In [14]: f.show() F.x = 1 In the case of your original script, you don't refer to any of the variables outside __init__(), so there is no reason for them to be attributes, they can all be local variables. In general, if you don't need the value outside the method, just store it in a local variable. HTH, Kent From cspears2002 at yahoo.com Thu Jun 22 05:29:54 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 21 Jun 2006 20:29:54 -0700 (PDT) Subject: [Tutor] help with GUI Message-ID: <20060622032954.85832.qmail@web51607.mail.yahoo.com> I am trying to write a GUI that consists of a scrollbar and two buttons. One button is called Convert, and the other is called Quit. The vertical scrollbar represents degrees Fahrenheit starting from 212 at the top and ending at 32 at the bottom. I want to be able to pick degrees Fahrenheit with the the scrollbar. Then I would click Convert, and the script should print the conversion into degrees Celsius on the screen. My first problem is that the knob on the scrollbar doesn't move when I drag it. I would like my GUI to by wider as well. Finally, I need to figure out how to get the number selected from the scrollbar to the function that does the conversion. Here is what I have written so far: #!/usr/bin/python import pygtk pygtk.require('2.0') import gtk def convert_to_celsius(self,widget,data=None): degC = (degF - 32)/1.8 print "Degrees Celsius: .2%f" % degC def scale_set_default_values(scale): scale.set_update_policy(gtk.UPDATE_CONTINUOUS) scale.set_digits(1) scale.set_value_pos(gtk.POS_LEFT) scale.set_draw_value(True) class Conversion_GUI: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("Convert to Celsius") box1 = gtk.VBox(False, 0) self.window.add(box1) box2 = gtk.HBox(False, 10) box2.set_border_width(10) box1.pack_end(box2, True, True, 0) box3 = gtk.HBox(False, 10) box3.set_border_width(10) box1.pack_end(box3, True, True, 0) adj1 = gtk.Adjustment(32.0, 212.0, 32.0, 0.1, 1.0, 1.0) self.vscale = gtk.VScale(adj1) self.vscale.set_size_request(20, 300) scale_set_default_values(self.vscale) box1.pack_start(self.vscale, True, True, 0) quit_button = gtk.Button("Quit") quit_button.connect("clicked", lambda w:gtk.main_quit()) convert_button = gtk.Button("Convert") #convert_button.connect("clicked", convert_to_celsius) box3.pack_start(convert_button, True, True, 0) box2.pack_start(quit_button, True, True, 0) self.vscale.show() convert_button.show() quit_button.show() box3.show() box2.show() box1.show() self.window.show() def main(self): gtk.main() return 0 if __name__ == '__main__': convert = Conversion_GUI() convert.main() From kent37 at tds.net Thu Jun 22 12:28:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jun 2006 06:28:05 -0400 Subject: [Tutor] help with GUI In-Reply-To: <20060622032954.85832.qmail@web51607.mail.yahoo.com> References: <20060622032954.85832.qmail@web51607.mail.yahoo.com> Message-ID: <449A70B5.7010206@tds.net> Christopher Spears wrote: > My first problem is that the knob on the scrollbar > doesn't move when I drag it. I would like my GUI to > by wider as well. Finally, I need to figure out how > to get the number selected from the scrollbar to the > function that does the conversion. Just guessing from a quick look at the pygtk docs... Maybe you need to set_sensitive(True) on the VScale. Call VScale.get_value() to get the value. I'm not sure if there are any pyGTK experts on this list, if you don't get help here you might try the pyGTK list at http://www.daa.com.au/mailman/listinfo/pygtk Kent From andrew.arobert at gmail.com Thu Jun 22 13:36:13 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 22 Jun 2006 07:36:13 -0400 Subject: [Tutor] Question regarding commit/backout of a message using the pymqi module Message-ID: <449A80AD.2000508@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi everyone, Could someone help explain what I am doing wrong in this code block? This code block is an excerpt from a larger file that receives transmitted files via IBM WebSphere MQSeries an drops it to the local file system. Transmission of the file works as designed but it has a flaw. If the file cannot be created for whatever reason, the transmitted message is lost. What I am trying to do is ensure that a file transmit is considered successful only after the created file's checksum matches. If not, the code should treat it as an error and roll back the message to MQSeries without a commit. The basis for this should be around the pymqi.QueueManager class which is named mq in the block listed below. On execution, I get the traceback of: Traceback (most recent call last): File "M:\MQ\MQ\Scripts\receiver.py", line 269, in ? receiver.run() File "M:\MQ\MQ\Scripts\receiver.py", line 109, in run self.connect() File "M:\MQ\MQ\Scripts\receiver.py", line 118, in connect self.qm.begin() File "c:\python24\lib\site-packages\pymqi.py", line 738, in begin raise MQMIError(rv[0], rv[1]) pymqi.MQMIError: MQI Error. Comp: 1, Reason 2121: WARNING: MQRC_NO_EXTERNAL_PARTICIPANTS Do you have any idea why this might be occurring? class Receiver(object): def __init__(self,qm_name,queue_name): self.qm_name = qm_name self.queue_name = queue_name # Will be set later self.qm = None self.message = None def run(self): self.connect() self.get() def connect(self): """ Connect to queue manager """ try: self.qm = mq.QueueManager(options.qmanager.upper() ) self.qm.begin() except mq.PYIFError, err: mqevlog.event("error",err) sys.exit(1) def get(self): """ Get a message from queue. """ queue = mq.Queue(self.qm, self.queue_name) pmo = mq.pmo(Options = CMQC.MQPMO_SYNCPOINT) md = mq.md() while True: try: var = queue.get(self.message, md, pmo ) except mq.MQMIError,e: if e.reason != CMQC.MQRC_NO_MSG_AVAILABLE: mqevlog.event("error",e) sys.exit(1) break else: buff = StringIO(var) tree = ElementTree(file=buff) # Extract required elements and assign to local variables key = "this should be a well-kept secret" file_name = tree.find("dest").text creation_time = tree.find("creation_time").text contents = tree.find("contents").text check = tree.find("checksum").text #Decode temp file original = file_encoder.decode(contents) # Drop file to disk if os.path.exists(file_name) is False: open(file_name,"wb").write(original) else: mqevlog.event(sys.argv[0],"error","Output file path/name already exists") sys.exit(1) # Get checksum of newly created file sum=csums.getsum(file_name) # Compare checksum of created file with value transmitted if csums.checksum_compare(sys.argv[0],sum,check,file_name) == True: queue.commit() sys.exit(0) else: queue.backout() mqevlog.event("error","CheckSums of received/transmitted files do not match") sys.exit(1) Any help/insight you can provide on this would be greatly appreciated. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEmoCtDvn/4H0LjDwRAonCAKCAiWPpO1UcXWMKIP8xPzCtzP6eLACeMWFO qmHgdq/nI3gJ1v3jquDKnu8= =Ga33 -----END PGP SIGNATURE----- From visional_freeman at yahoo.com Thu Jun 22 14:57:45 2006 From: visional_freeman at yahoo.com (Ivan Low) Date: Thu, 22 Jun 2006 20:57:45 +0800 Subject: [Tutor] How to make the loop work? Message-ID: <449A93C9.1000908@yahoo.com> Hi, I'm new to python trying to figure how to make this work. c=0;d=raw_input("input number limit: ") while 1: c = c + 1 if c == d: break print c, My idea is to able to input a number to limit the print out of this loop. But this will not work. Where is the error? Ivan From pjlists at gmail.com Thu Jun 22 15:09:10 2006 From: pjlists at gmail.com (Peter Jessop) Date: Thu, 22 Jun 2006 15:09:10 +0200 Subject: [Tutor] How to make the loop work? In-Reply-To: <449A93C9.1000908@yahoo.com> References: <449A93C9.1000908@yahoo.com> Message-ID: <7a8d5a0c0606220609nf936cfcib1ceea99e0d5bc45@mail.gmail.com> It's basically correct but you need to convert the raw_input to integer. c=0 d=int(raw_input("input number limit: ")) while 1: c = c + 1 if c == d: break print c From null.scripter at gmail.com Thu Jun 22 15:45:16 2006 From: null.scripter at gmail.com (Null Mr.Freeman) Date: Thu, 22 Jun 2006 06:45:16 -0700 Subject: [Tutor] Python Word Unscrambler Message-ID: <1b9236700606220645qfbc9b9er104559ddb398e021@mail.gmail.com> Python Word Unscrambler: OK, this is the Python code I'm using to unscramble words but it unscrambles one word at a time, can someone please help me out and tell me how can I improve my code to make it decrypt several words at a time? P.S: Another thing is that it prints the solution 4 or 5 times don't know why. Sorry, I'm very new to Python. Please help if you can. Thanks a ton! ------------------------------------------------------------------------------------------------------------ CODE import string def anagrams(s): if s == "": return [s] else: ans = [] for an in anagrams(s[1:]): for pos in range(len(an)+1): ans.append(an[:pos]+s[0]+an[pos:]) return ans def dictionary(wordlist): dict = {} infile = open(wordlist, "r") for line in infile: word = line.split("\n")[0] dict[word] = 1 infile.close() return dict def main(): anagram = raw_input("Please enter a words you need to unscramble: ") anaLst = anagrams(anagram) diction = dictionary("wordlist.txt") for ana in anaLst: if diction.has_key(ana): print "The solution to the jumble is", ana main() ------------------------------------------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060622/5a1f4d92/attachment.html From bgailer at alum.rpi.edu Thu Jun 22 16:46:47 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 22 Jun 2006 07:46:47 -0700 Subject: [Tutor] How to make the loop work? In-Reply-To: <449A93C9.1000908@yahoo.com> References: <449A93C9.1000908@yahoo.com> Message-ID: <449AAD57.9090104@alum.rpi.edu> Ivan Low wrote: > Hi, I'm new to python trying to figure how to make this work. > > c=0;d=raw_input("input number limit: ") > > while 1: > c = c + 1 > if c == d: break > print c, > > > My idea is to able to input a number to limit the print out of this loop. > But this will not work. Where is the error? > "Will not work" does not (in general) give us enough to go on. Please in the future tell us what the evidence of the problem is - e.g. unexpected output, exception, ... If it is an exception please include the traceback in your post. -- Bob Gailer 510-978-4454 From doug.shawhan at gmail.com Thu Jun 22 17:06:04 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 22 Jun 2006 10:06:04 -0500 Subject: [Tutor] How to make the loop work? In-Reply-To: <449AAD57.9090104@alum.rpi.edu> References: <449A93C9.1000908@yahoo.com> <449AAD57.9090104@alum.rpi.edu> Message-ID: <5e1ceb8a0606220806o1d38de1bn3436f4f26f56485e@mail.gmail.com> Hi Bob, You can use a while loop in this case, but range() might be a bit more appropriate! c = 0 d = raw_input("Enter Number Limit: ") for i in range(int(d)): #note, we make sure "d" is an integer! c = c + 1 print c On 6/22/06, Bob Gailer wrote: > > Ivan Low wrote: > > Hi, I'm new to python trying to figure how to make this work. > > > > c=0;d=raw_input("input number limit: ") > > > > while 1: > > c = c + 1 > > if c == d: break > > print c, > > > > > > My idea is to able to input a number to limit the print out of this > loop. > > But this will not work. Where is the error? > > > "Will not work" does not (in general) give us enough to go on. Please in > the future tell us what the evidence of the problem is - e.g. unexpected > output, exception, ... If it is an exception please include the > traceback in your post. > > -- > Bob Gailer > 510-978-4454 > > _______________________________________________ > 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/20060622/22bc394f/attachment.html From emily.fortuna at nist.gov Thu Jun 22 19:22:54 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Thu, 22 Jun 2006 13:22:54 -0400 Subject: [Tutor] for loops over multiple lists of the same length Message-ID: <449AD1EE.5080305@nist.gov> I feel like there should be a better way to do this process: Can you please help? (This is trivial example code I created off the top of my head, but the same concept that I am trying to do elsewhere.) class Person(object): def __init__(self, first_name, age, fav_color): self.first_name = first_name self.age = age self.fav_color = fav_color first_names = ['emily', 'john', 'jeremy', 'juanita'] ages = [6, 34, 1, 19] colors = ['blue', 'orange', 'green', 'yellow'] ageIter = ages.iter() colorIter = colors.iter() people = [Person(name, ageIter.next(), colorIter.next()) for name in first_names] print people any suggestions, please? Emily From kent37 at tds.net Thu Jun 22 19:39:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jun 2006 13:39:04 -0400 Subject: [Tutor] for loops over multiple lists of the same length In-Reply-To: <449AD1EE.5080305@nist.gov> References: <449AD1EE.5080305@nist.gov> Message-ID: <449AD5B8.7060506@tds.net> Emily Fortuna wrote: > I feel like there should be a better way to do this process: > Can you please help? > (This is trivial example code I created off the top of my head, but the > same concept that I am trying to do elsewhere.) > > class Person(object): > def __init__(self, first_name, age, fav_color): > self.first_name = first_name > self.age = age > self.fav_color = fav_color > > first_names = ['emily', 'john', 'jeremy', 'juanita'] > ages = [6, 34, 1, 19] > colors = ['blue', 'orange', 'green', 'yellow'] > > ageIter = ages.iter() > colorIter = colors.iter() > people = [Person(name, ageIter.next(), colorIter.next()) for name in > first_names] > > print people > > any suggestions, please? The builtin function zip() does this: people = [Person(name, age, color) for name, age color in zip(first_names, ages, colors)] Kent From visional_freeman at yahoo.com Thu Jun 22 20:14:24 2006 From: visional_freeman at yahoo.com (Ivan Low) Date: Fri, 23 Jun 2006 02:14:24 +0800 Subject: [Tutor] How to make the loop work? In-Reply-To: <449AAD57.9090104@alum.rpi.edu> References: <449A93C9.1000908@yahoo.com> <449AAD57.9090104@alum.rpi.edu> Message-ID: <449ADE00.3010808@yahoo.com> Bob Gailer wrote: > Ivan Low wrote: >> Hi, I'm new to python trying to figure how to make this work. >> >> c=0;d=raw_input("input number limit: ") >> >> while 1: >> c = c + 1 >> if c == d: break >> print c, >> >> >> My idea is to able to input a number to limit the print out of this >> loop. >> But this will not work. Where is the error? >> > "Will not work" does not (in general) give us enough to go on. Please > in the future tell us what the evidence of the problem is - e.g. > unexpected output, exception, ... If it is an exception please include > the traceback in your post. > Hi, thanks for helping. After the reply from Peter by suggesting that I convert the raw_input to int, it works. Sorry that I didn't supply enough information in my post. However I'm curious about the result of my initial code after I enter a number which prompted by the raw_input it just keep printing numbers without break. Why is it acting like that? From singingxduck at gmail.com Thu Jun 22 20:12:56 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 22 Jun 2006 14:12:56 -0400 Subject: [Tutor] How to make the loop work? In-Reply-To: <449ADE00.3010808@yahoo.com> References: <449A93C9.1000908@yahoo.com> <449AAD57.9090104@alum.rpi.edu> <449ADE00.3010808@yahoo.com> Message-ID: <449ADDA8.1010104@gmail.com> Ivan Low wrote: >Bob Gailer wrote: > > >>Ivan Low wrote: >> >> >>>Hi, I'm new to python trying to figure how to make this work. >>> >>>c=0;d=raw_input("input number limit: ") >>> >>>while 1: >>> c = c + 1 >>> if c == d: break >>> print c, >>> >>> >>>My idea is to able to input a number to limit the print out of this >>>loop. >>>But this will not work. Where is the error? >>> >>> >>> >>"Will not work" does not (in general) give us enough to go on. Please >>in the future tell us what the evidence of the problem is - e.g. >>unexpected output, exception, ... If it is an exception please include >>the traceback in your post. >> >> >> >Hi, thanks for helping. >After the reply from Peter by suggesting that I convert the raw_input to >int, it works. >Sorry that I didn't supply enough information in my post. >However I'm curious about the result of my initial code after I enter a >number which >prompted by the raw_input it just keep printing numbers without break. >Why is it acting like that? > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Well, since you didn't convert d to an integer, and a string can never equal an integer, c never equals d, and therefore you get an infinite loop, which continues to print c. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Thu Jun 22 20:14:01 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 22 Jun 2006 14:14:01 -0400 Subject: [Tutor] [Fwd: Re: for loops over multiple lists of the same length] Message-ID: <449ADDE9.1020507@gmail.com> Oops, forgot to reply to the list; sorry everyone. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An embedded message was scrubbed... From: Orri Ganel Subject: Re: [Tutor] for loops over multiple lists of the same length Date: Thu, 22 Jun 2006 14:10:57 -0400 Size: 3058 Url: http://mail.python.org/pipermail/tutor/attachments/20060622/dcafa16b/attachment.mht From David.Heiser at intelliden.com Thu Jun 22 20:28:00 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Thu, 22 Jun 2006 12:28:00 -0600 Subject: [Tutor] Escape sequences Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BD18@COSIUM03.intelliden.net> I have code that assigns escape sequences to variables like "self.resetString = '\03'". As long as they are hard coded in, everything works fine. But I want to read the variable from a text/config file so my users can override the defaults. In the file are a list of "parameter = value" pairs like "resetString = \03". As the file is parsed, each pair is stored in a dictionary; "parmeterDictionary[parameter] = value". Then in the code, the value is assigned to the variable with a statement like "self.resetString = parmeterDictionary['resetString']". Simple ASCII strings work fine, but the escape sequences don't work and the code fails. "print self.resetString" returns "\\03", instead of a nonprintable character. Any ideas? David Heiser From kent37 at tds.net Thu Jun 22 21:02:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jun 2006 15:02:57 -0400 Subject: [Tutor] Escape sequences In-Reply-To: <3CABD13EA1D5D347A1B75014BD54CFD502B0BD18@COSIUM03.intelliden.net> References: <3CABD13EA1D5D347A1B75014BD54CFD502B0BD18@COSIUM03.intelliden.net> Message-ID: <449AE961.1080306@tds.net> David Heiser wrote: > I have code that assigns escape sequences to variables like > "self.resetString = '\03'". As long as they are hard coded in, > everything works fine. > > But I want to read the variable from a text/config file so my users can > override the defaults. In the file are a list of "parameter = value" > pairs like "resetString = \03". As the file is parsed, each pair is > stored in a dictionary; "parmeterDictionary[parameter] = value". > > Then in the code, the value is assigned to the variable with a statement > like "self.resetString = parmeterDictionary['resetString']". > > Simple ASCII strings work fine, but the escape sequences don't work and > the code fails. "print self.resetString" returns "\\03", instead of a > nonprintable character. Use the 'string_escape' codec to decode the escaped strings: In [1]: s= '\\03' In [2]: s Out[2]: '\\03' In [3]: len(s) Out[3]: 3 In [4]: s.decode('string_escape') Out[4]: '\x03' In [5]: len(_) Out[5]: 1 Kent From shantanoo at gmail.com Thu Jun 22 20:56:22 2006 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Fri, 23 Jun 2006 00:26:22 +0530 Subject: [Tutor] for loops over multiple lists of the same length In-Reply-To: <449AD1EE.5080305@nist.gov> References: <449AD1EE.5080305@nist.gov> Message-ID: <20060622185622.GA2628@madhosh.dhoomketu.net.in> +++ Emily Fortuna [22-06-06 13:22 -0400]: | I feel like there should be a better way to do this process: | Can you please help? | (This is trivial example code I created off the top of my head, but the | same concept that I am trying to do elsewhere.) | | class Person(object): | def __init__(self, first_name, age, fav_color): | self.first_name = first_name | self.age = age | self.fav_color = fav_color | | first_names = ['emily', 'john', 'jeremy', 'juanita'] | ages = [6, 34, 1, 19] | colors = ['blue', 'orange', 'green', 'yellow'] | | ageIter = ages.iter() | colorIter = colors.iter() | people = [Person(name, ageIter.next(), colorIter.next()) for name in | first_names] | | print people | | any suggestions, please? | Emily data = [['emily',6,'blue'],['jhon',34,'orange'],['jeremy',1,'green'],['junita',19,'yellow']] people = [Person(name,age,color) for name,age,color in data] Regards, Shantanoo -- Eliminate guilt. Don't fiddle expenses, taxes or benefits, and don't cheat colleagues. From bgailer at alum.rpi.edu Thu Jun 22 21:51:06 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 22 Jun 2006 12:51:06 -0700 Subject: [Tutor] How to make the loop work? In-Reply-To: <449ADE00.3010808@yahoo.com> References: <449A93C9.1000908@yahoo.com> <449AAD57.9090104@alum.rpi.edu> <449ADE00.3010808@yahoo.com> Message-ID: <449AF4AA.5030104@alum.rpi.edu> Ivan Low wrote: > Bob Gailer wrote: > >> Ivan Low wrote: >> >>> Hi, I'm new to python trying to figure how to make this work. >>> >>> c=0;d=raw_input("input number limit: ") >>> >>> while 1: >>> c = c + 1 >>> if c == d: break >>> print c, >>> >>> >>> My idea is to able to input a number to limit the print out of this >>> loop. >>> But this will not work. Where is the error? >>> >>> >> "Will not work" does not (in general) give us enough to go on. Please >> in the future tell us what the evidence of the problem is - e.g. >> unexpected output, exception, ... If it is an exception please include >> the traceback in your post. >> >> > Hi, thanks for helping. > After the reply from Peter by suggesting that I convert the raw_input to > int, it works. > Sorry that I didn't supply enough information in my post. > However I'm curious about the result of my initial code after I enter a > number which > prompted by the raw_input it just keep printing numbers without break. > Why is it acting like that? > Python will compare any two objects. If their types are not compatible for comparison the result is False. Your program was comparing a character string to a numeric. Their types are not "compatible". Hence always False. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From David.Heiser at intelliden.com Thu Jun 22 22:29:33 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Thu, 22 Jun 2006 14:29:33 -0600 Subject: [Tutor] Escape sequences Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BD19@COSIUM03.intelliden.net> That worked just dandy. Thanks. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, June 22, 2006 1:03 PM Cc: tutor at python.org Subject: Re: [Tutor] Escape sequences David Heiser wrote: > I have code that assigns escape sequences to variables like > "self.resetString = '\03'". As long as they are hard coded in, > everything works fine. > > But I want to read the variable from a text/config file so my users > can override the defaults. In the file are a list of "parameter = > value" pairs like "resetString = \03". As the file is parsed, each > pair is stored in a dictionary; "parmeterDictionary[parameter] = > value". > > Then in the code, the value is assigned to the variable with a > statement like "self.resetString = parmeterDictionary['resetString']". > > Simple ASCII strings work fine, but the escape sequences don't work > and the code fails. "print self.resetString" returns "\\03", instead > of a nonprintable character. Use the 'string_escape' codec to decode the escaped strings: In [1]: s= '\\03' In [2]: s Out[2]: '\\03' In [3]: len(s) Out[3]: 3 In [4]: s.decode('string_escape') Out[4]: '\x03' In [5]: len(_) Out[5]: 1 Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dkuhlman at rexx.com Thu Jun 22 22:47:38 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 22 Jun 2006 13:47:38 -0700 Subject: [Tutor] A few more notes on Python interfaces Message-ID: <20060622204738.GA84998@cutter.rexx.com> Several weeks ago, there was a discussion on this list about the use of interfaces in Python. That motivated me to write up some notes on Python interfaces, in part to force myself to learn a bit more about it. Needless to say, my notes benefited much from the comments on this list. You can find these notes here: http://www.rexx.com/~dkuhlman/python_comments.html#interfaces I'll welcome any comments. And, thanks for the interesting and helpful discussion on interfaces, and other topics, on this list. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From falcon3166 at hotmail.com Fri Jun 23 03:20:32 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 22 Jun 2006 19:20:32 -0600 Subject: [Tutor] Is this correct syntax for what I want? Message-ID: I want to be able to add and subtract from a number in a tuple in a list. Is this the correct syntax? letterlist[x] = letterlist[x] + amount # for addition letterlist[x] = letterlist[x] - amount # for subtraction If this is not correct, what is the correct syntax? Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060622/5499aa56/attachment.htm From justin.mailinglists at gmail.com Fri Jun 23 03:59:35 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 23 Jun 2006 09:59:35 +0800 Subject: [Tutor] MySQLdb: cant get '... where field in %s' to work for string sequences Message-ID: <3c6718980606221859n72f65f48n75693bafab868a44@mail.gmail.com> how can I get 'select ... from ... where field in %s' to work for sequences of strings? sequences of integers works just fine import MySQLdb DBCRED = {'host': 'localhost', 'user': 'userjustin', 'passwd': 'passwdjustin', 'db': 'dbjustin'} ARTICLES = ('XXX99999', 'ABZ00002') PIDS = (29379, 29380) FIXEDARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite WHERE articleName IN ('XXX99999', 'ABZ00002')""" TESTARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite WHERE articleName IN %r""" % (ARTICLES,) SQLARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite WHERE articleName IN %s""" FIXEDPID = """SELECT * FROM tblForTransfer2Prodsite WHERE pid IN (29379, 29380)""" TESTPID = """SELECT * FROM tblForTransfer2Prodsite WHERE pid IN %r""" % (PIDS,) SQLPID = """SELECT * FROM tblForTransfer2Prodsite WHERE pid IN %s""" if __name__ == '__main__': conn = MySQLdb.connect(**DBCRED) try: cur = conn.cursor() print FIXEDARTICLENAME print TESTARTICLENAME print cur.execute(FIXEDARTICLENAME), print cur.execute(TESTARTICLENAME), # cannot get this to work print cur.execute(SQLARTICLENAME, (ARTICLES,)) print print FIXEDPID print TESTPID print cur.execute(FIXEDPID), print cur.execute(TESTPID), # but this does print cur.execute(SQLPID, (PIDS,)) print finally: conn.close() From andre.roberge at gmail.com Fri Jun 23 04:44:21 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 22 Jun 2006 23:44:21 -0300 Subject: [Tutor] [ANN] RUR-PLE version 0.9.9 Message-ID: <7528bcdd0606221944t42c36ff9md4db743bba6b9909@mail.gmail.com> Roberge's Used Robot: a Python Learning Environment Version 0.9.9 of RUR-PLE has been released. It can be found at: https://sourceforge.net/project/showfiles.php?group_id=125834 RUR-PLE should work properly on all major platforms (Mac, Linux and Windows) in 3 different languages (English, French, Spanish). Feedback would be appreciated to confirm this prior to release of version 1.0. -------------------------------------- Learning to program computer should be fun, for adults and children alike. RUR-PLE is an environment designed to help you learn computer programming using Python. RUR-PLE is a wxPython-based app. RUR-PLE contains four main elements: 1. Lessons viewable within an incorporated browser. Version 0.9.9 includes over 40 lessons introducing Python. A few more will be written for the 1.0 release. 2. A "robot world" with a robot that can accomplish tasks through Python programs. 3. A built-in interpreter which can be used to play with Python. 4. A built-in file editor which can be used for futher Python explorations. This version includes a triilingual (English, French and Spanish) interface. Translations to other languages are welcome. Only English lessons are included. Andr? From carroll at tjc.com Fri Jun 23 06:38:27 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 22 Jun 2006 21:38:27 -0700 (PDT) Subject: [Tutor] Is this correct syntax for what I want? In-Reply-To: Message-ID: On Thu, 22 Jun 2006, Nathan Pinno wrote: > I want to be able to add and subtract from a number in a tuple in a > list. Is this the correct syntax? > > letterlist[x] = letterlist[x] + amount # for addition > > letterlist[x] = letterlist[x] - amount # for subtraction Try it. From devayani.barve at gmail.com Fri Jun 23 07:07:52 2006 From: devayani.barve at gmail.com (devayani barve) Date: Fri, 23 Jun 2006 10:37:52 +0530 Subject: [Tutor] what does the warning indicate? Message-ID: <301929340606222207q70d8186q260c34dd2cd59f3f@mail.gmail.com> Hi!! I'm new to python and just trying to play around, when I run my program in the interactive shell before executing the program it shows the following warning : Warning: HOME environment variable points to H: but the path does not exist. ================================ RESTART ================================ >>> or sometimes it just gets stuck. What does this mean? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060623/0490a5a0/attachment.html From clsdaniel at gmail.com Fri Jun 23 08:12:29 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Thu, 22 Jun 2006 23:12:29 -0700 Subject: [Tutor] what does the warning indicate? In-Reply-To: <301929340606222207q70d8186q260c34dd2cd59f3f@mail.gmail.com> References: <301929340606222207q70d8186q260c34dd2cd59f3f@mail.gmail.com> Message-ID: <4fae7dfa0606222312w2bfab622l6cf8bca8ce9cb79f@mail.gmail.com> Most probably you are using Python on Windows, on Unix-like system there is a "home" for each user where the user files reside, normally HOME on windows must point to something like c:\Documents and Settings\Username, are you using Python on Windows 98? Otherwise it may be a problem with the enviroment variable (Home), pointing to drive H (H:), while it dosen't exist in your system. Anyways, that's my 2 cents :) On 6/22/06, devayani barve wrote: > > Hi!! > I'm new to python and just trying to play around, > when I run my program in the interactive shell before executing the program > it shows the following warning : > > Warning: HOME environment variable points to > H: > but the path does not exist. > ================================ RESTART > ================================ > >>> > > or sometimes it just gets stuck. > What does this mean? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From clsdaniel at gmail.com Fri Jun 23 10:43:28 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Fri, 23 Jun 2006 01:43:28 -0700 Subject: [Tutor] what does the warning indicate? In-Reply-To: <301929340606222207q70d8186q260c34dd2cd59f3f@mail.gmail.com> References: <301929340606222207q70d8186q260c34dd2cd59f3f@mail.gmail.com> Message-ID: <4fae7dfa0606230143v6a2f34b9jd6d4dd5c23adb07@mail.gmail.com> By the way, when do you get this warning? while starting the python interpreter (python.exe)?, it's IDLE which gives you that warning? or could it be some code? if it is code then send it to the list, i'm sure will be able to help you more that way :) Regards, Carlos Daniel Ruvalcaba From murtog at gmail.com Fri Jun 23 12:21:20 2006 From: murtog at gmail.com (murtog_) Date: Fri, 23 Jun 2006 07:21:20 -0300 Subject: [Tutor] Is this correct syntax for what I want? In-Reply-To: References: Message-ID: You can do: letterlist[x] += amount letterlist[x] -= amount Cheers, -- murtog_ [ http://murtog.blogspot.com ] From kent37 at tds.net Fri Jun 23 12:34:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jun 2006 06:34:50 -0400 Subject: [Tutor] Python Word Unscrambler In-Reply-To: <1b9236700606220645qfbc9b9er104559ddb398e021@mail.gmail.com> References: <1b9236700606220645qfbc9b9er104559ddb398e021@mail.gmail.com> Message-ID: <449BC3CA.2020107@tds.net> Null Mr.Freeman wrote: > Python Word Unscrambler: > > OK, this is the Python code I'm using to unscramble words but it > unscrambles one word at a time, can someone please help me out and tell > me how can I improve my code to make it decrypt several words at a time? > P.S: Another thing is that it prints the solution 4 or 5 times don't > know why. One way to make it work with multiple words would be to put the call to main() in a loop. (You might want to rename main() to something like unscramble()). Each time through the loop you will be asked for a word to unscramble. I'm not sure why you get the same solution multiple times. If the scrambled word has repeated letters that will cause repeated answers because you generate all permutations of the letters. One solution would be to make a set out of the anagrams of the original word, that will remove any duplicates. You could also use a set instead of a dict to store the word list. And don't use dict as the name of a variable, it shadows the name of the built-in dict object. Another approach to solving anagrams is to sort the letters in the scrambled word. When you read the dictionary, sort the letters in each dictionary word and build a dict that maps sorted words to a list of all the words that sort that way. Then you can solve an anagram with a single lookup in the dict of sorted words. HTH, Kent > > Sorry, I'm very new to Python. > Please help if you can. > Thanks a ton! > ------------------------------------------------------------------------------------------------------------ > > CODE > > import string > > def anagrams(s): > if s == "": > return [s] > else: > ans = [] > for an in anagrams(s[1:]): > for pos in range(len(an)+1): > ans.append(an[:pos]+s[0]+an[pos:]) > return ans > > def dictionary(wordlist): > dict = {} > infile = open(wordlist, "r") > for line in infile: > word = line.split("\n")[0] > dict[word] = 1 > infile.close() > return dict > > def main(): > anagram = raw_input("Please enter a words you need to unscramble: ") > anaLst = anagrams(anagram) > diction = dictionary("wordlist.txt") > for ana in anaLst: > if diction.has_key(ana): > print "The solution to the jumble is", ana > > main() > > ------------------------------------------------------------------------------------------------------------ > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From shortpath at gmail.com Fri Jun 23 17:48:32 2006 From: shortpath at gmail.com (Matt Richardson) Date: Fri, 23 Jun 2006 08:48:32 -0700 Subject: [Tutor] MySQLdb: cant get '... where field in %s' to work for string sequences In-Reply-To: <3c6718980606221859n72f65f48n75693bafab868a44@mail.gmail.com> References: <3c6718980606221859n72f65f48n75693bafab868a44@mail.gmail.com> Message-ID: <4621e3520606230848m65848c68w537cfadb7ba88aa0@mail.gmail.com> On 6/22/06, Justin Ezequiel wrote: > how can I get 'select ... from ... where field in %s' to work for > sequences of strings? > sequences of integers works just fine > > import MySQLdb > > DBCRED = {'host': 'localhost', 'user': 'userjustin', > 'passwd': 'passwdjustin', 'db': 'dbjustin'} > > ARTICLES = ('XXX99999', 'ABZ00002') > PIDS = (29379, 29380) > > FIXEDARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN ('XXX99999', 'ABZ00002')""" > TESTARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN %r""" % (ARTICLES,) > SQLARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN %s""" > > FIXEDPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN (29379, 29380)""" > TESTPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN %r""" % (PIDS,) > SQLPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN %s""" > > if __name__ == '__main__': > conn = MySQLdb.connect(**DBCRED) > try: > cur = conn.cursor() > print FIXEDARTICLENAME > print TESTARTICLENAME > print cur.execute(FIXEDARTICLENAME), > print cur.execute(TESTARTICLENAME), > # cannot get this to work > print cur.execute(SQLARTICLENAME, (ARTICLES,)) > print > print FIXEDPID > print TESTPID > print cur.execute(FIXEDPID), > print cur.execute(TESTPID), > # but this does > print cur.execute(SQLPID, (PIDS,)) > print > finally: conn.close() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Can you post your error messages? -- Matt From falcon3166 at hotmail.com Fri Jun 23 20:23:19 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 23 Jun 2006 12:23:19 -0600 Subject: [Tutor] Needing help with my account tracker program. Message-ID: Hey all, I was wondering if you could help me fix a glitch in my program that's preventing it from running. Here's the code: accountlist = [] def load_file(ac): import os filename = 'accounts.txt' if os.path.exists(filename): store = open(filename, 'r') for line in store: account = line.strip() amount = line.next().strip() ac[account] = amount else: store = open(filename, 'w') #create a new file store.close def save_file(ac): store = open('accounts.txt', 'w') for account, amount in accountlist.items(): store.write(account + '\n') store.write(amount + '\n') store.close() def main_menu(): print "1) Add a new account" print "2) Remove a account" print "3) Print all info" print "4) Find account" print "5) Deposit" print "6) Withdraw funds" print "9) Save and exit." def add(): print "Add a new account" account = raw_input("Account Name: ") amount = float(raw_input("Amount: ")) accountlist[account] = amount def remove(): print "Remove a account" account = raw_input("Account: ") if accountlist.has_key(account): del accountlist[account] else: print account," was not found." def printall(): print "Account Info" for account in accountlist.keys(): print account,"\t $",accountlist[account]+"\n" def lookup(): print "Specific Account Info" account = raw_input("Account: ") if accountlist.has_key(account): print account," $",accountlist[account] else: print account," was not found." def deposit(): print "Deposit funds" account = raw_input("Account: ") if accountlist.has_key(account): amount = float(raw_input("Amount: ")) accountlist[account] += amount print account,"\t $",accountlist[account] else: print account," was not found." def withdraw(): print "Withdraw Funds." account = raw_input("Account: ") if accountlist.has_key(account): amount = float(raw_input("Amount: ")) accountlist[account] -= amount print account,"\t $",accountlist[account] else: print account," was not found." print "Account Tracker" print "By Nathan Pinno" print load_file(accountlist) while 1: main_menu() menu_choice = int(raw_input("Which item? ")) if menu_choice == 1: add() elif menu_choice == 2: remove() elif menu_choice == 3: printall() elif menu_choice == 4: lookup() elif menu_choice == 5: deposit() elif menu_choice == 6: withdraw() elif menu_choice == 9: break else: print "That's not an option. Please choose a valid option." save_file(accountlist) print "Have a nice day!" Here is the error I'm having troubles solving: Traceback (most recent call last): File "C:\Python24\Account Tracker.py", line 87, in -toplevel- add() File "C:\Python24\Account Tracker.py", line 36, in add accountlist[account] = amount TypeError: list indices must be integers So. how do I solve it to make it work the way I want it to? Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060623/8ef0e9fa/attachment.html From bgailer at alum.rpi.edu Fri Jun 23 21:10:31 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 23 Jun 2006 12:10:31 -0700 Subject: [Tutor] Needing help with my account tracker program. In-Reply-To: References: Message-ID: <449C3CA7.4030209@alum.rpi.edu> Nathan Pinno wrote: > Hey all, > > I was wondering if you could help me fix a glitch in my program that's > preventing it from running. > > Here's the code: > accountlist = [] accountlist = {} # dictionary rather than list > > def load_file(ac): > import os > filename = 'accounts.txt' > if os.path.exists(filename): > store = open(filename, 'r') > for line in store: > account = line.strip() > amount = line.next().strip() > ac[account] = amount > else: > store = open(filename, 'w') #create a new file > store.close > > def save_file(ac): > store = open('accounts.txt', 'w') > for account, amount in accountlist.items(): > store.write(account + '\n') > store.write(amount + '\n') > store.close() > > def main_menu(): > print "1) Add a new account" > print "2) Remove a account" > print "3) Print all info" > print "4) Find account" > print "5) Deposit" > print "6) Withdraw funds" > print "9) Save and exit." > > def add(): > print "Add a new account" > account = raw_input("Account Name: ") > amount = float(raw_input("Amount: ")) > accountlist[account] = amount > > def remove(): > print "Remove a account" > account = raw_input("Account: ") > if accountlist.has_key(account): > del accountlist[account] > else: > print account," was not found." > > def printall(): > print "Account Info" > for account in accountlist.keys(): > print account,"\t $",accountlist[account]+"\n" > > def lookup(): > print "Specific Account Info" > account = raw_input("Account: ") > if accountlist.has_key(account): > print account," $",accountlist[account] > else: > print account," was not found." > > def deposit(): > print "Deposit funds" > account = raw_input("Account: ") > if accountlist.has_key(account): > amount = float(raw_input("Amount: ")) > accountlist[account] += amount > print account,"\t $",accountlist[account] > else: > print account," was not found." > > def withdraw(): > print "Withdraw Funds." > account = raw_input("Account: ") > if accountlist.has_key(account): > amount = float(raw_input("Amount: ")) > accountlist[account] -= amount > print account,"\t $",accountlist[account] > else: > print account," was not found." > > print "Account Tracker" > print "By Nathan Pinno" > print > load_file(accountlist) > while 1: > main_menu() > menu_choice = int(raw_input("Which item? ")) > if menu_choice == 1: > add() > elif menu_choice == 2: > remove() > elif menu_choice == 3: > printall() > elif menu_choice == 4: > lookup() > elif menu_choice == 5: > deposit() > elif menu_choice == 6: > withdraw() > elif menu_choice == 9: > break > else: > print "That's not an option. Please choose a valid option." > save_file(accountlist) > print "Have a nice day!" > Here is the error I'm having troubles solving: > Traceback (most recent call last): > File "C:\Python24\Account Tracker.py", line 87, in -toplevel- > add() > File "C:\Python24\Account Tracker.py", line 36, in add > accountlist[account] = amount > TypeError: list indices must be integers > > So. how do I solve it to make it work the way I want it to? > > Thanks, > Nathan Pinno > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From alan.gauld at freenet.co.uk Fri Jun 23 22:42:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 23 Jun 2006 21:42:54 +0100 Subject: [Tutor] A few more notes on Python interfaces References: <20060622204738.GA84998@cutter.rexx.com> Message-ID: <004101c69705$9a82c590$0301a8c0@XPpro> > more about it. Needless to say, my notes benefited much from the > comments on this list. You can find these notes here: > > http://www.rexx.com/~dkuhlman/python_comments.html#interfaces > > I'll welcome any comments. Nice work. One wee point is that the term prorocol is an OOP community term rather than a Python community. Interfaces are a way to enforce protocols in certain languages (usually but not always statically typed, eg both Java(statically typed) and Visual Basic (dynamically typed - sort of) both support interfaces). The term protocol has been widely used in OOP since the 1970's and is commonly found in the literature of Smalltallk, Lisp and Objective C. The latter has language constructs that explicitly support protocols, as well as interfaces. (This leads to some subtle capabilities of ObjectiveC which are mainly of interest to academics! :-) Regards, Alan G. From alan.gauld at freenet.co.uk Fri Jun 23 22:48:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 23 Jun 2006 21:48:38 +0100 Subject: [Tutor] Is this correct syntax for what I want? References: Message-ID: <004d01c69706$67bc9d10$0301a8c0@XPpro> Nathan, Can you show us an example of the data? And what you want to do to it, ie before and after values. Its not clear to me whether you want to add the number to the number while keeping it in the tuple (Which is impossible because tuples are immutable) or whether you simply want to access the data to use in an addition/subrtraction storing the result elsewhere (which is perfectly possible) Alan G. ----- Original Message ----- From: "Nathan Pinno" To: Sent: Friday, June 23, 2006 2:20 AM Subject: [Tutor] Is this correct syntax for what I want? I want to be able to add and subtract from a number in a tuple in a list. Is this the correct syntax? letterlist[x] = letterlist[x] + amount # for addition letterlist[x] = letterlist[x] - amount # for subtraction If this is not correct, what is the correct syntax? Thanks, Nathan Pinno From lantal at tmail.com Fri Jun 23 22:59:06 2006 From: lantal at tmail.com (Laszlo Antal) Date: Fri, 23 Jun 2006 13:59:06 -0700 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: References: Message-ID: <1151096384.2025A810@fb6.dngr.org> Hi, This is how my directory looks myprogram (this is the main folder for my program) | myprogram.py mymodules (this is where I store my modules) | mymodule1.py mymodule2.py I would like to import from mymodules folder my modules1.py, mymodules2.py into myprogram.py. How can I add mymodules folder to pythonpath from myprogram.py.? So if I copy myprogram folder into an other pc than myprogram.py can take care of adding mymodules folder to pythonpath. Thank you in advance Laszlo Antal From falcon3166 at hotmail.com Fri Jun 23 22:59:54 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 23 Jun 2006 14:59:54 -0600 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> Message-ID: The data is account name and 12.50 (example). I want to access the data to add and subtract from it. For example 12.50 - 2.25 = 10.25 10.25 + 4.75 = 15.00 Thanks, Nathan Pinno ----- Original Message ----- From: "Alan Gauld" To: "Nathan Pinno" ; Sent: Friday, June 23, 2006 2:48 PM Subject: Re: [Tutor] Is this correct syntax for what I want? > Nathan, > > Can you show us an example of the data? > And what you want to do to it, ie before and after values. > > Its not clear to me whether you want to add the number to the > number while keeping it in the tuple (Which is impossible > because tuples are immutable) or whether you simply want > to access the data to use in an addition/subrtraction storing > the result elsewhere (which is perfectly possible) > > Alan G. > > ----- Original Message ----- > From: "Nathan Pinno" > To: > Sent: Friday, June 23, 2006 2:20 AM > Subject: [Tutor] Is this correct syntax for what I want? > > > I want to be able to add and subtract from a number in a tuple in a > list. Is this the correct syntax? > > letterlist[x] = letterlist[x] + amount # for addition > > letterlist[x] = letterlist[x] - amount # for subtraction > > If this is not correct, what is the correct syntax? > > Thanks, > Nathan Pinno > > > From alan.gauld at freenet.co.uk Fri Jun 23 23:05:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 23 Jun 2006 22:05:19 +0100 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> Message-ID: <001501c69708$bc3face0$0301a8c0@XPpro> > The data is account name and 12.50 (example). > I want to access the data to add and subtract from it. > For example > 12.50 - 2.25 = 10.25 > 10.25 + 4.75 = 15.00 Sorry, I meant the data structures. You mentioned you had a list of tuples? And you wanted to perform addition./subtraction on members of the tuples. Therefore I assume you have something like: mydata = [(1,2),(3,4)] and you want to add 7 to, say, 4. But do you want the end result to be an updated mydata: mydata = [(1,2),(3,11)] Or do you only want to store the resuilt of the addition somewhere, like this: myvar = mydata[1][1] + 7 which leaves mydata unchanged. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From emily.fortuna at nist.gov Fri Jun 23 23:11:33 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Fri, 23 Jun 2006 17:11:33 -0400 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: <1151096384.2025A810@fb6.dngr.org> References: <1151096384.2025A810@fb6.dngr.org> Message-ID: <449C5905.70308@nist.gov> If I understand what you're asking (forgive me if I misunderstood), you need to create a file in the mymodules directory and call it __init__.py (even if you don't put anything in this file). This tells Python that it is a package containing modules. Then, in your program myprogram.py, you can say import mymodule1 mymodule1.function_name('foo') Then it shouldn't matter what computer you are on; the script should run. HTH, emily Laszlo Antal wrote: > Hi, > > This is how my directory looks > myprogram (this is the main folder for my program) > | > myprogram.py > mymodules (this is where I store my modules) > | > mymodule1.py > mymodule2.py > > I would like to import from mymodules folder my modules1.py, > mymodules2.py into myprogram.py. > > How can I add mymodules folder to pythonpath > from myprogram.py.? > So if I copy myprogram folder into an other pc than myprogram.py can > take care of adding mymodules folder to pythonpath. > > Thank you in advance > Laszlo Antal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From lantal at tmail.com Fri Jun 23 23:25:56 2006 From: lantal at tmail.com (Laszlo Antal) Date: Fri, 23 Jun 2006 14:25:56 -0700 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: <449C5905.70308@nist.gov> References: <1151096384.2025A810@fb6.dngr.org> <449C5905.70308@nist.gov> Message-ID: <1151097956.1C825F61@fb5.dngr.org> On 06/23/06 at 2:11 PM you wrote: > If I understand what you're asking (forgive me if I misunderstood), > you need to create a file in the mymodules directory and call it > __init__.py (even if you don't put anything in this file). This tells > Python that it is a package containing modules. Then, in your program > myprogram.py, you can say import mymodule1 > mymodule1.function_name('foo') > Then it shouldn't matter what computer you are on; the script should > run. > HTH, > emily > > > > Laszlo Antal wrote: > >Hi, > >This is how my directory looks > >myprogram (this is the main folder for my program) > >| > > myprogram.py > > mymodules (this is where I store my modules) > > | > > mymodule1.py > > mymodule2.py > >I would like to import from mymodules folder my modules1.py, > >mymodules2.py into myprogram.py. > >How can I add mymodules folder to pythonpath > >from myprogram.py.? > >So if I copy myprogram folder into an other pc than > >myprogram.py can take care of adding mymodules folder to > >pythonpath. > >Thank you in advance > >Laszlo Antal > >_ I tried your suggestion. I created a file inside mymodules folder called __init__.py. when i run myprogram.py i still get the same error. Traceback (most recent call last): File "/home/laszlo/myprogram/myprogram.py", line 7, in ? import mymodule1 ImportError: No module named mymodule1# What am I doing wrong? > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor Laszlo Antal From andrew.arobert at gmail.com Fri Jun 23 23:39:38 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Fri, 23 Jun 2006 17:39:38 -0400 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: <449C5905.70308@nist.gov> References: <1151096384.2025A810@fb6.dngr.org> <449C5905.70308@nist.gov> Message-ID: <449C5F9A.8040401@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 What you need to do is append your existing path. for example: import sys sys.path.append(r'd:\python_modules') You can then import any modules that reside in that path as if they where part of the standard library. Andy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEnF+aDvn/4H0LjDwRAl14AKDEfZc0TKEbfhtF+/4h7o56MnCeSACdG6y8 DwLC/UAbZMBHNCQDS/2A5jY= =HmM2 -----END PGP SIGNATURE----- From kent37 at tds.net Fri Jun 23 23:40:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jun 2006 17:40:54 -0400 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: <449C5905.70308@nist.gov> References: <1151096384.2025A810@fb6.dngr.org> <449C5905.70308@nist.gov> Message-ID: <449C5FE6.70206@tds.net> Emily Fortuna wrote: > If I understand what you're asking (forgive me if I misunderstood), you > need to create a file in the mymodules directory and call it __init__.py > (even if you don't put anything in this file). This tells Python that > it is a package containing modules. Then, in your program myprogram.py, > you can say import mymodule1 > mymodule1.function_name('foo') > Then it shouldn't matter what computer you are on; the script should run. That is close but not quite right. The correct import will be from mymodules import mymodule1 Kent > > > > Laszlo Antal wrote: >> Hi, >> >> This is how my directory looks >> myprogram (this is the main folder for my program) >> | >> myprogram.py >> mymodules (this is where I store my modules) >> | >> mymodule1.py >> mymodule2.py >> >> I would like to import from mymodules folder my modules1.py, >> mymodules2.py into myprogram.py. >> >> How can I add mymodules folder to pythonpath >> from myprogram.py.? >> So if I copy myprogram folder into an other pc than myprogram.py can >> take care of adding mymodules folder to pythonpath. >> >> Thank you in advance >> Laszlo Antal >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cspears2002 at yahoo.com Sat Jun 24 00:34:48 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 23 Jun 2006 15:34:48 -0700 (PDT) Subject: [Tutor] critique my script! Message-ID: <20060623223448.38232.qmail@web51610.mail.yahoo.com> I wrote a script that creates a gui using pygtk. The gui consists of a vertical scrollbar and two buttons. The user picks a number (degrees Fahrenheit) with the scrollbar and then clicks the convert button. A functions converts the number to its equivalent in degrees Celsius and prints a response to the screen. The quit buttons ends the script. Tell me what you think! #!/usr/bin/python import pygtk pygtk.require('2.0') import gtk def scale_set_default_values(scale): scale.set_update_policy(gtk.UPDATE_CONTINUOUS) scale.set_digits(1) scale.set_value_pos(gtk.POS_LEFT) scale.set_draw_value(True) scale.set_sensitive(True) class Conversion_GUI: def convert_to_celsius(self, adj): self.degC = (adj.value - 32)/1.8 return self.degC def print_celsius(self, widget): print "Degrees Celsius: %.2f" % self.degC def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("Convert to Celsius") self.window.set_default_size(200,240) box1 = gtk.VBox(False, 0) self.window.add(box1) box2 = gtk.HBox(False, 10) box2.set_border_width(10) box1.pack_end(box2, True, True, 0) box3 = gtk.HBox(False, 10) box3.set_border_width(10) box1.pack_end(box3, True, True, 0) adj1 = gtk.Adjustment(32.0, 32.0, 213.0, 0.1, 1.0, 1.0) self.vscale = gtk.VScale(adj1) self.vscale.set_size_request(20, 300) scale_set_default_values(self.vscale) box1.pack_start(self.vscale, True, True, 0) adj1.connect("value_changed",self.convert_to_celsius) quit_button = gtk.Button("Quit") quit_button.connect("clicked", lambda w:gtk.main_quit()) convert_button = gtk.Button("Convert") convert_button.connect("clicked", self.print_celsius) box3.pack_start(convert_button, True, True, 0) box2.pack_start(quit_button, True, True, 0) self.vscale.show() convert_button.show() quit_button.show() box3.show() box2.show() box1.show() self.window.show() def main(self): gtk.main() return 0 if __name__ == '__main__': convert = Conversion_GUI() convert.main() From alan.gauld at freenet.co.uk Sat Jun 24 14:34:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 24 Jun 2006 13:34:17 +0100 Subject: [Tutor] critique my script! References: <20060623223448.38232.qmail@web51610.mail.yahoo.com> Message-ID: <002d01c6978a$827fea60$0301a8c0@XPpro> I can't really comment on the GTk bits because I've never used it. >From what I can see it looks like a fairly standard type of GUI framework however. A couple of comments: > class Conversion_GUI: > > def print_celsius(self, widget): > print "Degrees Celsius: %.2f" % self.degC I assume this prints to a consol rather than the GUI? > def __init__(self): > def main(self): I assume putting main inside the class is a GTk thing? Its a bit unusual in normal OOP since every instance will have a main() which is not the usual intention of main() functions... > if __name__ == '__main__': > convert = Conversion_GUI() > convert.main() Why not simply Conversion_GUI().main() Since you don't use convert anywhere. Alan G. From vinstce at gmail.com Sat Jun 24 20:04:28 2006 From: vinstce at gmail.com (vinodh kumar) Date: Sat, 24 Jun 2006 23:34:28 +0530 Subject: [Tutor] search engine Message-ID: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> hai all, i am a student of computer science dept. i have planned to design a search engine in python..i am seeking info about how to proceed further. i need some example source code -- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060624/23ff2103/attachment.htm From bgailer at alum.rpi.edu Sat Jun 24 21:33:23 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 24 Jun 2006 12:33:23 -0700 Subject: [Tutor] search engine In-Reply-To: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> References: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> Message-ID: <449D9383.9040005@alum.rpi.edu> vinodh kumar wrote: > hai all, > i am a student of computer science dept. i have planned to > design a search engine in python..i am seeking info about how to > proceed further. > i need some example source code That is an ambitious project. I wonder whether this is "homework". (It sounds too ambitious to be homework but one never knows). We don't provide code for homework but are glad to assist you when you get stuck. Before coding I suggest you create a design or plan for the program. Do you want to emulate Google? (Do you understand what Google does?) Or something simpler? (I suggest simpler). What are you searching for? How much information do you want to store? How do you want to present the results to a user? Python provides a urllib2 module for getting the contents of a web page. This example gets the python.org main page and displays the first 100 bytes of it: >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> print f.read(100) <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> Message-ID: <000301c697d8$c6167b10$0301a8c0@XPpro> > The data structure is: > mydata = [(Checking, 12.50),(Savings, 34.50)] > > And I want the result to look like this: > mydata = [(Checking, 19.50),(Savings, 34.50)] > > So how do I do this? OK, The problem is that you cannot change the contents of a tuple, you can only create a new tuple. Therefore you are probably better changing to a list or dictionary. >From the look of the data I'd suggest a dictionary might be best: myData = { 'Checking': 12.50, 'Savings': 34.50} Then you can do: myData['Checking'] += 7.00 If you decide to go for a list then it would look like: myData = [['Checking', 12.5],['Savings',34.50]] And you would modify it with: myData[0][1] += 7 # [0][1] = second element of first list But I think you will agree the dictionary approach looks a lot nicer, so unless there is a good reason why you can't use that I'd strongly recommend a dictionary. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Sun Jun 25 07:31:57 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 24 Jun 2006 22:31:57 -0700 (PDT) Subject: [Tutor] search engine In-Reply-To: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> Message-ID: On Sat, 24 Jun 2006, vinodh kumar wrote: > i am a student of computer science dept. i have planned to design > a search engine in python..i am seeking info about how to proceed further. What are you searching? From vinstce at gmail.com Sun Jun 25 07:52:15 2006 From: vinstce at gmail.com (vinodh kumar) Date: Sun, 25 Jun 2006 11:22:15 +0530 Subject: [Tutor] search engine In-Reply-To: References: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> Message-ID: <4a8ca98f0606242252r5295bc70mbecc4fbd166dd4b7@mail.gmail.com> On 6/25/06, Terry Carroll wrote: > > On Sat, 24 Jun 2006, vinodh kumar wrote: > > > i am a student of computer science dept. i have planned to > design > > a search engine in python..i am seeking info about how to proceed > further. > > What are you searching? hai, i am doing a search on the intranet portal. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060625/f7f0f4b2/attachment.htm From falcon3166 at hotmail.com Sun Jun 25 07:57:42 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 24 Jun 2006 23:57:42 -0600 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> <000301c697d8$c6167b10$0301a8c0@XPpro> Message-ID: Alan and all, Ok, so I changed it to a dictionary, and when I tested it, this error came up: Traceback (most recent call last): File "C:\Python24\Account Tracker.py", line 91, in -toplevel- printall() File "C:\Python24\Account Tracker.py", line 49, in printall print account,"\t $",accountlist[account]+"\n" TypeError: unsupported operand type(s) for +: 'float' and 'str' So how do I fix this error? Thanks for the help so far! ----- Original Message ----- From: "Alan Gauld" To: "Nathan Pinno" ; Sent: Saturday, June 24, 2006 3:54 PM Subject: Re: [Tutor] Is this correct syntax for what I want? > >> The data structure is: >> mydata = [(Checking, 12.50),(Savings, 34.50)] And I want the result to >> look like this: >> mydata = [(Checking, 19.50),(Savings, 34.50)] >> >> So how do I do this? > > OK, The problem is that you cannot change the contents of a > tuple, you can only create a new tuple. Therefore you are probably better > changing to a list or dictionary. > > From the look of the data I'd suggest a dictionary might be best: > > myData = { 'Checking': 12.50, 'Savings': 34.50} > > Then you can do: > > myData['Checking'] += 7.00 > > If you decide to go for a list then it would look like: > > myData = [['Checking', 12.5],['Savings',34.50]] > > And you would modify it with: > > myData[0][1] += 7 # [0][1] = second element of first list > > But I think you will agree the dictionary approach looks a lot nicer, so > unless there is a good reason why you can't use that I'd strongly > recommend a dictionary. > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > From bgailer at alum.rpi.edu Sun Jun 25 08:28:44 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 24 Jun 2006 23:28:44 -0700 Subject: [Tutor] search engine In-Reply-To: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> References: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> Message-ID: <449E2D1C.5040409@alum.rpi.edu> vinodh kumar wrote: > hai all, > i am a student of computer science dept. i have planned to > design a search engine in python..i am seeking info about how to > proceed further. > i need some example source code [snip] On further thought - I think my definition of search engine was too narrow. I did a Google search on python search engine and came up with interesting links. I recommend you do this search too. -- Bob Gailer 510-978-4454 From ravi.mathi at gmail.com Sun Jun 25 08:52:46 2006 From: ravi.mathi at gmail.com (ravi sankar) Date: Sun, 25 Jun 2006 12:22:46 +0530 Subject: [Tutor] Regular expressions Message-ID: <22c46a460606242352p2359b9f8x92458965b50ea23b@mail.gmail.com> hello all we are doing an intranet portral search.we had a look at the tutorials for Regular expressions...we need an insight on how to implement this.we r in the process of developing a unified search... -- regards, ravi. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060625/9964fe47/attachment.html From alan.gauld at freenet.co.uk Sun Jun 25 09:07:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 25 Jun 2006 08:07:10 +0100 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> <000301c697d8$c6167b10$0301a8c0@XPpro> Message-ID: <000301c69825$fa5600b0$0301a8c0@XPpro> > File "C:\Python24\Account Tracker.py", line 49, in printall > print account,"\t $",accountlist[account]+"\n" > TypeError: unsupported operand type(s) for +: 'float' and 'str' > > So how do I fix this error? What it's saying is you can't add a float and string. If you look at the code you are trying to add "\n" to accountlist[account] which is a float. You need to convert the string to a float or the float to a string. In this case converting the float to a string would be the better approach! :-) However I would personally recommend that you use a format string here since it will give you much better control of the appearance of the output and avoids the need to convert the values. print "%s\t $%0.2f\n" % (account, accountlist[account]) HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Sun Jun 25 09:13:23 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 25 Jun 2006 01:13:23 -0600 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> <000301c697d8$c6167b10$0301a8c0@XPpro> <000301c69825$fa5600b0$0301a8c0@XPpro> Message-ID: Thanks, it works now perfectly! Thanks for all the help! ----- Original Message ----- From: "Alan Gauld" To: "Nathan Pinno" ; Sent: Sunday, June 25, 2006 1:07 AM Subject: Re: [Tutor] Is this correct syntax for what I want? >> File "C:\Python24\Account Tracker.py", line 49, in printall >> print account,"\t $",accountlist[account]+"\n" >> TypeError: unsupported operand type(s) for +: 'float' and 'str' >> >> So how do I fix this error? > > What it's saying is you can't add a float and string. If you > look at the code you are trying to add "\n" to accountlist[account] > which is a float. You need to convert the string to a float or > the float to a string. In this case converting the float to a > string would be the better approach! :-) > > However I would personally recommend that you use a > format string here since it will give you much better control > of the appearance of the output and avoids the need to > convert the values. > > print "%s\t $%0.2f\n" % (account, accountlist[account]) > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > From falcon3166 at hotmail.com Sun Jun 25 10:02:31 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 25 Jun 2006 02:02:31 -0600 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> <000301c697d8$c6167b10$0301a8c0@XPpro> <000301c69825$fa5600b0$0301a8c0@XPpro> Message-ID: When I loaded it up, I got the following error: Traceback (most recent call last): File "C:\Python24\Account Tracker.py", line 82, in ? load_file(accountlist) File "C:\Python24\Account Tracker.py", line 10, in load_file amount = line.next().strip() AttributeError: 'str' object has no attribute 'next' According to it, the 'str' object has no attribute 'next'. So how would I load my file containing my data? Relevant code: def load_file(ac): import os filename = 'accounts.txt' if os.path.exists(filename): store = open(filename, 'r') for line in store: account = line.strip() amount = line.next().strip() ac[account] = amount else: store = open(filename, 'w') store.close Thanks. Nathan Pinno ----- Original Message ----- From: "Alan Gauld" To: "Nathan Pinno" ; Sent: Sunday, June 25, 2006 1:07 AM Subject: Re: [Tutor] Is this correct syntax for what I want? >> File "C:\Python24\Account Tracker.py", line 49, in printall >> print account,"\t $",accountlist[account]+"\n" >> TypeError: unsupported operand type(s) for +: 'float' and 'str' >> >> So how do I fix this error? > > What it's saying is you can't add a float and string. If you look at the > code you are trying to add "\n" to accountlist[account] which is a float. > You need to convert the string to a float or the float to a string. In > this case converting the float to a string would be the better approach! > :-) > > However I would personally recommend that you use a format string here > since it will give you much better control of the appearance of the output > and avoids the need to convert the values. > > print "%s\t $%0.2f\n" % (account, accountlist[account]) > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > From alan.gauld at freenet.co.uk Sun Jun 25 10:58:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 25 Jun 2006 09:58:42 +0100 Subject: [Tutor] Is this correct syntax for what I want? References: <004d01c69706$67bc9d10$0301a8c0@XPpro> <001501c69708$bc3face0$0301a8c0@XPpro> <000301c697d8$c6167b10$0301a8c0@XPpro> <000301c69825$fa5600b0$0301a8c0@XPpro> Message-ID: <000301c69835$8f05d2d0$0301a8c0@XPpro> > File "C:\Python24\Account Tracker.py", line 10, in load_file > amount = line.next().strip() > AttributeError: 'str' object has no attribute 'next' > > According to it, the 'str' object has no attribute 'next'. So how > would I load my file containing my data? The str object in question is line. line is a string that you have read from your file. What exactly do you think the next call would return even if line had a next method? I think you may be looking for the split method which will return a list of fields within the string. You will need to convert the string data into whatever format you require. You may find it helpful when debugging these kinds of problems to insert a few print statements, for example a print line at the top of the for loop. It depends a lot on the format of the data in the file. Alan G. From brb.shneider at yahoo.de Sun Jun 25 17:21:35 2006 From: brb.shneider at yahoo.de (Barbara Schneider) Date: Sun, 25 Jun 2006 17:21:35 +0200 (CEST) Subject: [Tutor] beginner: using optional agument in __init__ breaks my code Message-ID: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> Hello Group, I am puzzled about this: The following code implements a simple FIFO object. class Queue: " Implementing a FIFO data structure." # Methods def __init__(self): self.queue = [] def emptyP(self): return (self.queue == []) def insert(self, item): self.queue.append(item) def remove(self): if not self.emptyP(): return self.queue.pop(0) def __str__(self): return str(self.queue) This code works as intended. Now my idea is to provide an optional argument to the constructor. So I change it to: def __init__(self, q =[]): self.queue = q Now, something very strange happens: >>> a = Queue() >>> b = Queue() >>> a.insert(12) >>> print b [12] >>> Why do a and b share the same data? "self.queue" is supposed to be an instance variable. What does may change of the __init__ method do here? Thanx for your help. Barb ___________________________________________________________ Telefonate ohne weitere Kosten vom PC zum PC: http://messenger.yahoo.de From fiveholiday55 at hotmail.com Sun Jun 25 20:39:25 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Sun, 25 Jun 2006 19:39:25 +0100 Subject: [Tutor] search engine References: <4a8ca98f0606241104w68495925s8e66100f0c74d5a8@mail.gmail.com> Message-ID: it would be very hard to know the type of help you need at this time. You have not really written a single line of code and besides, no one will start it for you unless you have a specific problem that needs attention. Again, it sounds to me as though you've not actually grasped the scope of your intended project anyway. Until you have it defined and designed, it will remain/exist in your head which is the same problem that new developers like yourself have. A piece of advice, get a piece of paper, jot down what you want to do, or in effect, design your project prototype and the finally product. This will help you narrow down what you need to do and where/when to start and end. Finally, when you request help from lists like this, make your request very clear and precise; the guys here are more than happy to help you, trust me :) Projects like search engines are too ambiguous, generic and not defined. We don't know if you want to become a new Google, or you want a search facility for your site, or ... Be very direct and please use Google to do your search first before requesting help. Good luck Evans ----- Original Message ----- From: vinodh kumar To: tutor at python.org Sent: Saturday, June 24, 2006 7:04 PM Subject: [Tutor] search engine hai all, i am a student of computer science dept. i have planned to design a search engine in python..i am seeking info about how to proceed further. i need some example source code -- ------------------------------------------------------------------------------ _______________________________________________ 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/20060625/55729c51/attachment.html From khp at pflaesterer.de Sun Jun 25 21:01:58 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun, 25 Jun 2006 21:01:58 +0200 Subject: [Tutor] beginner: using optional agument in __init__ breaks my code In-Reply-To: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> (Barbara Schneider's message of "Sun, 25 Jun 2006 17:21:35 +0200 (CEST)") References: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> Message-ID: On 25 Jun 2006, brb.shneider at yahoo.de wrote: [...] > This code works as intended. Now my idea is to provide > an optional argument to the constructor. So I change > it to: > > def __init__(self, q =[]): > self.queue = q > > Now, something very strange happens: > >>>> a = Queue() >>>> b = Queue() >>>> a.insert(12) >>>> print b > [12] >>>> > > Why do a and b share the same data? "self.queue" is > supposed to be an instance variable. What does may > change of the __init__ method do here? The values of optional arguments are only once evaluated (when Python reads the definition). If you place there mutable objects like e.g. a list most of the time the effect you see is not what you want. So you have to write it a bit different. def __init__(self, q = None): if not q: q = [] self.queue = q or def __init__(self, q = None): self.queue = q or [] Now you get a fresh list for each instance. Karl -- Please do *not* send copies of replies to me. I read the list From ravi.mathi at gmail.com Sun Jun 25 22:17:31 2006 From: ravi.mathi at gmail.com (ravi sankar) Date: Mon, 26 Jun 2006 01:47:31 +0530 Subject: [Tutor] doubt in Regular expressions Message-ID: <22c46a460606251317i3d1923q313da8043943353a@mail.gmail.com> hello all, i want to search strings in the database available and return the link of the string instead simply returning the words... by using regular expressions(RE) i got a way to perform the string matches....give some info regarding how to return the link of the matched strings... ravi. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060626/33c0a0aa/attachment.html From fiveholiday55 at hotmail.com Sun Jun 25 22:37:13 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Sun, 25 Jun 2006 21:37:13 +0100 Subject: [Tutor] doubt in Regular expressions References: <22c46a460606251317i3d1923q313da8043943353a@mail.gmail.com> Message-ID: bump ----- Original Message ----- From: ravi sankar To: tutor at python.org Sent: Sunday, June 25, 2006 9:17 PM Subject: [Tutor] doubt in Regular expressions hello all, i want to search strings in the database available and return the link of the string instead simply returning the words... by using regular expressions(RE) i got a way to perform the string matches....give some info regarding how to return the link of the matched strings... ravi. ------------------------------------------------------------------------------ _______________________________________________ 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/20060625/9f3e4c08/attachment.htm From bgailer at alum.rpi.edu Sun Jun 25 22:45:21 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 25 Jun 2006 13:45:21 -0700 Subject: [Tutor] beginner: using optional agument in __init__ breaks my code In-Reply-To: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> References: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> Message-ID: <449EF5E1.5020806@alum.rpi.edu> Barbara Schneider wrote: > Hello Group, I am puzzled about this: The following > code implements a simple FIFO object. > > class Queue: > " Implementing a FIFO data structure." > > # Methods > def __init__(self): > self.queue = [] > > def emptyP(self): > return (self.queue == []) > > def insert(self, item): > self.queue.append(item) > > def remove(self): > if not self.emptyP(): > return self.queue.pop(0) > > def __str__(self): > return str(self.queue) > > This code works as intended. Now my idea is to provide > an optional argument to the constructor. So I change > it to: > > def __init__(self, q =[]): > self.queue = q > > Now, something very strange happens: > > >>>> a = Queue() >>>> b = Queue() >>>> a.insert(12) >>>> print b >>>> > [12] > > > Why do a and b share the same data? "self.queue" is > supposed to be an instance variable. What does may > change of the __init__ method do here? > When the function definition is processed, Python creates an empty list, which will be used as the default value for q whenever the function is called with no 2nd parameter. Any changes to that list are visible in any call to the function that has no 2nd parameter. To get the behavior I think you want try: def __init__(self, q = None): if not q: q = [] self.queue = q -- Bob Gailer 510-978-4454 From brb.shneider at yahoo.de Sun Jun 25 23:03:00 2006 From: brb.shneider at yahoo.de (Barbara Schneider) Date: Sun, 25 Jun 2006 23:03:00 +0200 (CEST) Subject: [Tutor] beginner: using optional agument in __init__ breaks my code In-Reply-To: Message-ID: <20060625210300.34835.qmail@web27806.mail.ukl.yahoo.com> --- Karl Pfl?sterer schrieb: > > The values of optional arguments are only once > evaluated (when Python > reads the definition). If you place there mutable > objects like e.g. a > list most of the time the effect you see is not what > you want. So you > have to write it a bit different. > > def __init__(self, q = None): > if not q: q = [] > self.queue = q > > or > > def __init__(self, q = None): > self.queue = q or [] > > Now you get a fresh list for each instance. > > Karl Thank you very much. I will use your code as a "recipe", while I still try to understand the mechanism and the reasons behind it. For me this feels odd. Barb ___________________________________________________________ Gesendet von Yahoo! Mail - Jetzt mit 1GB Speicher kostenlos - Hier anmelden: http://mail.yahoo.de From rabidpoobear at gmail.com Sun Jun 25 23:26:26 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 25 Jun 2006 16:26:26 -0500 Subject: [Tutor] doubt in Regular expressions In-Reply-To: References: <22c46a460606251317i3d1923q313da8043943353a@mail.gmail.com> Message-ID: <449EFF82.20504@gmail.com> Post Script: Sorry for the double e-mail, Evans. I forgot to forward it to the list the first time. Also, why don't replies automatically forward themselves to the list like the pygame mailing list does? For privacy reasons, in case you want to reply to someone separately? End of P.S. --------------------- Evans Anyokwu wrote: > bump Please don't send useless messages like this to the list. If you don't get a reply you want in a few days, send the message again. You waited 30 minutes and bumped the post. This is a huge turn-off for me and makes me not even want to consider your problem. However, I'll assume that you're used to asking questions on high-traffic message boards where this type of thing is necessary. [snip header] > > hello all, > i want to search strings in the database available and return > the link of the string instead simply returning the words... by > using regular expressions(RE) i got a way to perform the string > matches....give some info regarding how to return the link of the > matched strings... > ravi. > Again, you need to be more specific. We have no idea what your data structure looks like so we have no idea how to help you. This is the way I would do it. class SearchObj(object): def __init__(self): self.database = {} def addElement(astr,alink): self.database[astr] = alink def searchElement(astr): bstr = "blah blah" #insert code to match the element they're trying to search for with the closest one in the database. try: return self.database[bstr] except: pass This sounds like what you're trying to do, but I don't think it's a very good way to make a search engine. no matter how your string-matching is, a single keyword shouldn't be mapped to a single site link. That doesn't make sense! so if someone searches for "Puppy" they'll only get a single link back? What's the point of that? I want to search through the sites not have you search through them for me, find out which you think I want, and only give me the link to that one. If I did I would use Google's I'm Feeling Lucky. For that matter, I would use Google for any search. Why are you wanting to make this search engine? If it's for practice, I feel that it's not a very good project to practice on, because the design issues are so much larger than the programming itself. For practicing programming you should probably use some simple example that requires a lot of code. Like Tetris or Pong. If you're doing this for commercial use, you should just look into adding a Google SiteSearch to your page. python.org did this and it works fantastically. If you insist on continuing in this, I wish you luck and I hope everything turns out how you want it. Are you going to send us a link to it when you're done? -Luke From glingl at aon.at Sun Jun 25 23:42:09 2006 From: glingl at aon.at (Gregor Lingl) Date: Sun, 25 Jun 2006 23:42:09 +0200 Subject: [Tutor] for teachers and students: xturtle.py a new tutle graphics module Message-ID: <449F0331.8090005@aon.at> xturtle.py, extended turtle graphics a new turtle graphics module for Python and Tkinter Version 0.9 of xturtle.py has been released. It can be found at: http://ada.rg16.asn-wien.ac.at/~python/xturtle xturtle should work properly on all major platforms (Mac, Linux and Windows) Feedback would be appreciated to take it into account for polishing it to a final version 1.0. -------------------------------------- Learning to program computer should be fun, for adults and children alike. xturtle.py is a module designed to help you learn computer programming using Python. Turtle graphics provides a means for the beginning programmers to get immediate visual feedback about the correct working of her programs. It's main goal is to provide easy access to a sufficiently rich graphics toolkit. It needs only the standard distribution of python (incl. Tkinter) and imho it (or some descendant of it) once could (and should?) replace turtle.py which is contained in the current standard distribution. xturtle - delivered as a zip-file - contains four main elements: 1. the module xturtle.py . 2. set of 25+ sample scripts of great variety to show possible uses of xturtle.py 3. A simple demoViewer to run and view those sample scripts 4. documentation in form of *.txt files, which also can be viewed with the demoViewer. Docs are derived from doc strings. thus Python's help utility works fine with the module xturtle.py For more information (e.g. some screenshots) see the web page mentioned above. Gregor (It was very convenient for me to use Andre Roberge's last posting as a pattern. You don't mind, Andre?) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From r2b2 at myway.com Mon Jun 26 02:14:55 2006 From: r2b2 at myway.com (Rene Bourgoin) Date: Sun, 25 Jun 2006 20:14:55 -0400 (EDT) Subject: [Tutor] database help for newbie, fetchall() Message-ID: <20060626001455.0023B7E422@mprdmxin.myway.com> What is the best way to handle the resutls to a fetchall() command? The result seems to be a list of tuples [(aaa,bbb,ccc0,(11,222,333,)]. I'm new to programming but it seems that what ever I try to accomplish at some point i need the results to end up as strings. Even if you loop through the list you are left with a tuple that represents each column. (aa,bbb,x,ccc) Then you need to loop through the tuple to get your data into strings to use in your app some where. It seems to be more steps then it should be. Is there a cleaner way to do this? _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From justin.mailinglists at gmail.com Mon Jun 26 05:30:26 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 26 Jun 2006 11:30:26 +0800 Subject: [Tutor] MySQLdb: cant get '... where field in %s' to work Message-ID: <3c6718980606252030t78bcf2dcub2e7da2ccc0e0334@mail.gmail.com> I wrote: >> ARTICLES = ('XXX99999', 'ABZ00002') >> TESTARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite >> WHERE articleName IN %r""" % (ARTICLES,) >> SQLARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite >> WHERE articleName IN %s""" >> >> print cur.execute(TESTARTICLENAME), >> # cannot get this to work >> print cur.execute(SQLARTICLENAME, (ARTICLES,)) Matt wrote: > Can you post your error messages? Sorry, I neglected to state that I do not get any error message. I expected both 'execute' statements to print 2 but the second prints 0. For integers, I get the results I expected. From keosophon at khmeros.info Mon Jun 26 10:40:33 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Mon, 26 Jun 2006 15:40:33 +0700 Subject: [Tutor] Graphical Toolkit for new XLIFF translation editor Message-ID: <200606261540.33340.keosophon@khmeros.info> Hello list, KhmerOS is going to write an XLIFF translation editor with Python. Before starting, we would like to know which Graphical Toolkit should be used for the editor which supports many languages including Latin, Indic, Arabic and so on. However, there are many GUI toolkits such as QT, GTK, wxPython, Tkinter that have many different features that we don't know. So could you advice us which one should we use and why? Thanks, Phon From Pawel at kraszewscy.net Mon Jun 26 00:15:07 2006 From: Pawel at kraszewscy.net (Pawel Kraszewski) Date: Mon, 26 Jun 2006 00:15:07 +0200 Subject: [Tutor] beginner: using optional agument in __init__ breaks my code In-Reply-To: <449EF5E1.5020806@alum.rpi.edu> References: <20060625152135.25817.qmail@web27812.mail.ukl.yahoo.com> <449EF5E1.5020806@alum.rpi.edu> Message-ID: <200606260015.08174.Pawel@kraszewscy.net> Dnia niedziela, 25 czerwca 2006 22:45, Bob Gailer napisa?: > To get the behavior I think you want try: > > def __init__(self, q = None): > if not q: q = [] > self.queue = q I would disagree... This sure works for empty arguments, but: >>> u = [1,2,3] >>> a = Queue(u) >>> b = Queue(u) >>> a.insert(12) >>> print b gives [1, 2, 3, 12] which is still wrong. However assigning self.queue a COPY of parameter (empty or not) gives the desired result: def __init__(self, q = []): self.queue = q[:] -- Pawel Kraszewski From fiveholiday55 at hotmail.com Mon Jun 26 12:13:45 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Mon, 26 Jun 2006 11:13:45 +0100 Subject: [Tutor] doubt in Regular expressions References: <22c46a460606251317i3d1923q313da8043943353a@mail.gmail.com> <449EFF82.20504@gmail.com> Message-ID: Luke, You are confusing me for the OP. Please read carefully next time before you respond to the wrong person. I bumped because the OP's question was not specific and I thought I talked about people making their requests or questions very specific if they expect any useful replies. So, Luke take note; the message was not from me! ----- Original Message ----- From: "Luke Paireepinart" To: "Evans Anyokwu" ; Sent: Sunday, June 25, 2006 10:26 PM Subject: Re: [Tutor] doubt in Regular expressions > Post Script: Sorry for the double e-mail, Evans. I forgot to forward it > to the list the first time. > Also, why don't replies automatically forward themselves to the list like > the pygame mailing list does? > For privacy reasons, in case you want to reply to someone separately? > End of P.S. > --------------------- > > Evans Anyokwu wrote: >> bump > Please don't send useless messages like this to the list. If you don't > get a reply you want in a few days, send the message again. > You waited 30 minutes and bumped the post. This is a huge turn-off for me > and makes me not even want to consider your problem. > However, I'll assume that you're used to asking questions on high-traffic > message boards where this type of thing is necessary. > > [snip header] >> >> hello all, >> i want to search strings in the database available and return >> the link of the string instead simply returning the words... by >> using regular expressions(RE) i got a way to perform the string >> matches....give some info regarding how to return the link of the >> matched strings... >> ravi. >> > Again, you need to be more specific. We have no idea what your data > structure looks like so we have no idea how to help you. > This is the way I would do it. > > class SearchObj(object): > def __init__(self): > self.database = {} > def addElement(astr,alink): > self.database[astr] = alink > def searchElement(astr): > bstr = "blah blah" #insert code to match the element they're trying > to search for with the closest one in the database. > try: return self.database[bstr] > except: pass > > This sounds like what you're trying to do, but I don't think it's a very > good way to make a search engine. > no matter how your string-matching is, a single keyword shouldn't be > mapped to a single site link. That doesn't make sense! > so if someone searches for "Puppy" they'll only get a single link back? > What's the point of that? > I want to search through the sites not have you search through them for > me, find out which you think I want, and only give me the link to that > one. > If I did I would use Google's I'm Feeling Lucky. > For that matter, I would use Google for any search. > Why are you wanting to make this search engine? > If it's for practice, I feel that it's not a very good project to practice > on, because the design issues are so much larger than the programming > itself. > For practicing programming you should probably use some simple example > that requires a lot of code. Like Tetris or Pong. > If you're doing this for commercial use, you should just look into adding > a Google SiteSearch to your page. > python.org did this and it works fantastically. > If you insist on continuing in this, I wish you luck and I hope everything > turns out how you want it. > Are you going to send us a link to it when you're done? > -Luke > From emily.fortuna at nist.gov Mon Jun 26 14:33:26 2006 From: emily.fortuna at nist.gov (Emily Fortuna) Date: Mon, 26 Jun 2006 08:33:26 -0400 Subject: [Tutor] How can I add my folder to pythonpath? In-Reply-To: <449C5FE6.70206@tds.net> References: <1151096384.2025A810@fb6.dngr.org> <449C5905.70308@nist.gov> <449C5FE6.70206@tds.net> Message-ID: <449FD416.1090207@nist.gov> > That is close but not quite right. The correct import will be > from mymodules import mymodule1 > > Kent My apologies for misleading instructions. Emily > >> >> >> Laszlo Antal wrote: >>> Hi, >>> >>> This is how my directory looks >>> myprogram (this is the main folder for my program) >>> | >>> myprogram.py >>> mymodules (this is where I store my modules) >>> | >>> mymodule1.py >>> mymodule2.py >>> >>> I would like to import from mymodules folder my modules1.py, >>> mymodules2.py into myprogram.py. >>> >>> How can I add mymodules folder to pythonpath >>> from myprogram.py.? >>> So if I copy myprogram folder into an other pc than myprogram.py can >>> take care of adding mymodules folder to pythonpath. >>> >>> Thank you in advance >>> Laszlo Antal >>> _______________________________________________ >>> 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 >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Mon Jun 26 16:38:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 26 Jun 2006 07:38:13 -0700 (PDT) Subject: [Tutor] Regular expressions In-Reply-To: <22c46a460606242352p2359b9f8x92458965b50ea23b@mail.gmail.com> References: <22c46a460606242352p2359b9f8x92458965b50ea23b@mail.gmail.com> Message-ID: On Sun, 25 Jun 2006, ravi sankar wrote: > we are doing an intranet portral search.we had a look at the > tutorials for Regular expressions...we need an insight on how to > implement this.we r in the process of developing a unified search... If you have a question, please ask it directly. Are you asking for help in finding search engine implementations in Python, or how to implement regular expressions? Another question that comes up directly is: if you do have to implement a search engine, why? The technology for search engines is already established. Have you looked at common implementations such as Lucene or ht://Dig yet? http://lucene.apache.org/java/docs/ http://www.htdig.org/ Other than that, this really sounds like an assignment for a data-mining class. It skirts too close to homework territiory. So unless you have specific Python questions, the help we can give you will be limited. From dyoo at hkn.eecs.berkeley.edu Mon Jun 26 16:46:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 26 Jun 2006 07:46:41 -0700 (PDT) Subject: [Tutor] beginner: using optional agument in __init__ breaks my code In-Reply-To: <20060625210300.34835.qmail@web27806.mail.ukl.yahoo.com> References: <20060625210300.34835.qmail@web27806.mail.ukl.yahoo.com> Message-ID: >> The values of optional arguments are only once evaluated (when Python >> reads the definition). If you place there mutable objects like e.g. a >> list most of the time the effect you see is not what you want. So you >> have to write it a bit different. >> >> def __init__(self, q = None): >> if not q: q = [] >> self.queue = q >> >> Now you get a fresh list for each instance. >> > Thank you very much. I will use your code as a "recipe", while I still > try to understand the mechanism and the reasons behind it. For me this > feels odd. Hi Barbara, It is odd. *grin* There were at least two possible design choices to Python's behavior here. On every __init__, should Python re-evaluate the default argument expression? Or should that value be fixed? The designers of Python chose to the former, which leads to slight weirdness like this. From dyoo at hkn.eecs.berkeley.edu Mon Jun 26 17:11:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 26 Jun 2006 08:11:38 -0700 (PDT) Subject: [Tutor] doubt in Regular expressions In-Reply-To: References: <22c46a460606251317i3d1923q313da8043943353a@mail.gmail.com> <449EFF82.20504@gmail.com> Message-ID: > You are confusing me for the OP. Please read carefully next time before > you respond to the wrong person. > > I bumped because the OP's question was not specific and I thought I > talked about people making their requests or questions very specific if > they expect any useful replies. Hi Evans, Let get this out in the open. I'm not certain that "bumping" helps on Python-Tutor. It's not like we're voting for certain questions to be answered. And the volume of questions isn't yet high enough to "bury" anything. We're not Digg or Slashdot. The key to mailing lists like this is to keep signal-to-noise as low as we can: otherwise, it ends up driving away volunteers who want to help but who have limited time. Bumping doesn't add signal, but it does annoy volunteers, and that's bad. So, let's please not do that again. Addressing a general problem: I'm getting the strong sense that some data-mining class has just given an assignment to write a search engine in Python. In this scenario, the instructor may link Python-Tutor as a good resource for asking questions. All of this would be perfectly fine. Well, sorta. If one is in an "upper-level" course such as data-mining, Python-tutor should not be much help, since we focus on basic programming questions that should already be familiar to any CS student. I don't mean this to be snobbery; this is just a statement of my expectations. In any case, we're getting hit now with questions on how to do this search engine assignment. If I'm reading this situation correctly: can someone contact that instructor and tell them to tell their students not to abuse Python-tutor? We're not a one-stop shop for homework or project help, and these sort of questions tend to hit the morale of volunteers a bit. Again, it's not healthy for the list. Thanks! From python at venix.com Mon Jun 26 17:16:29 2006 From: python at venix.com (Python) Date: Mon, 26 Jun 2006 11:16:29 -0400 Subject: [Tutor] database help for newbie, fetchall() In-Reply-To: <20060626001455.0023B7E422@mprdmxin.myway.com> References: <20060626001455.0023B7E422@mprdmxin.myway.com> Message-ID: <1151334989.10267.291.camel@www.venix.com> On Sun, 2006-06-25 at 20:14 -0400, Rene Bourgoin wrote: > What is the best way to handle the resutls to a fetchall() command? > The result seems to be a list of tuples [(aaa,bbb,ccc0,(11,222,333,)]. Correct > I'm new to programming but it seems that what ever I try to accomplish > at some point i need the results to end up as strings. The python sql module will have converted the data items into Python data types. That is usually preferable. If you really need all of your data as strings, your code could look something like: def strcols(cursor): for row in cursor.fetchall(): yield [str(col) for col in row] ... for cols in strcols(cursor): # cols will be a list of row values converted to strings # do what needs to be done ... > Even if you loop through the list you are left with a tuple that represents each column. (aa,bbb,x,ccc) > Then you need to loop through the tuple to get your data into strings to use in your app some where. > It seems to be more steps then it should be. > Is there a cleaner way to do this? You'll need to decide if that is cleaner than your current code. If you want named access to the column values, some of the Python database packages (such as MySQLdb) can be configured to return the rows as dictionaries rather than tuples. Also the strcols function could be changed to yield a dictionary rather than a list. The cursor.description provides the column names, along with other data. > > > > > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From shanus_d at hotmail.com Mon Jun 26 17:15:13 2006 From: shanus_d at hotmail.com (shane davin) Date: Mon, 26 Jun 2006 16:15:13 +0100 Subject: [Tutor] (no subject) Message-ID: Stop the emails??? im getting more than i need regards _________________________________________________________________ The new MSN Search Toolbar now includes Desktop search! http://join.msn.com/toolbar/overview From alan.gauld at freenet.co.uk Mon Jun 26 18:25:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 26 Jun 2006 17:25:52 +0100 Subject: [Tutor] database help for newbie, fetchall() References: <20060626001455.0023B7E422@mprdmxin.myway.com> Message-ID: <000e01c6993d$31a43e20$0301a8c0@XPpro> > What is the best way to handle the resutls to a fetchall() command? > The result seems to be a list of tuples > [(aaa,bbb,ccc0,(11,222,333,)]. Yes, thats usually the most convenient way to present groups of data. > I'm new to programming but it seems that what ever I try to > accomplish > at some point i need the results to end up as strings. Thats pretty unusual. Usually strings are only needed for display (other than where the data is a string by default - eg a name!) Mostly its moire convenient to treat numbers as numbers, dates as dates, money as money etc and only turn them into strings for display purposes - which is where the format string operator comes into its own. > Even if you loop through the list you are left with a tuple that > represents each column. (aa,bbb,x,ccc) Correct and you can extract each item using indexing: for group in result: myDate = group[0] myCash = group[3] myString = group[2] etc... > Then you need to loop through the tuple to get your data into > strings > to use in your app some where. Why do you need to convert to strings? If the data is string data it should still be string data when you extract it. If its not string data why do you need to convert it? Other than for display, and that can be done in one line, like: displayString = "%s\t%0.2f\t%s" % (myDate, myCash,myString) > It seems to be more steps then it should be. > Is there a cleaner way to do this? The question is probably more about why you feel the need for strings? Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jun 26 18:36:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 26 Jun 2006 17:36:37 +0100 Subject: [Tutor] MySQLdb: cant get '... where field in %s' to work References: <3c6718980606252030t78bcf2dcub2e7da2ccc0e0334@mail.gmail.com> Message-ID: <001401c6993e$b6d9b1a0$0301a8c0@XPpro> >>> ARTICLES = ('XXX99999', 'ABZ00002') >>> TESTARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite >>> WHERE articleName IN %r""" % (ARTICLES,) This uses normal string substitution so puts the tuple ARTICLES in the query using the repr format - includes parens) which is what you want. (BTW using uppercase for variable names is considered bad practice - it makes your code much harer to read, and in Python uppercase usually means a constant.) >>> SQLARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite >>> WHERE articleName IN %s""" >>> print cur.execute(SQLARTICLENAME, (ARTICLES,)) This puts a tuple in the tuple but the substitution uses the substitution character of your database adaptor . Are you sure your adaprtor uses %s to substitute a tuple? You mat need to use str() on it first: print cur.execute(SQLARTICLENAME, (str(ARTICLES)) > Sorry, I neglected to state that I do not get any error message. > I expected both 'execute' statements to print 2 but the second > prints 0. > For integers, I get the results I expected. But I'm guessing... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tinoloc at gmail.com Mon Jun 26 19:58:36 2006 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 26 Jun 2006 13:58:36 -0400 Subject: [Tutor] Unit testing Message-ID: Hey Everybody, First off, I like to thank Kent, Alan, and Danny for their invaluable help. You guys are amazing! I do have some questions about unit testing. I have read through the diving into python section about unit testing as well as the documentation from the python docs. While that gives me a good beginning, of course I'm hungry for more and the doc doesn't go far enough. Here are the questions: I have a part of the code that writes to the filesystem. Is the only way of unit testing that section of code to write a piece of code that will actually go out and test to see if that particular is out there or is there another way? How do I simulate my queues and other sources of data. In Java, there is a program called JMock that you can use to simulate that. Is there anything like that in Python or do I roll my own and create the appropriate queues with some data in the unit test? How would I unit test python GUIs Could you recommend a book on unit testing, and maybe a book python and unit testing Thanks and much gratitude, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060626/5f72328c/attachment.htm From godoy at ieee.org Mon Jun 26 20:12:17 2006 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 26 Jun 2006 15:12:17 -0300 Subject: [Tutor] Unit testing References: Message-ID: <87veqnn5vi.fsf@ieee.org> "Tino Dai" writes: > How do I simulate my queues and other sources of data. In Java, there > is a program called JMock that you can use to simulate that. Is there > anything like that in Python or do I roll my own and create the appropriate > queues with some data in the unit test? >From JMock's page you get to mockobject's page and from there there's a link to Python-mock. http://sourceforge.net/projects/python-mock I hope it helps. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From kent37 at tds.net Mon Jun 26 20:42:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Jun 2006 14:42:36 -0400 Subject: [Tutor] Unit testing Message-ID: <20060626184236.JPBS16096.outaamta01.mail.tds.net@smtp.tds.net> Tino Dai wrote: > Hey Everybody, > > First off, I like to thank Kent, Alan, and Danny for their > invaluable help. You guys are amazing! You are welcome! > I do have some questions about unit testing. > > I have a part of the code that writes to the filesystem. Is the > only way of unit testing that section of code to write a piece of code > that will actually go out and test to see if that particular is out > there or is there another way? I often write unit tests that do this. In my opinion it is simple and straightforward and effective. Some purists will insist that a unit test shouldn't write the file system or touch a database or use any other external resource, but I think that is silly - if the job of a bit of code is to write a file or interact with the database, then the simplest way to test it is to check the file or database. As long as the tests run fast enough it's OK. (For me, a unit test on a single module should ideally run in well under a second.) Alternately you can use StringIO or other substitutes for files in your tests. But somewhere in your test system you probably want to make sure the actual file is there on disk, whether it is in a unit test or acceptance test. Kent PS to the list - I am out of town this week so don't expect my usual volume of postings :-) -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From Mike.Hansen at atmel.com Mon Jun 26 20:20:33 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 26 Jun 2006 12:20:33 -0600 Subject: [Tutor] (no subject) Message-ID: <57B026980605A64F9B23484C5659E32E179845@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of shane davin > Sent: Monday, June 26, 2006 9:15 AM > To: Tutor at python.org > Subject: [Tutor] (no subject) > > Stop the emails??? > im getting more than i need > regards > > _________________________________________________________________ > The new MSN Search Toolbar now includes Desktop search! > http://join.msn.com/toolbar/overview > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Go to http://mail.python.org/mailman/listinfo/tutor See the bottom of the page to unsubscribe. Mike From Barry.Carroll at psc.com Mon Jun 26 21:23:30 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 26 Jun 2006 12:23:30 -0700 Subject: [Tutor] for teachers and students: xturtle.py a new turtle graphics module Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36CA@eugsrv400.psc.pscnet.com> Gregor: Doesn't this really belong on Python-announce-list instead of here? You aren't asking any questions and you are announcing a new python-based application. That's what Python-announce-list is for. Post your announcement there and you will get plenty of feedback for your next release. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > Date: Sun, 25 Jun 2006 23:42:09 +0200 > From: Gregor Lingl > Subject: [Tutor] for teachers and students: xturtle.py a new tutle > graphics module > To: Tutor > Message-ID: <449F0331.8090005 at aon.at> > Content-Type: text/plain; charset=ISO-8859-15; format=flowed > > xturtle.py, extended turtle graphics > a new turtle graphics module for Python and Tkinter > > Version 0.9 of xturtle.py has been released. It can be found at: > > http://ada.rg16.asn-wien.ac.at/~python/xturtle > > xturtle should work properly on all major platforms (Mac, Linux and > Windows) Feedback would be appreciated to take it into account for > polishing it to a final version 1.0. > <> From tinoloc at gmail.com Mon Jun 26 21:50:36 2006 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 26 Jun 2006 15:50:36 -0400 Subject: [Tutor] Unit testing In-Reply-To: <20060626184236.JPBS16096.outaamta01.mail.tds.net@smtp.tds.net> References: <20060626184236.JPBS16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: > I often write unit tests that do this. In my opinion it is simple and > straightforward and effective. Some purists will insist that a unit test > shouldn't write the file system or touch a database or use any other > external resource, but I think that is silly - if the job of a bit of code > is to write a file or interact with the database, then the simplest way to > test it is to check the file or database. As long as the tests run fast > enough it's OK. (For me, a unit test on a single module should ideally run > in well under a second.) > > Alternately you can use StringIO or other substitutes for files in your > tests. But somewhere in your test system you probably want to make sure the > actual file is there on disk, whether it is in a unit test or acceptance > test. Ok, that leads me to my next question. Currently, I have a class that I want to unit test, but it contains a semaphore from another class. Now, I could make the semaphore a global variable, or I bring in the other class. One violates "good" programming principles and the other violates the unit testing principles. Is there another way? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060626/bf127497/attachment.htm From adam.jtm30 at gmail.com Tue Jun 27 00:41:22 2006 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 26 Jun 2006 23:41:22 +0100 Subject: [Tutor] Here's some interesting float oddness. Message-ID: I tried this expecting an exception In [2]: math.tan(math.pi/2) Out[2]: 16331778728383844.0 so I thought maybe that was a float limit which it probably is as you get weird results from higher values but it seems strange that it tries to run with it. In [5]: 16331778728383844.0 Out[5]: 16331778728383844.0 In [6]: 16331778728383845.0 Out[6]: 16331778728383844.0 In [7]: 16331778728383846.0 Out[7]: 16331778728383846.0 In [8]: 16331778728383845.0 Out[8]: 16331778728383844.0 In [9]: 16331778728383847.0 Out[9]: 16331778728383848.0 In [10]: 16331778728383848.0 Out[10]: 16331778728383848.0 weird huh? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060626/a47a4dfa/attachment.htm From falcon3166 at hotmail.com Tue Jun 27 00:48:03 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 26 Jun 2006 16:48:03 -0600 Subject: [Tutor] Why doesn't it save the data before exiting? Message-ID: Hey all, I am needing help on this. Why isn't it saving the data beore exiting the program? I don't get an error before exiting. Here's the code so far: accountlist = {} def load_file(ac): import os import pickle filename = 'accounts.txt' if os.path.exists(filename): store = open(filename, 'r') ac = pickle.load(store) else: store = open(filename, 'w') store.close() def save_file(ac): import pickle store = open('accounts.txt', 'w') pickle.dump(ac, store) store.close() def main_menu(): print "1) Add a new account" print "2) Remove a account" print "3) Print all info" print "4) Find account" print "5) Deposit" print "6) Withdraw funds" print "9) Save and exit." def add(): print "Add a new account" account = raw_input("Account Name: ") amount = float(raw_input("Amount: ")) accountlist[account] = amount def remove(): print "Remove a account" account = raw_input("Account: ") if accountlist.has_key(account): del accountlist[account] else: print account," was not found." def printall(): print "Account Info" for account in accountlist.keys(): print account+"\t $"+str(accountlist[account]),"\n" def lookup(): print "Specific Account Info" account = raw_input("Account: ") if accountlist.has_key(account): print account+"\t $"+str(accountlist[account]),"\n" else: print account," was not found." def deposit(): print "Deposit funds" account = raw_input("Account: ") if accountlist.has_key(account): amount = float(raw_input("Amount: ")) accountlist[account] += amount print account+"\t $"+str(accountlist[account]),"\n" else: print account," was not found." def withdraw(): print "Withdraw Funds." account = raw_input("Account: ") if accountlist.has_key(account): amount = float(raw_input("Amount: ")) accountlist[account] -= amount print account+"\t $"+str(accountlist[account]),"\n" else: print account," was not found." print "Account Tracker" print "By Nathan Pinno" print load_file(accountlist) while 1: main_menu() menu_choice = int(raw_input("Which item? ")) if menu_choice == 1: add() elif menu_choice == 2: remove() elif menu_choice == 3: printall() elif menu_choice == 4: lookup() elif menu_choice == 5: deposit() elif menu_choice == 6: withdraw() elif menu_choice == 9: break else: print "That's not an option. Please choose a valid option." save_file(accountlist) print "Have a nice day!" Thanks for the help so far! Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060626/c104a468/attachment-0001.html From bgailer at alum.rpi.edu Tue Jun 27 01:12:12 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 26 Jun 2006 16:12:12 -0700 Subject: [Tutor] Why doesn't it save the data before exiting? In-Reply-To: References: Message-ID: <44A069CC.4030402@alum.rpi.edu> Nathan Pinno wrote: > Hey all, > > I am needing help on this. Why isn't it saving the data beore exiting > the program? But it does save it. What evidence do you have that it is not? Please in the future always tell us what the evidence of a problem is. Also I suggest you add validation of user input, to avoid the program terminating if the user hits the wrong key. In fact the whole menu thing would be easier to manage if the choices were character rather than integer. Then you don't need int() conversion and the exception raising if the user does not enter an integer string. Similar comment regarding checking input before applying float(). Consider % formatting for the outputs as in: print "%s\t $%2f\n" % (account, accountlist[account]) # instead of print account+"\t $"+str(accountlist[account]),"\n" Also I suggest you not open store for writing until just before the pickle.dump. Otherwise it is possible to have an empty file on which pickle.load will raise an exception. > I don't get an error before exiting. Good. You should not, unless you enter something that won't convert to integer, or string, or you leave an empty account.txt file. > > Here's the code so far: > accountlist = {} > > def load_file(ac): > import os > import pickle > filename = 'accounts.txt' > if os.path.exists(filename): > store = open(filename, 'r') > ac = pickle.load(store) > else: > store = open(filename, 'w') > store.close() > > def save_file(ac): > import pickle > store = open('accounts.txt', 'w') > pickle.dump(ac, store) > store.close() > > def main_menu(): > print "1) Add a new account" > print "2) Remove a account" > print "3) Print all info" > print "4) Find account" > print "5) Deposit" > print "6) Withdraw funds" > print "9) Save and exit." > > def add(): > print "Add a new account" > account = raw_input("Account Name: ") > amount = float(raw_input("Amount: ")) > accountlist[account] = amount > > def remove(): > print "Remove a account" > account = raw_input("Account: ") > if accountlist.has_key(account): > del accountlist[account] > else: > print account," was not found." > > def printall(): > print "Account Info" > for account in accountlist.keys(): > print account+"\t $"+str(accountlist[account]),"\n" > > def lookup(): > print "Specific Account Info" > account = raw_input("Account: ") > if accountlist.has_key(account): > print account+"\t $"+str(accountlist[account]),"\n" > else: > print account," was not found." > > def deposit(): > print "Deposit funds" > account = raw_input("Account: ") > if accountlist.has_key(account): > amount = float(raw_input("Amount: ")) > accountlist[account] += amount > print account+"\t $"+str(accountlist[account]),"\n" > else: > print account," was not found." > > def withdraw(): > print "Withdraw Funds." > account = raw_input("Account: ") > if accountlist.has_key(account): > amount = float(raw_input("Amount: ")) > accountlist[account] -= amount > print account+"\t $"+str(accountlist[account]),"\n" > else: > print account," was not found." > > print "Account Tracker" > print "By Nathan Pinno" > print > load_file(accountlist) > while 1: > main_menu() > menu_choice = int(raw_input("Which item? ")) > if menu_choice == 1: > add() > elif menu_choice == 2: > remove() > elif menu_choice == 3: > printall() > elif menu_choice == 4: > lookup() > elif menu_choice == 5: > deposit() > elif menu_choice == 6: > withdraw() > elif menu_choice == 9: > break > else: > print "That's not an option. Please choose a valid option." > save_file(accountlist) > print "Have a nice day!" > > Thanks for the help so far! > Nathan Pinno > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Tue Jun 27 01:19:06 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 26 Jun 2006 16:19:06 -0700 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION In-Reply-To: <44A069CC.4030402@alum.rpi.edu> References: <44A069CC.4030402@alum.rpi.edu> Message-ID: <44A06B6A.3010805@alum.rpi.edu> Bob Gailer wrote: > Nathan Pinno wrote: > >> Hey all, >> >> I am needing help on this. Why isn't it saving the data beore exiting >> the program? >> > But it does save it. What evidence do you have that it is not? > > Please in the future always tell us what the evidence of a problem is. > > Also I suggest you add validation of user input, to avoid the program > terminating if the user hits the wrong key. In fact the whole menu thing > would be easier to manage if the choices were character rather than > integer. Then you don't need int() conversion and the exception raising > if the user does not enter an integer string. > > Similar comment regarding checking input before applying float(). > > Consider % formatting for the outputs as in: > print "%s\t $%2f\n" % (account, accountlist[account]) # instead of > print account+"\t $"+str(accountlist[account]),"\n" > > Also I suggest you not open store for writing until just before the > pickle.dump. Otherwise it is possible to have an empty file on which > pickle.load will raise an exception. > >> I don't get an error before exiting. >> > Good. You should not, unless you enter something that won't convert to > integer, or string [ I MEANT float ], or you leave an empty account.txt file. > >> >> Here's the code so far: >> accountlist = {} >> >> def load_file(ac): >> import os >> import pickle >> filename = 'accounts.txt' >> if os.path.exists(filename): >> store = open(filename, 'r') >> ac = pickle.load(store) >> else: >> store = open(filename, 'w') >> store.close() >> >> def save_file(ac): >> import pickle >> store = open('accounts.txt', 'w') >> pickle.dump(ac, store) >> store.close() >> >> def main_menu(): >> print "1) Add a new account" >> print "2) Remove a account" >> print "3) Print all info" >> print "4) Find account" >> print "5) Deposit" >> print "6) Withdraw funds" >> print "9) Save and exit." >> >> def add(): >> print "Add a new account" >> account = raw_input("Account Name: ") >> amount = float(raw_input("Amount: ")) >> accountlist[account] = amount >> >> def remove(): >> print "Remove a account" >> account = raw_input("Account: ") >> if accountlist.has_key(account): >> del accountlist[account] >> else: >> print account," was not found." >> >> def printall(): >> print "Account Info" >> for account in accountlist.keys(): >> print account+"\t $"+str(accountlist[account]),"\n" >> >> def lookup(): >> print "Specific Account Info" >> account = raw_input("Account: ") >> if accountlist.has_key(account): >> print account+"\t $"+str(accountlist[account]),"\n" >> else: >> print account," was not found." >> >> def deposit(): >> print "Deposit funds" >> account = raw_input("Account: ") >> if accountlist.has_key(account): >> amount = float(raw_input("Amount: ")) >> accountlist[account] += amount >> print account+"\t $"+str(accountlist[account]),"\n" >> else: >> print account," was not found." >> >> def withdraw(): >> print "Withdraw Funds." >> account = raw_input("Account: ") >> if accountlist.has_key(account): >> amount = float(raw_input("Amount: ")) >> accountlist[account] -= amount >> print account+"\t $"+str(accountlist[account]),"\n" >> else: >> print account," was not found." >> >> print "Account Tracker" >> print "By Nathan Pinno" >> print >> load_file(accountlist) >> while 1: >> main_menu() >> menu_choice = int(raw_input("Which item? ")) >> if menu_choice == 1: >> add() >> elif menu_choice == 2: >> remove() >> elif menu_choice == 3: >> printall() >> elif menu_choice == 4: >> lookup() >> elif menu_choice == 5: >> deposit() >> elif menu_choice == 6: >> withdraw() >> elif menu_choice == 9: >> break >> else: >> print "That's not an option. Please choose a valid option." >> save_file(accountlist) >> print "Have a nice day!" >> >> Thanks for the help so far! >> Nathan Pinno >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- Bob Gailer 510-978-4454 From falcon3166 at hotmail.com Tue Jun 27 01:23:40 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 26 Jun 2006 17:23:40 -0600 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION References: <44A069CC.4030402@alum.rpi.edu> <44A06B6A.3010805@alum.rpi.edu> Message-ID: How do I know? Simple. Next time I load it and ask it to print the list of accounts and how much in each, I only get: Account Info then the menu again, with no info. Nathan Pinno ----- Original Message ----- From: "Bob Gailer" To: "Bob Gailer" Cc: "Nathan Pinno" ; Sent: Monday, June 26, 2006 5:19 PM Subject: Re: [Tutor] Why doesn't it save the data before exiting? CORRECTION > Bob Gailer wrote: >> Nathan Pinno wrote: >> >>> Hey all, >>> I am needing help on this. Why isn't it saving the data beore exiting >>> the program? >>> >> But it does save it. What evidence do you have that it is not? >> >> Please in the future always tell us what the evidence of a problem is. >> >> Also I suggest you add validation of user input, to avoid the program >> terminating if the user hits the wrong key. In fact the whole menu thing >> would be easier to manage if the choices were character rather than >> integer. Then you don't need int() conversion and the exception raising >> if the user does not enter an integer string. >> >> Similar comment regarding checking input before applying float(). >> >> Consider % formatting for the outputs as in: >> print "%s\t $%2f\n" % (account, accountlist[account]) # instead >> of >> print account+"\t $"+str(accountlist[account]),"\n" >> >> Also I suggest you not open store for writing until just before the >> pickle.dump. Otherwise it is possible to have an empty file on which >> pickle.load will raise an exception. >> >>> I don't get an error before exiting. >>> >> Good. You should not, unless you enter something that won't convert to >> integer, or string [ I MEANT float ], or you leave an empty account.txt >> file. >> >>> Here's the code so far: >>> accountlist = {} >>> def load_file(ac): >>> import os >>> import pickle >>> filename = 'accounts.txt' >>> if os.path.exists(filename): >>> store = open(filename, 'r') >>> ac = pickle.load(store) >>> else: >>> store = open(filename, 'w') >>> store.close() >>> def save_file(ac): >>> import pickle >>> store = open('accounts.txt', 'w') >>> pickle.dump(ac, store) >>> store.close() >>> def main_menu(): >>> print "1) Add a new account" >>> print "2) Remove a account" >>> print "3) Print all info" >>> print "4) Find account" >>> print "5) Deposit" >>> print "6) Withdraw funds" >>> print "9) Save and exit." >>> def add(): >>> print "Add a new account" >>> account = raw_input("Account Name: ") >>> amount = float(raw_input("Amount: ")) >>> accountlist[account] = amount >>> def remove(): >>> print "Remove a account" >>> account = raw_input("Account: ") >>> if accountlist.has_key(account): >>> del accountlist[account] >>> else: >>> print account," was not found." >>> def printall(): >>> print "Account Info" >>> for account in accountlist.keys(): >>> print account+"\t $"+str(accountlist[account]),"\n" >>> def lookup(): >>> print "Specific Account Info" >>> account = raw_input("Account: ") >>> if accountlist.has_key(account): >>> print account+"\t $"+str(accountlist[account]),"\n" >>> else: >>> print account," was not found." >>> def deposit(): >>> print "Deposit funds" >>> account = raw_input("Account: ") >>> if accountlist.has_key(account): >>> amount = float(raw_input("Amount: ")) >>> accountlist[account] += amount >>> print account+"\t $"+str(accountlist[account]),"\n" >>> else: >>> print account," was not found." >>> def withdraw(): >>> print "Withdraw Funds." >>> account = raw_input("Account: ") >>> if accountlist.has_key(account): >>> amount = float(raw_input("Amount: ")) >>> accountlist[account] -= amount >>> print account+"\t $"+str(accountlist[account]),"\n" >>> else: >>> print account," was not found." >>> print "Account Tracker" >>> print "By Nathan Pinno" >>> print >>> load_file(accountlist) >>> while 1: >>> main_menu() >>> menu_choice = int(raw_input("Which item? ")) >>> if menu_choice == 1: >>> add() >>> elif menu_choice == 2: >>> remove() >>> elif menu_choice == 3: >>> printall() >>> elif menu_choice == 4: >>> lookup() >>> elif menu_choice == 5: >>> deposit() >>> elif menu_choice == 6: >>> withdraw() >>> elif menu_choice == 9: >>> break >>> else: >>> print "That's not an option. Please choose a valid option." >>> save_file(accountlist) >>> print "Have a nice day!" >>> Thanks for the help so far! >>> Nathan Pinno >>> ------------------------------------------------------------------------ >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> > > > -- > Bob Gailer > 510-978-4454 > > From bgailer at alum.rpi.edu Tue Jun 27 01:33:31 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 26 Jun 2006 16:33:31 -0700 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION In-Reply-To: References: <44A069CC.4030402@alum.rpi.edu> <44A06B6A.3010805@alum.rpi.edu> Message-ID: <44A06ECB.4070909@alum.rpi.edu> Nathan Pinno wrote: > How do I know? Simple. Next time I load it and ask it to print the > list of accounts and how much in each, I only get: > > Account Info > > then the menu again, with no info. Ah. But the program starts setting accountlist = {}. When you reach printall, accountlist is still {}. Can you figure out why? Hint: load_file(accountlist) does not change accountlist. > > Nathan Pinno > ----- Original Message ----- From: "Bob Gailer" > To: "Bob Gailer" > Cc: "Nathan Pinno" ; > Sent: Monday, June 26, 2006 5:19 PM > Subject: Re: [Tutor] Why doesn't it save the data before exiting? > CORRECTION > > >> Bob Gailer wrote: >>> Nathan Pinno wrote: >>> >>>> Hey all, >>>> I am needing help on this. Why isn't it saving the data beore >>>> exiting the program? >>>> >>> But it does save it. What evidence do you have that it is not? >>> >>> Please in the future always tell us what the evidence of a problem is. >>> >>> Also I suggest you add validation of user input, to avoid the >>> program terminating if the user hits the wrong key. In fact the >>> whole menu thing would be easier to manage if the choices were >>> character rather than integer. Then you don't need int() conversion >>> and the exception raising if the user does not enter an integer string. >>> >>> Similar comment regarding checking input before applying float(). >>> >>> Consider % formatting for the outputs as in: >>> print "%s\t $%2f\n" % (account, accountlist[account]) # >>> instead of >>> print account+"\t $"+str(accountlist[account]),"\n" >>> >>> Also I suggest you not open store for writing until just before the >>> pickle.dump. Otherwise it is possible to have an empty file on which >>> pickle.load will raise an exception. >>> >>>> I don't get an error before exiting. >>>> >>> Good. You should not, unless you enter something that won't convert >>> to integer, or string [ I MEANT float ], or you leave an empty >>> account.txt file. >>> >>>> Here's the code so far: >>>> accountlist = {} >>>> def load_file(ac): >>>> import os >>>> import pickle >>>> filename = 'accounts.txt' >>>> if os.path.exists(filename): >>>> store = open(filename, 'r') >>>> ac = pickle.load(store) >>>> else: >>>> store = open(filename, 'w') >>>> store.close() >>>> def save_file(ac): >>>> import pickle >>>> store = open('accounts.txt', 'w') >>>> pickle.dump(ac, store) >>>> store.close() >>>> def main_menu(): >>>> print "1) Add a new account" >>>> print "2) Remove a account" >>>> print "3) Print all info" >>>> print "4) Find account" >>>> print "5) Deposit" >>>> print "6) Withdraw funds" >>>> print "9) Save and exit." >>>> def add(): >>>> print "Add a new account" >>>> account = raw_input("Account Name: ") >>>> amount = float(raw_input("Amount: ")) >>>> accountlist[account] = amount >>>> def remove(): >>>> print "Remove a account" >>>> account = raw_input("Account: ") >>>> if accountlist.has_key(account): >>>> del accountlist[account] >>>> else: >>>> print account," was not found." >>>> def printall(): >>>> print "Account Info" >>>> for account in accountlist.keys(): >>>> print account+"\t $"+str(accountlist[account]),"\n" >>>> def lookup(): >>>> print "Specific Account Info" >>>> account = raw_input("Account: ") >>>> if accountlist.has_key(account): >>>> print account+"\t $"+str(accountlist[account]),"\n" >>>> else: >>>> print account," was not found." >>>> def deposit(): >>>> print "Deposit funds" >>>> account = raw_input("Account: ") >>>> if accountlist.has_key(account): >>>> amount = float(raw_input("Amount: ")) >>>> accountlist[account] += amount >>>> print account+"\t $"+str(accountlist[account]),"\n" >>>> else: >>>> print account," was not found." >>>> def withdraw(): >>>> print "Withdraw Funds." >>>> account = raw_input("Account: ") >>>> if accountlist.has_key(account): >>>> amount = float(raw_input("Amount: ")) >>>> accountlist[account] -= amount >>>> print account+"\t $"+str(accountlist[account]),"\n" >>>> else: >>>> print account," was not found." >>>> print "Account Tracker" >>>> print "By Nathan Pinno" >>>> print >>>> load_file(accountlist) >>>> while 1: >>>> main_menu() >>>> menu_choice = int(raw_input("Which item? ")) >>>> if menu_choice == 1: >>>> add() >>>> elif menu_choice == 2: >>>> remove() >>>> elif menu_choice == 3: >>>> printall() >>>> elif menu_choice == 4: >>>> lookup() >>>> elif menu_choice == 5: >>>> deposit() >>>> elif menu_choice == 6: >>>> withdraw() >>>> elif menu_choice == 9: >>>> break >>>> else: >>>> print "That's not an option. Please choose a valid option." >>>> save_file(accountlist) >>>> print "Have a nice day!" >>>> Thanks for the help so far! >>>> Nathan Pinno >>>> ------------------------------------------------------------ >> > -- Bob Gailer 510-978-4454 From Barry.Carroll at psc.com Tue Jun 27 01:35:10 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 26 Jun 2006 16:35:10 -0700 Subject: [Tutor] Unit testing Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36CC@eugsrv400.psc.pscnet.com> Regards, Tino: I agree with Kent on this. As much as possible, a unit test should test what it is supposed to do. > Date: Mon, 26 Jun 2006 15:50:36 -0400 > From: "Tino Dai" > Subject: Re: [Tutor] Unit testing > To: "Kent Johnson" , tutor at python.org > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > > I often write unit tests that do this. In my opinion it is simple and > > straightforward and effective. Some purists will insist that a unit test > > shouldn't write the file system or touch a database or use any other > > external resource, but I think that is silly - if the job of a bit of > code > > is to write a file or interact with the database, then the simplest way > to > > test it is to check the file or database. As long as the tests run fast > > enough it's OK. (For me, a unit test on a single module should ideally > run > > in well under a second.) > > > > Alternately you can use StringIO or other substitutes for files in your > > tests. But somewhere in your test system you probably want to make sure > the > > actual file is there on disk, whether it is in a unit test or acceptance > > test. > > > Ok, that leads me to my next question. Currently, I have a class that I > want to unit test, but it contains a semaphore from another class. Now, I > could make the semaphore a global variable, or I bring in the other class. > One violates "good" programming principles and the other violates the unit > testing principles. Is there another way? > > -Tino > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060626/bf127497/att ac > hment.html > > ------------------------------ I think the same principle applies here. The code you are testing involves a semaphore. By all means, include the other class and test the semaphore. I'm not familiar with the 'unit testing principles' that would forbid your doing this. Even if I were, principles are to be followed when they make sense. When it makes better sense to violate a principle, then violate it. Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From falcon3166 at hotmail.com Tue Jun 27 03:22:07 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 26 Jun 2006 19:22:07 -0600 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION References: <44A069CC.4030402@alum.rpi.edu> <44A06B6A.3010805@alum.rpi.edu> <44A06ECB.4070909@alum.rpi.edu> Message-ID: Would it be this line? pickle.dump(ac, store) Would this make it work? ac = pickle.dump(store) Nathan ----- Original Message ----- From: "Bob Gailer" To: "Nathan Pinno" Cc: Sent: Monday, June 26, 2006 5:33 PM Subject: Re: [Tutor] Why doesn't it save the data before exiting? CORRECTION > Nathan Pinno wrote: >> How do I know? Simple. Next time I load it and ask it to print the list >> of accounts and how much in each, I only get: >> >> Account Info >> >> then the menu again, with no info. > Ah. But the program starts setting accountlist = {}. When you reach > printall, accountlist is still {}. Can you figure out why? > > Hint: load_file(accountlist) does not change accountlist. >> >> Nathan Pinno >> ----- Original Message ----- From: "Bob Gailer" >> To: "Bob Gailer" >> Cc: "Nathan Pinno" ; >> Sent: Monday, June 26, 2006 5:19 PM >> Subject: Re: [Tutor] Why doesn't it save the data before exiting? >> CORRECTION >> >> >>> Bob Gailer wrote: >>>> Nathan Pinno wrote: >>>> >>>>> Hey all, >>>>> I am needing help on this. Why isn't it saving the data beore exiting >>>>> the program? >>>>> >>>> But it does save it. What evidence do you have that it is not? >>>> >>>> Please in the future always tell us what the evidence of a problem is. >>>> >>>> Also I suggest you add validation of user input, to avoid the program >>>> terminating if the user hits the wrong key. In fact the whole menu >>>> thing would be easier to manage if the choices were character rather >>>> than integer. Then you don't need int() conversion and the exception >>>> raising if the user does not enter an integer string. >>>> >>>> Similar comment regarding checking input before applying float(). >>>> >>>> Consider % formatting for the outputs as in: >>>> print "%s\t $%2f\n" % (account, accountlist[account]) # instead >>>> of >>>> print account+"\t $"+str(accountlist[account]),"\n" >>>> >>>> Also I suggest you not open store for writing until just before the >>>> pickle.dump. Otherwise it is possible to have an empty file on which >>>> pickle.load will raise an exception. >>>> >>>>> I don't get an error before exiting. >>>>> >>>> Good. You should not, unless you enter something that won't convert to >>>> integer, or string [ I MEANT float ], or you leave an empty account.txt >>>> file. >>>> >>>>> Here's the code so far: >>>>> accountlist = {} >>>>> def load_file(ac): >>>>> import os >>>>> import pickle >>>>> filename = 'accounts.txt' >>>>> if os.path.exists(filename): >>>>> store = open(filename, 'r') >>>>> ac = pickle.load(store) >>>>> else: >>>>> store = open(filename, 'w') >>>>> store.close() >>>>> def save_file(ac): >>>>> import pickle >>>>> store = open('accounts.txt', 'w') >>>>> pickle.dump(ac, store) >>>>> store.close() >>>>> def main_menu(): >>>>> print "1) Add a new account" >>>>> print "2) Remove a account" >>>>> print "3) Print all info" >>>>> print "4) Find account" >>>>> print "5) Deposit" >>>>> print "6) Withdraw funds" >>>>> print "9) Save and exit." >>>>> def add(): >>>>> print "Add a new account" >>>>> account = raw_input("Account Name: ") >>>>> amount = float(raw_input("Amount: ")) >>>>> accountlist[account] = amount >>>>> def remove(): >>>>> print "Remove a account" >>>>> account = raw_input("Account: ") >>>>> if accountlist.has_key(account): >>>>> del accountlist[account] >>>>> else: >>>>> print account," was not found." >>>>> def printall(): >>>>> print "Account Info" >>>>> for account in accountlist.keys(): >>>>> print account+"\t $"+str(accountlist[account]),"\n" >>>>> def lookup(): >>>>> print "Specific Account Info" >>>>> account = raw_input("Account: ") >>>>> if accountlist.has_key(account): >>>>> print account+"\t $"+str(accountlist[account]),"\n" >>>>> else: >>>>> print account," was not found." >>>>> def deposit(): >>>>> print "Deposit funds" >>>>> account = raw_input("Account: ") >>>>> if accountlist.has_key(account): >>>>> amount = float(raw_input("Amount: ")) >>>>> accountlist[account] += amount >>>>> print account+"\t $"+str(accountlist[account]),"\n" >>>>> else: >>>>> print account," was not found." >>>>> def withdraw(): >>>>> print "Withdraw Funds." >>>>> account = raw_input("Account: ") >>>>> if accountlist.has_key(account): >>>>> amount = float(raw_input("Amount: ")) >>>>> accountlist[account] -= amount >>>>> print account+"\t $"+str(accountlist[account]),"\n" >>>>> else: >>>>> print account," was not found." >>>>> print "Account Tracker" >>>>> print "By Nathan Pinno" >>>>> print >>>>> load_file(accountlist) >>>>> while 1: >>>>> main_menu() >>>>> menu_choice = int(raw_input("Which item? ")) >>>>> if menu_choice == 1: >>>>> add() >>>>> elif menu_choice == 2: >>>>> remove() >>>>> elif menu_choice == 3: >>>>> printall() >>>>> elif menu_choice == 4: >>>>> lookup() >>>>> elif menu_choice == 5: >>>>> deposit() >>>>> elif menu_choice == 6: >>>>> withdraw() >>>>> elif menu_choice == 9: >>>>> break >>>>> else: >>>>> print "That's not an option. Please choose a valid option." >>>>> save_file(accountlist) >>>>> print "Have a nice day!" >>>>> Thanks for the help so far! >>>>> Nathan Pinno >>>>> ------------------------------------------------------------ >>> >> > > > -- > Bob Gailer > 510-978-4454 > > From bgailer at alum.rpi.edu Tue Jun 27 04:49:45 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 26 Jun 2006 19:49:45 -0700 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION In-Reply-To: References: <44A069CC.4030402@alum.rpi.edu> <44A06B6A.3010805@alum.rpi.edu> <44A06ECB.4070909@alum.rpi.edu> Message-ID: <44A09CC9.6080805@alum.rpi.edu> Nathan Pinno wrote: I already told you that the data is being saved to the file. And is being reloaded by ac = pickle.load(store). But the reloaded data is not being assigned to accountlist, since parameters to functions are treated as local variables. Assigning to a parameter in a function does NOT change the value of the parameter in the call. You can demonstrate this as follows: >>> x = 2 >>> def f(y): ... y = 3 >>> print x 2 To fix your program, define load_file as: def load_file(): import os import pickle filename = 'accounts.txt' if os.path.exists(filename): store = open(filename, 'r') ac = pickle.load(store) store.close() else: ac = {} return ac And change load_file(accountlist) to: accountlist = load_file() [snip] -- Bob Gailer 510-978-4454 From alan.gauld at freenet.co.uk Tue Jun 27 06:10:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 27 Jun 2006 05:10:26 +0100 Subject: [Tutor] Unit testing References: <20060626184236.JPBS16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: <003901c6999f$9f0a25d0$0301a8c0@XPpro> > Ok, that leads me to my next question. Currently, I have a class > that I > want to unit test, but it contains a semaphore from another class. > Now, I > could make the semaphore a global variable, or I bring in the other > class. > One violates "good" programming principles and the other violates > the unit > testing principles. Is there another way? Reconsider your definition of a "Unit" maybe? A Unit should stand alone, it is the smallest amount of code that can stand alone. If your class relies on another class maybe both classes need to be considered as a single unit? Or maybe the classes need to be refactored to make them less closely coupled? Alan G. From alan.gauld at freenet.co.uk Tue Jun 27 06:26:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 27 Jun 2006 05:26:27 +0100 Subject: [Tutor] Why doesn't it save the data before exiting? CORRECTION References: <44A069CC.4030402@alum.rpi.edu> <44A06B6A.3010805@alum.rpi.edu> Message-ID: <005a01c699a1$dbcb3570$0301a8c0@XPpro> Hi Nathan, > How do I know? Simple. Next time I load it and ask it to print the > list of accounts and how much in each, I only get: OK, but that could be down to: 1) The save file not working, 2) the load file not working 3) the print accounts not working Have you checked whether the store file exists and is non zero in size? Have you checked that the load file is populating your accountlist? The code looks OK on first inspection, so we need to do a bit more detailed digging. I would definitely tidy it up accoding to the previous suggestions, in particular the spurious open(store('w') in the loadfile should be removed, its doing no good and could be causing harm... And using a format string defined at the top of the code and then reused in each function would improve consistency, maintainability and performance. Good luck Alan G. >>> Consider % formatting for the outputs as in: >>> print "%s\t $%2f\n" % (account, accountlist[account]) # >>> instead fmt = "%s\t $.2f\n" .... print fmt % (account,accountList[account]) >>>> def load_file(ac): >>>> import os >>>> import pickle >>>> filename = 'accounts.txt' >>>> if os.path.exists(filename): >>>> store = open(filename, 'r') >>>> ac = pickle.load(store) >>>> else: >>>> store = open(filename, 'w') The else bit does nothing useful. From baiju.m.mail at gmail.com Tue Jun 27 06:34:28 2006 From: baiju.m.mail at gmail.com (Baiju M) Date: Tue, 27 Jun 2006 10:04:28 +0530 Subject: [Tutor] Unit testing In-Reply-To: References: Message-ID: <3171e4820606262134m3e334d5du7853b5a3f3dde7eb@mail.gmail.com> On 6/26/06, Tino Dai wrote: [...] > How would I unit test python GUIs Few weeks back I wrote a small article, may be helpful, so here it is : http://baijum81.livejournal.com/11598.html Regards, Baiju M From tinoloc at gmail.com Tue Jun 27 13:41:32 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 27 Jun 2006 07:41:32 -0400 Subject: [Tutor] Unit testing In-Reply-To: <003901c6999f$9f0a25d0$0301a8c0@XPpro> References: <20060626184236.JPBS16096.outaamta01.mail.tds.net@smtp.tds.net> <003901c6999f$9f0a25d0$0301a8c0@XPpro> Message-ID: On 6/27/06, Alan Gauld wrote: > > > Ok, that leads me to my next question. Currently, I have a class > > that I > > want to unit test, but it contains a semaphore from another class. > > Now, I > > could make the semaphore a global variable, or I bring in the other > > class. > > One violates "good" programming principles and the other violates > > the unit > > testing principles. Is there another way? > > Reconsider your definition of a "Unit" maybe? > A Unit should stand alone, it is the smallest amount of code that can > stand alone. > > If your class relies on another class maybe both classes need to be > considered as a single unit? Or maybe the classes need to be > refactored to > make them less closely coupled? See that what makes this particular coding endevour so exciting. Instead of learning the mechanics of coding, I am starting to gain an understanding of style! I see that only two of my classes are "strongly" link because of a SocketServer call that I make. Other than that I can test all of the other classes independently. And there is one caveat, I will have to make a bunch of semaphores global instead of local to the classes. While I know that there is no hard and fast rule about using global variables, where can I find or can somebody tell me where I can find some guidelines about them (or is this a use common sense rule)? -Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060627/f274c1f7/attachment.htm From tinoloc at gmail.com Tue Jun 27 13:43:38 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 27 Jun 2006 07:43:38 -0400 Subject: [Tutor] Unit testing In-Reply-To: <3171e4820606262134m3e334d5du7853b5a3f3dde7eb@mail.gmail.com> References: <3171e4820606262134m3e334d5du7853b5a3f3dde7eb@mail.gmail.com> Message-ID: On 6/27/06, Baiju M wrote: > > On 6/26/06, Tino Dai wrote: > [...] > > How would I unit test python GUIs > > Few weeks back I wrote a small article, > may be helpful, so here it is : > http://baijum81.livejournal.com/11598.html > > Regards, > Baiju M > Baiju, This is extremely useful for my next coding endeveour. Thank you for contributing to my learning of python. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060627/29f50a84/attachment.html From kent37 at tds.net Tue Jun 27 18:18:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jun 2006 12:18:12 -0400 Subject: [Tutor] Unit testing Message-ID: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> Tino Dai wrote: > And there is one caveat, I > will have to make a bunch of semaphores global instead of local to the > classes. While I know that there is no hard and fast rule about using > global variables, where can I find or can somebody tell me where I can > find some guidelines about them (or is this a use common sense rule)? Main guideline - don't use globals. Fallback rule - don't use globals. Third rule - OK, if you really can't think of any other way, make it a global. :-) Can you pass the semaphore to the class constructor (__init__() method)? What is it about the unit test that pushes you to make it global? Kent From tinoloc at gmail.com Tue Jun 27 20:38:54 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 27 Jun 2006 14:38:54 -0400 Subject: [Tutor] Unit testing In-Reply-To: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> References: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: On 6/27/06, Kent Johnson wrote: > > Tino Dai wrote: > > And there is one caveat, I > > will have to make a bunch of semaphores global instead of local to the > > classes. While I know that there is no hard and fast rule about using > > global variables, where can I find or can somebody tell me where I can > > find some guidelines about them (or is this a use common sense rule)? > > Main guideline - don't use globals. Fallback rule - don't use globals. > Third rule - OK, if you really can't think of any other way, make it a > global. :-) > > Can you pass the semaphore to the class constructor (__init__() method)? > What is it about the unit test that pushes you to make it global? Man, spoil all my fun :) What I'm doing is I have a set.......actually...hang on...are you talking about the program or the unit test? The unit test doesn't have an globals. The program itself does. What the program is doing launching a bunch of threads that are linked together via queues. The reading of the queues by the next stage in the program is controlled by a semaphore. The semaphore will release on one side and acquire on the other side. The data is passed along the different threads until the data is indexed. The semaphores are global so that the unit test can bring in only one class at a time. How I had it before was: the semaphore would be local to the class and subsequent class would all that local semaphore. I think it might be easier if I just shown you. How I had it before: class nameA: sema = threading.semaphore() def __init__(self): def run(self): nameA.sema.release() class nameB: def __init__(self): def run(self): nameA.sema.acquire() How I have it now: semaA = threading.semaphore() class nameA: def __init__(self): def run(self): semaA.release() class nameB: def __init__(self): def run(self): semaA.acquire() Does that make sense. Or is there a better way? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060627/76a87170/attachment.html From tinoloc at gmail.com Tue Jun 27 20:44:42 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 27 Jun 2006 14:44:42 -0400 Subject: [Tutor] Unit testing In-Reply-To: References: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: On 6/27/06, Tino Dai wrote: > > On 6/27/06, Kent Johnson wrote: > > > Tino Dai wrote: > > > And there is one caveat, I > > > will have to make a bunch of semaphores global instead of local to the > > > classes. While I know that there is no hard and fast rule about using > > > global variables, where can I find or can somebody tell me where I can > > > > > find some guidelines about them (or is this a use common sense rule)? > > > > Main guideline - don't use globals. Fallback rule - don't use globals. > > Third rule - OK, if you really can't think of any other way, make it a > > global. :-) > > > > Can you pass the semaphore to the class constructor (__init__() method)? > > What is it about the unit test that pushes you to make it global? > > > Man, spoil all my fun :) What I'm doing is I have a > set.......actually...hang on...are you talking about the program or the unit > test? The unit test doesn't have an globals. The program itself does. What > the program is doing launching a bunch of threads that are linked together > via queues. The reading of the queues by the next stage in the program is > controlled by a semaphore. The semaphore will release on one side and > acquire on the other side. The data is passed along the different threads > until the data is indexed. The semaphores are global so that the unit test > can bring in only one class at a time. How I had it before was: the > semaphore would be local to the class and subsequent class would all that > local semaphore. I think it might be easier if I just shown you. > > How I had it before: > > class nameA: > sema = threading.semaphore() > def __init__(self): > > > def run(self): > > nameA.sema.release () > > class nameB: > def __init__(self): > > > def run(self): > nameA.sema.acquire() > > > > How I have it now: > > semaA = threading.semaphore() > > class nameA: > def __init__(self): > > > def run(self): > > semaA.release() > > class nameB: > def __init__(self): > > > def run(self): > semaA.acquire() > > > > Does that make sense. Or is there a better way? > > -Tino > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060627/3b29a8b8/attachment.html From kent37 at tds.net Tue Jun 27 21:28:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jun 2006 15:28:13 -0400 Subject: [Tutor] Unit testing Message-ID: <20060627192813.YYNC16096.outaamta01.mail.tds.net@smtp.tds.net> Tino Dai wrote: > How I have it now: > > semaA = threading.semaphore() > > class nameA: > def __init__(self): > > > def run(self): > > semaA.release() > > class nameB: > def __init__(self): > > > def run(self): > semaA.acquire() > > > > Does that make sense. Or is there a better way? class nameA: def __init__(self, sema): self.sema = sema def run(self): self.sema.release() class nameB: def __init__(self, sema): self.sema = sema def run(self): self.semaA.acquire() In the client code or the unit test: semaA = threading.semaphore() anA = nameA(semaA) aB = nameB(semaA) anA.run() aB.run() Look, ma, no globals! Kent From rabidpoobear at gmail.com Tue Jun 27 23:11:58 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 27 Jun 2006 16:11:58 -0500 Subject: [Tutor] Unit testing In-Reply-To: <20060627192813.YYNC16096.outaamta01.mail.tds.net@smtp.tds.net> References: <20060627192813.YYNC16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: <44A19F1E.5060700@gmail.com> [snip] > class nameB: > def __init__(self, sema): > self.sema = sema > > > def run(self): > self.semaA.acquire() > > I think here Kent meant self.sema.acquire() [snip] From asdlinux at yahoo.se Wed Jun 28 00:19:19 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Wed, 28 Jun 2006 00:19:19 +0200 Subject: [Tutor] File compression Message-ID: <44A1AEE7.1010904@yahoo.se> Hi Everyone I'm starting to python and i need to write a program that are able to compress a high amount of files and directories into a single file that is later going to be transfered with ftp to a backup storage server. The data is a quite big amount (over 1.5 gb in 40000 files and 1300 directories) so i would like to have high compression like RAR or bz2. What way is the best to approach this? I have looked a bit on zlib but i didn't find a good example that uses it to compress files and directories in one file from python. or perhaps it's simpler to execute a external program, doing the work. I would prefer to use python as much as i can without external apps. Does anyone have a idea how this can be made with python. Thanks Magnus Wirstr?m From mwhite3 at ttsd.k12.or.us Wed Jun 28 00:27:47 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Tue, 27 Jun 2006 15:27:47 -0700 Subject: [Tutor] File compression In-Reply-To: <44A1AEE7.1010904@yahoo.se> References: <44A1AEE7.1010904@yahoo.se> Message-ID: <20060627222746.GB29317@ttsd.k12.or.us> Hi Magnus, I would check out the python tarfile module: http://docs.python.org/lib/module-tarfile.html Looks like it will compress with bzip too! -mtw On Wed, Jun 28, 2006 at 12:19:19AM +0200, Magnus Wirstr?m (asdlinux at yahoo.se) wrote: > Hi Everyone > > I'm starting to python and i need to write a program that are able to > compress a high amount of files and directories into a single file that > is later going to be transfered with ftp to a backup storage server. > The data is a quite big amount (over 1.5 gb in 40000 files and 1300 > directories) so i would like to have high compression like RAR or bz2. > What way is the best to approach this? I have looked a bit on zlib but i > didn't find a good example that uses it to compress files and > directories in one file from python. or perhaps it's simpler to execute > a external program, doing the work. I would prefer to use python as much > as i can without external apps. > > Does anyone have a idea how this can be made with python. > > Thanks > Magnus Wirstr?m > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From clsdaniel at gmail.com Wed Jun 28 00:29:31 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 27 Jun 2006 15:29:31 -0700 Subject: [Tutor] File compression In-Reply-To: <4fae7dfa0606271528x5c415c87s772e94a5b63a704f@mail.gmail.com> References: <44A1AEE7.1010904@yahoo.se> <4fae7dfa0606271528x5c415c87s772e94a5b63a704f@mail.gmail.com> Message-ID: <4fae7dfa0606271529s167de87l5e31dbe1c705be82@mail.gmail.com> I think this is something that can be easily madded with some shell scripting, i suppose you are using Linux or a Unix derivate. In this case tar + bzip2 is your friend, altough for the volume of files i sugest looking at something like rsync or unison and coupling it with cron for automating the online backup. Otherwise i suggest looking at glob module for listing directories and files and the bz2 module, there is also ziplib module, check the docs: http://docs.python.org/lib/someos.html As for ftp, there is ftplib: http://docs.python.org/lib/module-ftplib.html Good luck, regards Carlos Daniel Ruvalcaba On 6/27/06, Magnus Wirstr?m wrote: > Hi Everyone > > I'm starting to python and i need to write a program that are able to > compress a high amount of files and directories into a single file that > is later going to be transfered with ftp to a backup storage server. > The data is a quite big amount (over 1.5 gb in 40000 files and 1300 > directories) so i would like to have high compression like RAR or bz2. > What way is the best to approach this? I have looked a bit on zlib but i > didn't find a good example that uses it to compress files and > directories in one file from python. or perhaps it's simpler to execute > a external program, doing the work. I would prefer to use python as much > as i can without external apps. > > Does anyone have a idea how this can be made with python. > > Thanks > Magnus Wirstr?m > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From python at kapitalisten.no Wed Jun 28 10:51:24 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Wed, 28 Jun 2006 10:51:24 +0200 (CEST) Subject: [Tutor] Threading Message-ID: <41735.193.71.38.142.1151484684.squirrel@mail.sporck.net> Hello. I am trying to learn threading, and found a good example at: http://effbot.org/librarybook/queue.htm (Using the Queue module with a maximum size). It works like a dream as is. But, I added it to a downloading-script I have made before. The difference is that in my version it has a wxPython-gui and download files. The module I use to download works great, so does the gui. So, when I start the downloading, the thread-example downloads from 20-80 files, and a box comes up, saying that Python has crashed. It ask if I would like to shut down or debug. (On Win XP). However, I can see the program run in the background as if nothing has happened. What does cause an error like that? Two threads write to same memoryspace? And, does anyone know of some great sites where I can learn more about threads? I have found a lot, but they are not basic enough. I have no idea what a 'lock' is, as most all sites assumes one should. So, the simpler the better... Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From jeffpeery at yahoo.com Tue Jun 27 22:01:10 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 27 Jun 2006 13:01:10 -0700 (PDT) Subject: [Tutor] treelistctrl help! Message-ID: <20060627200110.71409.qmail@web30501.mail.mud.yahoo.com> hello, I'm having some trouble with treelistctrl in wx python and I was wondering if there is someone who would share their code as an example. thanks! Jeff --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060627/beb5d97a/attachment.html From kent37 at tds.net Wed Jun 28 11:44:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jun 2006 5:44:00 -0400 Subject: [Tutor] Threading Message-ID: <20060628094400.ZAJK6289.outaamta02.mail.tds.net@smtp.tds.net> ?yvind wrote: > And, does anyone know of some great sites where I can learn more about > threads? I have found a lot, but they are not basic enough. I have no idea > what a 'lock' is, as most all sites assumes one should. So, the simpler > the better... "The Little Book of Semaphores" is a good introduction to locks and related threading issues. http://greenteapress.com/semaphores/ Kent From michel.maho at skynet.be Wed Jun 28 16:35:15 2006 From: michel.maho at skynet.be (michel maho) Date: Wed, 28 Jun 2006 16:35:15 +0200 Subject: [Tutor] NumPy Message-ID: <001501c69ac0$129c9d90$660aa8c0@LAPTOP> To all, Can somebody tell me from where to download NumPy easely. Thank you Michel Maho -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060628/9daa011a/attachment.html From dkuhlman at rexx.com Wed Jun 28 19:22:14 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 28 Jun 2006 10:22:14 -0700 Subject: [Tutor] NumPy In-Reply-To: <001501c69ac0$129c9d90$660aa8c0@LAPTOP> References: <001501c69ac0$129c9d90$660aa8c0@LAPTOP> Message-ID: <20060628172214.GB87541@cutter.rexx.com> On Wed, Jun 28, 2006 at 04:35:15PM +0200, michel maho wrote: > To all, > Can somebody tell me from where to download NumPy easely. > Thank you > Michel Maho Well, you probably want SciPy, which is the latest in scientific programming for Python. It's here: http://scipy.org/ There is also a NumPy page. But, I believe that NumPy is built into SciPy. See: - http://www.scipy.org/more_about_SciPy - http://numpy.org/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Wed Jun 28 19:31:00 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 28 Jun 2006 10:31:00 -0700 Subject: [Tutor] File compression In-Reply-To: <20060627222746.GB29317@ttsd.k12.or.us> References: <44A1AEE7.1010904@yahoo.se> <20060627222746.GB29317@ttsd.k12.or.us> Message-ID: <20060628173100.GC87541@cutter.rexx.com> On Tue, Jun 27, 2006 at 03:27:47PM -0700, Matthew White wrote: > Hi Magnus, > > I would check out the python tarfile module: > > http://docs.python.org/lib/module-tarfile.html > > Looks like it will compress with bzip too! Also look at the following: - http://docs.python.org/lib/module-zipfile.html - http://docs.python.org/lib/module-zlib.html - http://docs.python.org/lib/module-gzip.html - http://docs.python.org/lib/module-bz2.html Dave > > -mtw > > On Wed, Jun 28, 2006 at 12:19:19AM +0200, Magnus Wirstr?m (asdlinux at yahoo.se) wrote: > > Hi Everyone > > > > I'm starting to python and i need to write a program that are able to > > compress a high amount of files and directories into a single file that > > is later going to be transfered with ftp to a backup storage server. [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rschroev_nospam_ml at fastmail.fm Wed Jun 28 20:24:50 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 28 Jun 2006 20:24:50 +0200 Subject: [Tutor] Unit testing In-Reply-To: References: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: Tino Dai schreef: > How I have it now: > > semaA = threading.semaphore() > > class nameA: > def __init__(self): > > > def run(self): > > semaA.release() > > class nameB: > def __init__(self): > > > def run(self): > semaA.acquire() > > > > Does that make sense. Or is there a better way? I think it's better to do something like: class nameA: def __init__(self, sema): self.sema = sema def run(self): self.sema.release() class nameB: def __init__(self, sema): self.sema = sema def run(self): self.sema.acquire() Then where you create instances of those classes: sema = threading.semaphore() a = nameA(sema) b = nameB(sema) Maybe you don't even need the semaphore at all: have a look at Queue.Queue, it might do exactly what you need. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From tinoloc at gmail.com Wed Jun 28 22:29:53 2006 From: tinoloc at gmail.com (Tino Dai) Date: Wed, 28 Jun 2006 16:29:53 -0400 Subject: [Tutor] Unit testing In-Reply-To: References: <20060627161812.WBFM16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: > Then where you create instances of those classes: > > sema = threading.semaphore() > a = nameA(sema) > b = nameB(sema) > > > Maybe you don't even need the semaphore at all: have a look at > Queue.Queue, it might do exactly what you need. Ok, I think I'm going to back up and explain what I'm am heading towards. I'm working on an app that fire off a bunch of threads. Each one of these threads in connected via queues to another thread in a sequence like a chain. And how I tell the next stage thread that there is data in the queue is via semaphore. I couldn't come up with a better idea to control is sequence without having to get into patterns (maybe there is a observer pattern like in java for python, I don't know). And presently the global semaphores work (I know it's bad programming practice and it will be fixed - it's on the short list of thing to do). Presently, I'm reading about unit testing because that's a relatively new field to me, and I understand the basics of unit testing. It is the more depth concepts such as how the unit test threads that's not apparent to me (which google doesn't seem to have). Ok, back to searching! -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060628/a1e6be5a/attachment.htm From tinoloc at gmail.com Wed Jun 28 23:04:35 2006 From: tinoloc at gmail.com (Tino Dai) Date: Wed, 28 Jun 2006 17:04:35 -0400 Subject: [Tutor] Unit testing In-Reply-To: <20060627192813.YYNC16096.outaamta01.mail.tds.net@smtp.tds.net> References: <20060627192813.YYNC16096.outaamta01.mail.tds.net@smtp.tds.net> Message-ID: On 6/27/06, Kent Johnson wrote: > > Tino Dai wrote: > > How I have it now: > > > > semaA = threading.semaphore() > > > > class nameA: > > def __init__(self): > > > > > > def run(self): > > > > semaA.release() > > > > class nameB: > > def __init__(self): > > > > > > def run(self): > > semaA.acquire() > > > > > > > > Does that make sense. Or is there a better way? > > class nameA: > def __init__(self, sema): > self.sema = sema > > > def run(self): > > self.sema.release() > > class nameB: > def __init__(self, sema): > self.sema = sema > > > def run(self): > self.semaA.acquire() > > > > In the client code or the unit test: > semaA = threading.semaphore() > anA = nameA(semaA) > aB = nameB(semaA) > anA.run() > aB.run() I got it. I guess it doesn't work like regular variables! Thanks! -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060628/70e9a8df/attachment.htm From asdlinux at yahoo.se Thu Jun 29 00:22:45 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Thu, 29 Jun 2006 00:22:45 +0200 Subject: [Tutor] How to check a files size Message-ID: <44A30135.6010202@yahoo.se> Hi everyone. I would like to ask what is the best way to get the file size on a large file. the operation i'm trying to preform is to copy a large file to another drive using python file I/O commands. perhaps there is a better solution or a module that is doing this more easy? Thanks Magnus Wirstr?m From andrew.arobert at gmail.com Thu Jun 29 00:27:26 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 28 Jun 2006 18:27:26 -0400 Subject: [Tutor] How to check a files size In-Reply-To: <44A30135.6010202@yahoo.se> Message-ID: <000801c69b02$0990eb10$6501a8c0@arobserver> Perhaps this? stat = os.stat(self.file_name) file_size = stat[6] Thank you, Andrew Robert From carroll at tjc.com Thu Jun 29 01:40:06 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 28 Jun 2006 16:40:06 -0700 (PDT) Subject: [Tutor] How to check a files size In-Reply-To: <44A30135.6010202@yahoo.se> Message-ID: On Thu, 29 Jun 2006, [ISO-8859-1] Magnus Wirström wrote: > I would like to ask what is the best way to get the file size on a large > file. filesize = os.stat(filename).st_size From carroll at tjc.com Thu Jun 29 01:47:45 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 28 Jun 2006 16:47:45 -0700 (PDT) Subject: [Tutor] Unit testing In-Reply-To: Message-ID: On Wed, 28 Jun 2006, Tino Dai wrote: > Ok, I think I'm going to back up and explain what I'm am heading towards. > I'm working on an app that fire off a bunch of threads. Each one of these > threads in connected via queues to another thread in a sequence like a > chain. And how I tell the next stage thread that there is data in the queue > is via semaphore. You can just use a series of Queues, where each Queue represents the work being passed from one thread to the other. With respect to each Queue, the producing thread places a work unit onto it with Queue.put; the consumer thread takes a work unit off with Queue.get(True), so it will wait until there's something in the Queue for it to do. And of course, each consumer thread (except the last) is a producer thread to the next consumer thread. You could have the parent start up each thread, passing it the Queue from which it is to read and the Queue to which it is going to write. No globals. I think you'll find that to be much more straightforward than using semaphores. From kent37 at tds.net Thu Jun 29 06:48:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Jun 2006 0:48:46 -0400 Subject: [Tutor] How to check a files size Message-ID: <20060629044846.LBVB6289.outaamta02.mail.tds.net@smtp.tds.net> > From: Magnus Wirstr?m > > Hi everyone. > > I would like to ask what is the best way to get the file size on a large > file. the operation i'm trying to preform is to copy a large file to > another drive using python file I/O commands. perhaps there is a better > solution or a module that is doing this more easy? See shutil.copyfile() Kent From john at fouhy.net Thu Jun 29 06:53:47 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 29 Jun 2006 16:53:47 +1200 Subject: [Tutor] How to check a files size In-Reply-To: <20060629044846.LBVB6289.outaamta02.mail.tds.net@smtp.tds.net> References: <20060629044846.LBVB6289.outaamta02.mail.tds.net@smtp.tds.net> Message-ID: <5e58f2e40606282153n776ad99dt4f47bb1e5ea93e02@mail.gmail.com> On 29/06/06, Kent Johnson wrote: > See shutil.copyfile() Why isn't this function in the os module with the other file commands? -- John. From kent37 at tds.net Thu Jun 29 09:26:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Jun 2006 3:26:13 -0400 Subject: [Tutor] How to check a files size Message-ID: <20060629072613.LQMP6289.outaamta02.mail.tds.net@smtp.tds.net> > From: "John Fouhy" > > On 29/06/06, Kent Johnson wrote: > > See shutil.copyfile() > > Why isn't this function in the os module with the other file commands? I don't know why they are broken up in this way. The glob module also has some file access commands. J Orendorff's path module integrates them and makes a very useful wrapper around file functionality. I use it a lot: http://www.jorendorff.com/articles/python/path/index.html Kent From carroll at tjc.com Thu Jun 29 09:38:42 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 29 Jun 2006 00:38:42 -0700 (PDT) Subject: [Tutor] Unit testing In-Reply-To: Message-ID: On Wed, 28 Jun 2006, Terry Carroll wrote: > On Wed, 28 Jun 2006, Tino Dai wrote: > > > Ok, I think I'm going to back up and explain what I'm am heading towards. > > I'm working on an app that fire off a bunch of threads. Each one of these > > threads in connected via queues to another thread in a sequence like a > > chain. And how I tell the next stage thread that there is data in the queue > > is via semaphore. > > You can just use a series of Queues, where each Queue represents the work > being passed from one thread to the other.... Okay, I was bored tonight, so I cooked up an illustration. Here's an example with five stages. Stage 1 takes a string and fills an input queue with a series of letters from the string. Stages 2-4 do just take a letter off its input queue and move it to its output queue. Stage 5 takes a letter off its input queue and then assembles it into the string and prints it once complete. A token "stop" rather than a letter on the queue is a signal to shut down. Each stage recognizes the token when received, passes it onto its output queue (if any) and then shuts down. Status messages show the progress and threading; a pause of random duration keeps things from being too predictable. Code: import time, Queue, threading, random def randompause(): time.sleep(random.randint(1,5)) def statusmessage(id, workunit): print "%s thread %s, workunit %s" %(time.asctime(), id, workunit) def endmessage(id): print "%s thread %s ending" %(time.asctime(), id) class processor(threading.Thread): def __init__(self, id, inQ=None, outQ=None, inmessage=None): """ id is thread Id: "first" for initial producer, "last" for final consumer inQ is input Q, or None for first producer outQ is outputQ, or None for final consumer """ self.inQ = inQ self.outQ = outQ self.id = id if self.id == "first": self.l = list(inmessage) if self.id == "last": self.message="" threading.Thread.__init__(self) def producer(self): while True: randompause() try: workunit = self.l.pop(0) except IndexError: self.outQ.put("stop") endmessage(self.id) return statusmessage(self.id, workunit) self.outQ.put(workunit) def consumer(self): while True: randompause() workunit = self.inQ.get(True) if workunit == "stop": print "final message:", self.message endmessage(self.id) return else: statusmessage(self.id, workunit) self.message = self.message+workunit def hybrid(self): while True: randompause() workunit = self.inQ.get(True) if workunit == "stop": self.outQ.put(workunit) endmessage(self.id) return else: statusmessage(self.id, workunit) self.outQ.put(workunit) def run(self): if self.id == "first": processor.producer(self) elif self.id == "last": processor.consumer(self) else: processor.hybrid(self) if __name__ == "__main__": q_ab = Queue.Queue() pa = processor(id="first", inmessage="spam", outQ=q_ab) q_bc = Queue.Queue() pb = processor(id="second", inQ=q_ab, outQ=q_bc) q_cd = Queue.Queue() pc = processor(id="third", inQ=q_bc, outQ=q_cd) q_de = Queue.Queue() pd = processor(id="fourth", inQ=q_cd, outQ=q_de) pe = processor(id="last", inQ=q_de) pa.start() pb.start() pc.start() pd.start() pe.start() Result: Thu Jun 29 00:37:30 2006 thread first, workunit s Thu Jun 29 00:37:31 2006 thread first, workunit p Thu Jun 29 00:37:32 2006 thread first, workunit a Thu Jun 29 00:37:33 2006 thread second, workunit s Thu Jun 29 00:37:33 2006 thread third, workunit s Thu Jun 29 00:37:33 2006 thread fourth, workunit s Thu Jun 29 00:37:33 2006 thread last, workunit s Thu Jun 29 00:37:34 2006 thread first, workunit m Thu Jun 29 00:37:37 2006 thread second, workunit p Thu Jun 29 00:37:37 2006 thread third, workunit p Thu Jun 29 00:37:38 2006 thread first ending Thu Jun 29 00:37:38 2006 thread fourth, workunit p Thu Jun 29 00:37:38 2006 thread last, workunit p Thu Jun 29 00:37:41 2006 thread second, workunit a Thu Jun 29 00:37:41 2006 thread third, workunit a Thu Jun 29 00:37:41 2006 thread fourth, workunit a Thu Jun 29 00:37:41 2006 thread last, workunit a Thu Jun 29 00:37:43 2006 thread second, workunit m Thu Jun 29 00:37:43 2006 thread third, workunit m Thu Jun 29 00:37:43 2006 thread fourth, workunit m Thu Jun 29 00:37:44 2006 thread last, workunit m Thu Jun 29 00:37:47 2006 thread second ending Thu Jun 29 00:37:47 2006 thread third ending Thu Jun 29 00:37:48 2006 thread fourth ending final message: spam Thu Jun 29 00:37:48 2006 thread last ending From tinoloc at gmail.com Thu Jun 29 13:28:31 2006 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 29 Jun 2006 07:28:31 -0400 Subject: [Tutor] Unit testing In-Reply-To: References: Message-ID: > Okay, I was bored tonight, so I cooked up an illustration. Thanks for that! Here's an example with five stages. Stage 1 takes a string and fills an > input queue with a series of letters from the string. Stages 2-4 do just > take a letter off its input queue and move it to its output queue. Stage > 5 takes a letter off its input queue and then assembles it into the string > and prints it once complete. I think that I might be missing something in my understanding of python. Between the producer and consumer threads, does the consumer end of the queue sit there and wait for something to come down the queue or is the consumer wake up after a randompause()? Right now, I have the semaphores as gatekeepers to each one of the threads. And until something is in the queue, the thread's semaphore will wait for the semphore to be released by the previous thread. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060629/6a26a8f7/attachment.html From josipl2000 at yahoo.com Thu Jun 29 13:53:58 2006 From: josipl2000 at yahoo.com (josip) Date: Thu, 29 Jun 2006 04:53:58 -0700 (PDT) Subject: [Tutor] python multimedia cyber classrom Message-ID: <20060629115358.67263.qmail@web60811.mail.yahoo.com> Hi, I know that this is not question for this tutor, but someone please help. I tried everething but just not working. I contact Deitel, but they don't know I have Python multimedia cyber classroom cd with book Python how to program. When I run My cyberclassroom I get this error: A Runetime Error has occurred. Do You wish to Debug? Line: 63 Char: 2 Error: 'target_dir' is null or not an object. Code: 0 Url: file://C:\Program Files\Ptg Interactive\htdocs\6737d9\contents\navigation.html this happened when I click on link with javascript:void(0) Thanks! --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060629/59f62535/attachment.html From carroll at tjc.com Thu Jun 29 16:45:42 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 29 Jun 2006 07:45:42 -0700 (PDT) Subject: [Tutor] Threading synchronization (was: Unit testing In-Reply-To: Message-ID: On Thu, 29 Jun 2006, Tino Dai wrote: > Between the producer and consumer threads, does the consumer end of the > queue sit there and wait for something to come down the queue... Yes. The following call: workunit = self.inQ.get(True) means, try to take something off the queue, and if the queue is empty, wait until something is put onto the queue by another thread. That forced waiting ("blocking") is the behavior that I think you want. Another ("non-blocking") form (that I didn't use) could have been: workunit = self.inQ.get() But this one does *not* wait if the queue is empty. It either returns immediately, if there's something in the queue to get; or it raises the Empty exception if there isn't. If you use the non-blocking form, I think you're back to requiring your semaphores. The blocking form is particularly convenient for the type of application you're talking about, I think. (I've never actually had occasion to use the non-blocking form, but then, my needs are usually pretty simple). There's also a temporarily blocking form, e.g.: workunit = self.inQ.get(True, 10) This tries to get something from the queue, and either returns something, or, if nothing's on the queue, waits for up to 10 (in this example) seconds. If something shows up on that time, it wakes up and returns the element off the queue, or raises Empty if the queue is still empty. For our purposes, this has the same problems as the non-blocking form, and I'd avoid it. By the way, do not try to use a combination of the non-blocking form and Queue.empty(), to determine if something's there to get, and get only if it's non-empty. Queue.empty() is not reliable for synchronization purposes. I would consider using Queue.empty() only if, for example, I had some sort of monitoring thread that was periodically checking if there was anything in the queue, solely for the purpose of providing tuning data. (i.e., 90% of the time, a queue is non-empty, so maybe I should consider having more consumer threads on that queue) Even there, I'd probably use qsize() instead (which is also unreliable for synch purposes). You're best of just pretending that Queue.empty(), Queue.full() and Queue.qsize() don't exist, for synchronization purposes. > or is the consumer wake up after a randompause()? The randompause() is *only* to insert random pauses into the execution, so the threads have a little bit of a chance of executing out of order, in essence simulating the threads' work taking some amount of unpredictable time. In practice, it doesn't usually have any effect. You wouldn't use the randompause() in your code, that's just for simulation purposes. > Right now, I have the semaphores as gatekeepers to each one of the > threads. And until something is in the queue, the thread's semaphore > will wait for the semphore to be released by the previous thread. Right. That's an unnecessary complication, requiring that you manage the inter-thread communication. If you instead use blocking queue reads, you won't have to do that. The blocking will make sure that each thread wakes up and does work only when there's work for it. By the way, I'm not a professional programmer (I'm a lawyer, who programs pretty much as a hobby), and it shows in this code. My first cut had some errors because I really don't get namespaces very well. I adjusted it to get it to work, but not very well; very kludgily. Here's a more appropriate version (not that it's a paragon of good code now, but it's not as, um, eccentric, as last night's). I've also changed it to get rid of the id variable being carried in the thread instance. Instead, I use setName to name a thread, and getName to access that name. This is better, because then a meaningful thread name will show up in any exception messages you get (e.g., "Exception in thread first:") import time, Queue, threading, random class processor(threading.Thread): def __init__(self, id, inQ=None, outQ=None, inmessage=None): """ id is thread Id: "first" for initial producer, "last" for final consumer inQ is input Q, or None for first producer outQ is outputQ, or None for final consumer """ self.inQ = inQ self.outQ = outQ if id == "first": self.l = list(inmessage) if id == "last": self.message="" threading.Thread.__init__(self) self.setName(id) def run(self): threadname = self.getName() if threadname == "first": self.producer() elif threadname == "last": self.consumer() else: self.hybrid() def producer(self): while True: self.randompause() try: workunit = self.l.pop(0) except IndexError: self.outQ.put("stop") self.endmessage() return self.statusmessage(workunit) self.outQ.put(workunit) def consumer(self): while True: self.randompause() workunit = self.inQ.get(True) if workunit == "stop": print "final message:", self.message self.endmessage() return else: self.statusmessage(workunit) self.message = self.message+workunit def hybrid(self): while True: self.randompause() workunit = self.inQ.get(True) if workunit == "stop": self.outQ.put(workunit) self.endmessage() return else: self.statusmessage(workunit) self.outQ.put(workunit) def randompause(self): time.sleep(random.randint(1,5)) def statusmessage(self, workunit): print "%s thread %s, workunit %s" %(time.asctime(), self.getName(), workunit) def endmessage(self): print "%s thread %s ending" %(time.asctime(), self.getName()) if __name__ == "__main__": q_ab = Queue.Queue() pa = processor(id="first", inmessage="spam", outQ=q_ab) q_bc = Queue.Queue() pb = processor(id="second", inQ=q_ab, outQ=q_bc) q_cd = Queue.Queue() pc = processor(id="third", inQ=q_bc, outQ=q_cd) q_de = Queue.Queue() pd = processor(id="fourth", inQ=q_cd, outQ=q_de) pe = processor(id="last", inQ=q_de) pa.start() pb.start() pc.start() pd.start() pe.start() From dyoo at hkn.eecs.berkeley.edu Thu Jun 29 20:20:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 29 Jun 2006 11:20:32 -0700 (PDT) Subject: [Tutor] How to check a files size In-Reply-To: <20060629072613.LQMP6289.outaamta02.mail.tds.net@smtp.tds.net> References: <20060629072613.LQMP6289.outaamta02.mail.tds.net@smtp.tds.net> Message-ID: >> Why isn't this function in the os module with the other file commands? > > I don't know why they are broken up in this way. The glob module also > has some file access commands. For the most part, the 'os' module follows the interface functions that C provides to access the operating system. We can think of 'os' as the foundation for other high-level modules like 'shutil'. But there's probably a bit of historical cruft involved here too. os.path.walk() and os.walk() duplicate each other's behavior, but neither can be removed without some effort. Legacy is a hard nut to crack. As another concrete example, we can look at 'fnmatch', whose functions should really live in the 'glob' module. From anilmrn at yahoo.com Thu Jun 29 20:51:14 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 29 Jun 2006 11:51:14 -0700 (PDT) Subject: [Tutor] classes and functions In-Reply-To: Message-ID: <20060629185114.82893.qmail@web55908.mail.re3.yahoo.com> how to use classes and functions in python thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From appara_akp at yahoo.com Thu Jun 29 21:45:06 2006 From: appara_akp at yahoo.com (Apparao Anakapalli) Date: Thu, 29 Jun 2006 12:45:06 -0700 (PDT) Subject: [Tutor] Splitting text Message-ID: <20060629194506.17049.qmail@web55806.mail.re3.yahoo.com> hello all: I have a question and I do not know how I can work it out. I have a file of sequences >a TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' >b CCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACAATTTAA' .... (10 K) pattern = 'ATTTA' I want to find the pattern in the sequence and count. For instance in 'a' there are two 'ATTTA's. How can I do that. One approach tried: import re pat = 'ATTTA' if re.search(pat,a): print 'yes' By counting number of yeses I thought I can answer the question. However, the above approach only looks for the first instance of pat and says yes and moves to next. The other way: a.find(pat) This also looks for first one and reports the position of chracter. Could any one suggest the best way to cound the number of patterns. Thank you appu __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From mwhite3 at ttsd.k12.or.us Thu Jun 29 22:06:54 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Thu, 29 Jun 2006 13:06:54 -0700 Subject: [Tutor] Splitting text In-Reply-To: <20060629194506.17049.qmail@web55806.mail.re3.yahoo.com> References: <20060629194506.17049.qmail@web55806.mail.re3.yahoo.com> Message-ID: <20060629200654.GG29317@ttsd.k12.or.us> Hello Appu, You can use the count() method to find the number of occurances of a substring within a string: >>> a = 'TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' >>> a.count('ATTTA') 2 -mtw On Thu, Jun 29, 2006 at 12:45:06PM -0700, Apparao Anakapalli (appara_akp at yahoo.com) wrote: > hello all: > > I have a question and I do not know how I can work it > out. > > > I have a file of sequences > >a > TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' > >b > CCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACAATTTAA' > .... > > (10 K) > > > pattern = 'ATTTA' > > I want to find the pattern in the sequence and count. > > For instance in 'a' there are two 'ATTTA's. > > How can I do that. > > One approach tried: > import re > > pat = 'ATTTA' > if re.search(pat,a): > print 'yes' > > By counting number of yeses I thought I can answer the > question. However, the above approach only looks for > the first instance of pat and says yes and moves to > next. > > > The other way: > a.find(pat) > > This also looks for first one and reports the position > of chracter. > > > Could any one suggest the best way to cound the number > of patterns. > > > Thank you > appu > > > __________________________________________________ > 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 dkuhlman at rexx.com Thu Jun 29 23:29:10 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 29 Jun 2006 14:29:10 -0700 Subject: [Tutor] Splitting text In-Reply-To: <20060629200654.GG29317@ttsd.k12.or.us> References: <20060629194506.17049.qmail@web55806.mail.re3.yahoo.com> <20060629200654.GG29317@ttsd.k12.or.us> Message-ID: <20060629212910.GB7605@cutter.rexx.com> On Thu, Jun 29, 2006 at 01:06:54PM -0700, Matthew White wrote: > Hello Appu, > > You can use the count() method to find the number of occurances of a > substring within a string: > > >>> a = 'TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' > >>> a.count('ATTTA') > 2 > And, if you need to search for a more complicated pattern, consider using the regular expression module (re): >>> import re >>> a = 'TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' >>> pat = re.compile('ATTTA') >>> pat.findall(a) ['ATTTA', 'ATTTA'] >>> len(pat.findall(a)) 2 Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From carroll at tjc.com Thu Jun 29 23:30:25 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 29 Jun 2006 14:30:25 -0700 (PDT) Subject: [Tutor] Splitting text In-Reply-To: <20060629194506.17049.qmail@web55806.mail.re3.yahoo.com> Message-ID: On Thu, 29 Jun 2006, Apparao Anakapalli wrote: > pattern = 'ATTTA' > > I want to find the pattern in the sequence and count. > > For instance in 'a' there are two 'ATTTA's. use re.findall: >>> import re >>> pat = "ATTTA" >>> rexp=re.compile(pat) >>> a = "TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA" >>> print len(re.findall(rexp,a)) 2 >>> b = "CCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACAATTTAA" >>> print len(re.findall(rexp,b)) 2 Be aware, though, that findall finds non-overlapping occurances; and if overlapping occurances are important to you, it will fail: >>> c = "ATTTATTTA" >>> print len(re.findall(rexp,c)) 1 The following method will count all occurances, even if they overlap: def findall_overlap(regex, seq): resultlist=[] pos=0 while True: result = regex.search(seq, pos) if result is None: break resultlist.append(seq[result.start():result.end()]) pos = result.start()+1 return resultlist For example: >>> print len(findall_overlap(rexp,c)) 2 From alan.gauld at freenet.co.uk Fri Jun 30 00:14:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 29 Jun 2006 23:14:24 +0100 Subject: [Tutor] classes and functions References: <20060629185114.82893.qmail@web55908.mail.re3.yahoo.com> Message-ID: <00bb01c69bc9$61524070$0301a8c0@XPpro> > how to use classes and functions in python > thanks Most of the online tutorials, including mine, will have a section on OOP. Try reading one and if you have specific questions come back here and we will try to answer them. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eklitzke at gmail.com Fri Jun 30 00:43:34 2006 From: eklitzke at gmail.com (Evan Klitzke) Date: Thu, 29 Jun 2006 15:43:34 -0700 Subject: [Tutor] Variables don't change when altered within a loop? Message-ID: Hi, I just started picking up python yesterday, and have already come across something that has me stumped. I want some code that does this: a = foo(a) b = foo(b) c = foo(c) So I try to do this with a for loop, like so: for i in [a, b, c]: i = foo(i) print i # make sure that it worked correctly So far, so good. The problem is that outside the loop, the values aren't changed. For example, print [a, b, c] # outside the loop; the values never actually changed! What is going on? Why aren't the values of my variables changing when I change them inside a loop like this? -- Evan From bgailer at alum.rpi.edu Fri Jun 30 02:22:24 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 29 Jun 2006 17:22:24 -0700 Subject: [Tutor] Variables don't change when altered within a loop? In-Reply-To: References: Message-ID: <44A46EC0.7000801@alum.rpi.edu> Evan Klitzke wrote: > Hi, I just started picking up python yesterday, and have already come > across something that has me stumped. I want some code that does > this: > > a = foo(a) > b = foo(b) > c = foo(c) > > So I try to do this with a for loop, like so: > > for i in [a, b, c]: > i = foo(i) > print i # make sure that it worked correctly > > So far, so good. The problem is that outside the loop, the values > aren't changed. For example, > > print [a, b, c] # outside the loop; the values never actually changed! > > What is going on? Why aren't the values of my variables changing when > I change them inside a loop like this? > The program is not changing a or b or c in the loop. The for statement assigns a to i. The next statement assigns a new value to i. a is not affected. Change print i to print i, a, b, c # and note that a, b, c are unchanged. -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Fri Jun 30 02:27:14 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 29 Jun 2006 17:27:14 -0700 Subject: [Tutor] Variables don't change when altered within a loop? In-Reply-To: References: Message-ID: <44A46FE2.9020709@alum.rpi.edu> Evan Klitzke wrote: > Hi, I just started picking up python yesterday, and have already come > across something that has me stumped. I want some code that does > this: > > a = foo(a) > b = foo(b) > c = foo(c) > > So I try to do this with a for loop, like so: > > for i in [a, b, c]: > i = foo(i) > print i # make sure that it worked correctly > Typically in Python we'd store the values in a list (or dictionary), then apply the function to each element of the list (or dictionary). Python's list comprehension does this nicely: abc = [a, b, c] # from here on we forget the individual names a,b,c and work on list elements instead: abc = [foo(x) for x in abc] # this applies foo to each element of abc, constructs a new list and assigns it to abc. Alternatively we could write: for idx, val in enumerate(abc): abc[idx] = foo(val) > So far, so good. The problem is that outside the loop, the values > aren't changed. For example, > > print [a, b, c] # outside the loop; the values never actually changed! > > What is going on? Why aren't the values of my variables changing when > I change them inside a loop like this? > > -- Evan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From ryan_gm at sbcglobal.net Fri Jun 30 06:23:17 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Thu, 29 Jun 2006 21:23:17 -0700 (PDT) Subject: [Tutor] Wiget Message-ID: <20060630042317.88863.qmail@web80827.mail.yahoo.com> Hey everyone, im just learning to use Tkinter, and im trynig to write a "Guess my number" game program in widget forum but im having some problems, First heres the code im using, Button(self, text = "Sumit", command = self.number_anwser ).grid(row = 4, column = 0, sticky = W) self.response_txt = Text(self, width = 50, height = 5, wrap = WORD) self.response_txt.grid(row = 5, column = 0, columnspan = 4) def number_anwser(self): guess = self.guess_ent.get() guess = int(guess) response = "" tries = 1 if (guess < the_number): response += "Higher" tries += 1 elif (guess > the_number): response += "Lower" tries += 1 else: tries = str(tries) response += "Correct! that was my number, \n" response += "You guessed it in just " response += tries response += " tries!" self.response_txt.delete(0.0, END) self.response_txt.insert(0.0, response) the_number = random.randrange(100) + 1 root = Tk() root.title("Guess my number GUI") app = Application(root) root.mainloop() The problem is at the end where i try and get the number of Tries the user has tried it would just reset everytime the button in clicked, so my question is how would i go about getting the number of times the button is clicked and the anwser is wrong. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060629/2fe04426/attachment.htm From john at fouhy.net Fri Jun 30 07:02:55 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 30 Jun 2006 17:02:55 +1200 Subject: [Tutor] Wiget In-Reply-To: <20060630042317.88863.qmail@web80827.mail.yahoo.com> References: <20060630042317.88863.qmail@web80827.mail.yahoo.com> Message-ID: <5e58f2e40606292202y5510c435i43d9f97c011b8b4f@mail.gmail.com> On 30/06/06, ryan luna wrote: > def number_anwser(self): > guess = self.guess_ent.get() > guess = int(guess) > response = "" > tries = 1 > > if (guess < the_number): > response += "Higher" > tries += 1 > elif (guess > the_number): > response += "Lower" > tries += 1 > else: > tries = str(tries) > response += "Correct! that was my number, \n" > response += "You guessed it in just " > response += tries > response += " tries!" > > self.response_txt.delete(0.0, END) > self.response_txt.insert(0.0, response) This is the function that gets called whenever your button is clicked. So, every time you click the button, "tries" gets set to 1. I assume you have a class derived from Frame -- can you think how to store your "tries" value in your Frame object? (do you know the difference between local variables and object attributes?) -- John. From alan.gauld at freenet.co.uk Fri Jun 30 13:54:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 30 Jun 2006 12:54:46 +0100 Subject: [Tutor] Variables don't change when altered within a loop? References: Message-ID: <001501c69c3b$fe1943f0$0301a8c0@XPpro> > Hi, I just started picking up python yesterday, and have already come > across something that has me stumped. I want some code that does > this: > > a = foo(a) > b = foo(b) > c = foo(c) > > So I try to do this with a for loop, like so: > > for i in [a, b, c]: > i = foo(i) > print i # make sure that it worked correctly > > So far, so good. The problem is that outside the loop, the values > aren't changed. For example, You need to understand the difference between names and variables and values. A variable in Python is a reference to a value (or more correctly an object which has a value) for i in [a,b,c] makes a new variable(name) i which takes on the *values* of a,b,c in turn with each iteration of the loop. i does not take on the name a,b or c, it takes on the value. Thus in the first iteration the variable i will take on the value referenced by a, in the second iteration the value referenced by b and in the third iteration the value referenced by c. The original variables still refer to their original values. i = foo(a) now i will be rebound to the value returned by the function foo() when passed the value of a as an argument. The value refered to by a has not been changed in any way. print i prints the new value associated with i. It changes nothing. in the second iteration the same happens but with i taking on the initial value of b. Lets look at a more concrete example: def foo(x): return x + 10 a,b,c = 1,2,3 code iter 1 iter 2 iter 3 ---------------------------------------------------------------- for i in [a,b,c]: i = 1 i = 2 i = 3 i = foo(i) i = 11 i = 12 i = 13 Note that a,b,c are not changed anywhere in this loop. They retain the original values of 1,2,3. If you wanted to change them you would need to explicitly set their values > What is going on? > Why aren't the values of my variables changing when > I change them inside a loop like this? You are not changing the variables you are changing i which is an entirely different variable! The normal way to do what I think you want is to put the variables in a list or dictionary, then you can loop over that and change the values. Like so: vars = {'a':1, 'b':2,'c':3} def foo(x): return x+10 for key,value in vars.items(): vars[key] = foo(value) print vars HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060630/ceba6517/attachment.htm From alan.gauld at freenet.co.uk Fri Jun 30 14:03:21 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 30 Jun 2006 13:03:21 +0100 Subject: [Tutor] Wiget References: <20060630042317.88863.qmail@web80827.mail.yahoo.com> Message-ID: <002701c69c3d$312f2830$0301a8c0@XPpro> > The problem is at the end where i try and get the number of > Tries the user has tried it would just reset everytime the button > in clicked, so my question is how would i go about getting > the number of times the button is clicked and the anwser is wrong. > def number_anwser(self): > guess = self.guess_ent.get() > guess = int(guess) > response = "" > tries = 1 You are resetting tries to one every time. You need to store tries atthe object level by creating a self.tries in your init method. You can then increment self.tries in the code below. > > if (guess < the_number): > response += "Higher" > tries += 1 > elif (guess > the_number): > response += "Lower" > tries += 1 > else: > tries = str(tries) and this would become tries = str(self.tries) that is, you don't want to convert self.tries to a string! > response += "Correct! that was my number, \n" > response += "You guessed it in just " > response += tries > response += " tries!" > > self.response_txt.delete(0.0, END) > self.response_txt.insert(0.0, response) > HTH Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From patriciap.gu at gmail.com Fri Jun 30 15:58:03 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 30 Jun 2006 13:58:03 +0000 (UTC) Subject: [Tutor] Python urllib (linux) Message-ID: Hi all, I'm doing some failure testing for a python script that uses urllib and urllib2 to open a web page and post data. If the server's apache is down or if I change the ip address the script is trying to contact to be a bogus address, the script handles it prefectly. When I unplug the ethernet cable from my machine (client), the script hangs. Is there a way I can implement a timeout to handle this problem? I'd appreciate any suggestions because I'm clueless. Thanks, Patty From python at venix.com Fri Jun 30 19:44:53 2006 From: python at venix.com (Python) Date: Fri, 30 Jun 2006 13:44:53 -0400 Subject: [Tutor] Python urllib (linux) In-Reply-To: References: Message-ID: <1151689493.10267.693.camel@www.venix.com> On Fri, 2006-06-30 at 13:58 +0000, Patty wrote: > Hi all, > I'm doing some failure testing for a python script that uses urllib and urllib2 > to open a web page and post data. If the server's apache is down or if I change > the ip address the script is trying to contact to be a bogus address, the script > handles it prefectly. When I unplug the ethernet cable from my machine (client), > the script hangs. Is there a way I can implement a timeout to handle this > problem? import socket if not socket.getdefaulttimeout(): socket.setdefaulttimeout(25.0) This sets a timout of 25 seconds. You need to set the timeout BEFORE using a socket. The documentation is in the socket module, should you need more detail. This technique works for simple cases. > I'd appreciate any suggestions because I'm clueless. > Thanks, > Patty > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From carroll at tjc.com Fri Jun 30 19:47:22 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 30 Jun 2006 10:47:22 -0700 (PDT) Subject: [Tutor] Python urllib (linux) In-Reply-To: Message-ID: On Fri, 30 Jun 2006, Patty wrote: > I'm doing some failure testing for a python script that uses urllib and > urllib2 to open a web page and post data.... Is there a way I can > implement a timeout to handle this problem? I don't have any firsth-hand knowledge on this, but http://www.voidspace.org.uk/python/articles/urllib2.shtml says: ------------------------------------ By default the socket module has no timeout and can hang. Currently, the socket timeout is not exposed at the httplib or urllib2 levels. However, you can set the default timeout globally for all sockets using : import socket import urllib2 # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) # this call to urllib2.urlopen now uses the default timeout # we have set in the socket module req = urllib2.Request('http://www.voidspace.org.uk') response = urllib2.urlopen(req) ------------------------------------ Good luck! From patriciap.gu at gmail.com Fri Jun 30 19:54:27 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 30 Jun 2006 17:54:27 +0000 (UTC) Subject: [Tutor] Python urllib (linux) References: <1151689493.10267.693.camel@www.venix.com> Message-ID: Hi again, > > problem? > import socket > if not socket.getdefaulttimeout(): > socket.setdefaulttimeout(25.0) > I'm sorry I forgot to mention that I'm using python 2.2.3, and this version doesn't have those methods. Patty From chris.arndt at web.de Fri Jun 30 21:58:40 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 30 Jun 2006 20:58:40 +0100 Subject: [Tutor] Unit testing In-Reply-To: References: Message-ID: <44A58270.3030803@web.de> Terry Carroll schrieb: > You can just use a series of Queues, where each Queue represents the work > being passed from one thread to the other. If you want, you can have a look at my threadpool module, which implements exactly this pattern. It is basically nothing more than an elaborate example on this technique: http://chrisarndt.de/en/software/python/threadpool/ Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: chris.arndt.vcf Type: text/x-vcard Size: 270 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060630/39a532dd/attachment.vcf From Mike.Hansen at atmel.com Thu Jun 29 22:32:20 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 29 Jun 2006 14:32:20 -0600 Subject: [Tutor] classes and functions Message-ID: <57B026980605A64F9B23484C5659E32E1799E6@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of anil maran > Sent: Thursday, June 29, 2006 12:51 PM > To: Tutor > Subject: [Tutor] classes and functions > > how to use classes and functions in python > thanks What do you need to know? Have you read the tutorial? http://pytut.infogami.com/ The tutorial wiki has some info about functions http://pytut.infogami.com/node6.html There's also some information on classes http://pytut.infogami.com/node11-baseline.html Post specific questions if these links aren't clear enough, and we can probably help. I hope these links help you. Mike http://users.adelphia.net/~mahansen/programming/ From hafsaraza at hotmail.com Fri Jun 30 19:32:57 2006 From: hafsaraza at hotmail.com (Hafsa raza) Date: Fri, 30 Jun 2006 21:32:57 +0400 Subject: [Tutor] saving output in a text file Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060630/d0f477e0/attachment.htm