From kriti_satija at yahoo.co.in Sun Jun 1 07:37:30 2008 From: kriti_satija at yahoo.co.in (Kriti Satija) Date: Sun, 1 Jun 2008 06:37:30 +0100 (BST) Subject: [Tutor] Unsubscribe my membership Message-ID: <965646.94475.qm@web8507.mail.in.yahoo.com> Please Unsubscribe my membership from Python tutorlist. List Password // URL ---- -------- tutor at python.org hariom Planet Earth is in the hot seat. Know more - http://in.search.yahoo.com/search?&fr=na_onnetwork_mail_taglines&ei=UTF-8&rd=r1&p=global+warming From alan.gauld at btinternet.com Sun Jun 1 09:25:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jun 2008 08:25:42 +0100 Subject: [Tutor] Unsubscribe my membership References: <965646.94475.qm@web8507.mail.in.yahoo.com> Message-ID: "Kriti Satija" wrote > Please Unsubscribe my membership from Python You have to do that yourself using the link at the bottom of the message: > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Alan G From dineshbvadhia at hotmail.com Sun Jun 1 12:48:06 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 1 Jun 2008 03:48:06 -0700 Subject: [Tutor] finding special character string Message-ID: A text document has special character strings defined as "." + "set of characters" + ".". For example, ".sup." or ".quadbond." or ".degree." etc. The length of the characters between the opening "." and closing "." is variable. Assuming that you don't know beforehand all possible special character strings, how do you find all such character strings in the text document? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jun 1 13:03:03 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Jun 2008 07:03:03 -0400 Subject: [Tutor] reading a string into an array In-Reply-To: <1c2a2c590805311411i18d85bd4ka76a53bed8663f0c@mail.gmail.com> References: <1c2a2c590805311411i18d85bd4ka76a53bed8663f0c@mail.gmail.com> Message-ID: <484281E7.5090800@gmail.com> Kent Johnson wrote: > On Sat, May 31, 2008 at 3:43 PM, Bryan Fodness wrote: > >> I am trying to read a long string of values separated by a backslash into an >> array of known size. >> >> Here is my attempt, >> >> from numpy import * >> ay, ax = 384, 512 >> a = zeros([ay, ax]) >> for line in open('out.out'): >> data = line.split('\\') >> > > Are you trying to accumulate all the lines into data? If so you should use > data = [] > for line in open('out.out'): > data.extend(line.split('\\')) > > >> k = 0 >> for i in range(ay): >> for j in range(ax): >> a[i, j] = data[k] >> k+=1 >> but, I receive the following error. >> >> Traceback (most recent call last): >> File "C:/Users/bryan/Desktop/dose_array.py", line 13, in >> a[i, j] = data[k] >> ValueError: setting an array element with a sequence. >> > > I think this is because data is a list of strings, not numbers. Change > my line above to > data.extend(int(i) for i in line.split('\\')) > > But you don't have to create your array by copying every item. It is > numpy, after all! I think this will work: > data = [] > for line in open('out.out'): > data.extend(int(i) for i in line.split('\\')) > Even more concise and possibly faster: data = open('out.out').read().replace('\n', '\\').split('\\') > a = array(data) > a.shape = (384, 512) > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Sun Jun 1 13:08:56 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Jun 2008 07:08:56 -0400 Subject: [Tutor] finding special character string In-Reply-To: References: Message-ID: <48428348.6010802@gmail.com> Dinesh B Vadhia wrote: > A text document has special character strings defined as "." + "set of > characters" + ".". For example, ".sup." or ".quadbond." or ".degree." > etc. The length of the characters between the opening "." and closing > "." is variable. > > Assuming that you don't know beforehand all possible special character > strings, how do you find all such character strings in the text document? I'd read through it, looking for periods. If it were "cat.dog.rat.bat", I'd note that .dog. and .rat. meet the criteria and list them. How would you do it? And how does this question relate to Python? -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Sun Jun 1 13:22:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Jun 2008 07:22:50 -0400 Subject: [Tutor] reading a string into an array In-Reply-To: <484281E7.5090800@gmail.com> References: <1c2a2c590805311411i18d85bd4ka76a53bed8663f0c@mail.gmail.com> <484281E7.5090800@gmail.com> Message-ID: <1c2a2c590806010422y4ff5fd80g78fdeb106947e554@mail.gmail.com> On Sun, Jun 1, 2008 at 7:03 AM, bob gailer wrote: > Even more concise and possibly faster: > > data = open('out.out').read().replace('\n', '\\').split('\\') Or use re.split() to split without the replace: import re data = open('out.out').read() data = re.split(r'[\n\\]', data) Kent From kent37 at tds.net Sun Jun 1 13:25:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Jun 2008 07:25:29 -0400 Subject: [Tutor] finding special character string In-Reply-To: References: Message-ID: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> On Sun, Jun 1, 2008 at 6:48 AM, Dinesh B Vadhia wrote: > A text document has special character strings defined as "." + "set of > characters" + ".". For example, ".sup." or ".quadbond." or ".degree." etc. > The length of the characters between the opening "." and closing "." is > variable. > > Assuming that you don't know beforehand all possible special character > strings, how do you find all such character strings in the text document? Assuming the strings are non-overlapping, i.e. the closing "." of one string is not the opening "." of another, you can find them all with import re re.findall(r'\..*?\.', text) Kent From bgailer at gmail.com Sun Jun 1 14:22:41 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Jun 2008 08:22:41 -0400 Subject: [Tutor] finding special character string In-Reply-To: References: Message-ID: <48429491.6030007@gmail.com> Dinesh B Vadhia wrote: > A text document has special character strings defined as "." + "set of > characters" + ".". For example, ".sup." or ".quadbond." or ".degree." > etc. The length of the characters between the opening "." and closing > "." is variable. > > Assuming that you don't know beforehand all possible special character > strings, how do you find all such character strings in the text document? This sounds like a homework assignment. We don't offer solutions to homework, but are glad to help out after you have tried to write a program and run into blocks or specific problems. Are you studying Python? What have you learned that you could apply to this problem? Is the text document available as a computer file or is it on paper? The specification is what I'd call informal rather than precise. I'd ask the author of the specification to make it more precise. I deem this important because endless problems arise when the user does not get what he wanted from the programmer, architect, engineer, relationship, you-name-it, and the reason is the supplier provided what he thought the user wanted. Precise specification helps ensure desired results. Even in human relationships! OK - what next? How do you react to what I said? -- Bob Gailer 919-636-4239 Chapel Hill, NC From dineshbvadhia at hotmail.com Sun Jun 1 15:49:56 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 1 Jun 2008 06:49:56 -0700 Subject: [Tutor] finding special character string References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> Message-ID: Thank-you Kent - it works a treat! ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Sunday, June 01, 2008 4:25 AM Subject: Re: [Tutor] finding special character string On Sun, Jun 1, 2008 at 6:48 AM, Dinesh B Vadhia wrote: > A text document has special character strings defined as "." + "set of > characters" + ".". For example, ".sup." or ".quadbond." or ".degree." etc. > The length of the characters between the opening "." and closing "." is > variable. > > Assuming that you don't know beforehand all possible special character > strings, how do you find all such character strings in the text document? Assuming the strings are non-overlapping, i.e. the closing "." of one string is not the opening "." of another, you can find them all with import re re.findall(r'\..*?\.', text) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 1 19:30:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jun 2008 18:30:37 +0100 Subject: [Tutor] finding special character string References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> Message-ID: "Kent Johnson" wrote > Assuming the strings are non-overlapping, i.e. the closing "." of > one > string is not the opening "." of another, you can find them all with > import re > re.findall(r'\..*?\.', text) Hmm, my regex hopelessness comes to the fore again. Why a *? I would probably have guessed the pattern to be \..+?\. What am I missing? Alan G. From marilyn at deliberate.com Sun Jun 1 20:04:35 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 1 Jun 2008 11:04:35 -0700 (PDT) Subject: [Tutor] finding special character string In-Reply-To: References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> Message-ID: <56810.66.218.47.125.1212343475.squirrel@mail.tigertech.net> On Sun, June 1, 2008 10:30 am, Alan Gauld wrote: > "Kent Johnson" wrote > > >> Assuming the strings are non-overlapping, i.e. the closing "." of >> one string is not the opening "." of another, you can find them all with >> import re re.findall(r'\..*?\.', text) > > Hmm, my regex hopelessness comes to the fore again. > Why a *? > I would probably have guessed the pattern to be > > > \..+?\. > > > What am I missing? I think you're right. Maybe the specification means there should be word boundaries? r"\b\..+?\.\b" This little program includes a function to test regular expressions. I find it helpful and I give it to students. I think such programs exist on the net. #!/usr/bin/env python """This exercise is from the book "Perl by Example" by Ellie Quigley. The exercise in Ellie's book asks us to print the city and state where Norma lives. I used this little program to develop the regular expression.""" import re import sys def ReTest(re_str, data, flags): """Test the re_str against the data with flags. If it doesn't find a hit, try again with one character trimmed off the end, and again, and again, until a hit is found. Then give a report. """ for i in range(len(re_str), 0, -1): try: m = re.search(re_str[:i], data, flags) m.groups() # generate an error except: continue else: print "This much worked:" print re_str[:i] print "It broke here:" print re_str[i:] break def main(): data = """Tommy Savage:408-724-0140:1222 Oxbow Court, Sunnyvale, CA 94087:5/19/66:34200 Lesle Kerstin:408-456-1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600 JonDeLoach:408-253-3122:123 Park St., San Jose, CA 94086:7/25/53:85100 Ephram Hardy:293-259-5395:235 Carlton Lane, Joliet, IL 73858:8/12/20:56700 Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500 Wilhelm Kopf:846-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500 Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700 James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000 Lori Gortz:327-832-5728:3465 Mirlo Street, Peabody, MA 34756:10/2/76:35200 Barbara Kerz:385-573-8326:832 Pnce Drive, Gary, IN 83756:12/15/46:26850 """ re_str = r""" ^%s # Line starts with the name \b # followed by a non-word character (?: # Un-captured group [^:]+? # of non-colons :){2} # followed by a colon, twice x # a mistake!!! \d+? # some digits [ ]+ # one or spaces in [] (?P# capturing a group # named town. This sequence cannot be # split for comments. [^:\d] # with no colons or digits +?) # one or more times \d # a digit ends the match """ % 'Norma' ReTest(re_str, data, re.VERBOSE + re.MULTILINE) if __name__ == '__main__': main() """ $ ./re_test.py This much worked: ^Norma # Line starts with the name \b # followed by a non-word character (?: # Un-captured group [^:]+? # of non-colons :){2} # followed by a colon, twice It broke here: x # a mistake!!! \d+? # some digits [ ]+ # one or spaces in [] (?P# capturing a group # named town. This sequence cannot be # split for comments. [^:\d] # with no colons or digits +?) # one or more times \d # a digit ends the match """ Marilyn Davis > > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Jun 2 01:58:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Jun 2008 19:58:54 -0400 Subject: [Tutor] finding special character string In-Reply-To: <56810.66.218.47.125.1212343475.squirrel@mail.tigertech.net> References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> <56810.66.218.47.125.1212343475.squirrel@mail.tigertech.net> Message-ID: <1c2a2c590806011658u596ae42au890dc8ca6c8aa27f@mail.gmail.com> On Sun, Jun 1, 2008 at 2:04 PM, Marilyn Davis wrote: > On Sun, June 1, 2008 10:30 am, Alan Gauld wrote: > >> "Kent Johnson" wrote >> >> >>> Assuming the strings are non-overlapping, i.e. the closing "." of >>> one string is not the opening "." of another, you can find them all with >>> import re re.findall(r'\..*?\.', text) >> >> Hmm, my regex hopelessness comes to the fore again. >> Why a *? >> I would probably have guessed the pattern to be >> >> >> \..+?\. Mine will find two adjacent periods with no intervening text, yours won't. Whether this makes any difference to the OP, or which is correct, I don't know. > This little program includes a function to test regular expressions. I > find it helpful and I give it to students. I think such programs exist on > the net. I am always surprised at how many regex testers there are, because a simple tester comes with Python. It is called redemo.py; look for it in the Tools/scripts or bin/ directory installed with Python. On my Mac it is at /Library/Frameworks/Python.framework/Versions/2.5/bin/redemo.py. Kent From marilyn at deliberate.com Mon Jun 2 03:41:38 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 1 Jun 2008 18:41:38 -0700 (PDT) Subject: [Tutor] finding special character string In-Reply-To: <1c2a2c590806011658u596ae42au890dc8ca6c8aa27f@mail.gmail.com> References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> <56810.66.218.47.125.1212343475.squirrel@mail.tigertech.net> <1c2a2c590806011658u596ae42au890dc8ca6c8aa27f@mail.gmail.com> Message-ID: <45402.66.218.47.125.1212370898.squirrel@mail.tigertech.net> On Sun, June 1, 2008 4:58 pm, Kent Johnson wrote: > On Sun, Jun 1, 2008 at 2:04 PM, Marilyn Davis > wrote: > >> On Sun, June 1, 2008 10:30 am, Alan Gauld wrote: >> >> >>> "Kent Johnson" wrote >>> >>> >>> >>>> Assuming the strings are non-overlapping, i.e. the closing "." of >>>> one string is not the opening "." of another, you can find them all >>>> with import re re.findall(r'\..*?\.', text) >>> >>> Hmm, my regex hopelessness comes to the fore again. >>> Why a *? >>> I would probably have guessed the pattern to be >>> >>> >>> >>> \..+?\. >>> > > Mine will find two adjacent periods with no intervening text, yours > won't. Whether this makes any difference to the OP, or which is correct, I > don't know. Yeh, we need a better spec. I was wondering if the stuff between the text ought not include white space, or even a word boundary. A character class might be better, if we knew. Anyhow, I think we wore out the student. :^) Marilyn Davis > >> This little program includes a function to test regular expressions. I >> find it helpful and I give it to students. I think such programs >> exist on the net. > > I am always surprised at how many regex testers there are, because a > simple tester comes with Python. It is called redemo.py; look for it in the > Tools/scripts or bin/ directory installed with Python. On my > Mac it is at > /Library/Frameworks/Python.framework/Versions/2.5/bin/redemo.py. > > > Kent From kent37 at tds.net Mon Jun 2 03:56:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Jun 2008 21:56:26 -0400 Subject: [Tutor] finding special character string In-Reply-To: <45402.66.218.47.125.1212370898.squirrel@mail.tigertech.net> References: <1c2a2c590806010425l62688912p3da729a13c290ac7@mail.gmail.com> <56810.66.218.47.125.1212343475.squirrel@mail.tigertech.net> <1c2a2c590806011658u596ae42au890dc8ca6c8aa27f@mail.gmail.com> <45402.66.218.47.125.1212370898.squirrel@mail.tigertech.net> Message-ID: <1c2a2c590806011856x1875665ep690353c7c2ebc3da@mail.gmail.com> On Sun, Jun 1, 2008 at 9:41 PM, Marilyn Davis wrote: > Yeh, we need a better spec. I was wondering if the stuff between the text > ought not include white space, or even a word boundary. A character class > might be better, if we knew. Hmm, yes, my regex will find many ordinary sentences in plain text. > Anyhow, I think we wore out the student. :^) He went away happy after my first reply. Kent From santiagopm at wanadoo.es Mon Jun 2 23:19:56 2008 From: santiagopm at wanadoo.es (Santiago =?iso-8859-1?Q?Pay=E0?= i Miralta) Date: Mon, 02 Jun 2008 23:19:56 +0200 Subject: [Tutor] finding special character string In-Reply-To: (Dinesh B. Vadhia's message of "Sun, 1 Jun 2008 03:48:06 -0700") References: Message-ID: <87fxrva60z.fsf@gorda.chocita> Hi, Try the partition(sep) and rpartition(sep) in a loop. See: http://www.python.org/doc/2.5/whatsnew/other-lang.html Could be funny. Regards, Santiago On Sun, 1 Jun 2008 03:48:06 -0700 "Dinesh B Vadhia" wrote: > A text document has special character strings defined as "." + "set of > characters" + ".". For example, ".sup." or ".quadbond." or ".degree." etc. The > length of the characters between the opening "." and closing "." is variable. > > Assuming that you don't know beforehand all possible special character strings, > how do you find all such character strings in the text document? > > Dinesh > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- From ranaldos at msn.com Tue Jun 3 00:09:45 2008 From: ranaldos at msn.com (RaNaldo Shorter) Date: Mon, 02 Jun 2008 15:09:45 -0700 Subject: [Tutor] Open link in browser from mx Dialog Message-ID: Hello and thanks for you help. If you will, share the path or Internet reference that will allow me to open a Web link from a mxPython dialog window. My project is typical yet I am new to Python and need to learn to accomplish this task. The code is attached. As you can see I've attempted and have not yet the complete path or string. Please, let me thank you again for your help. from RaNaldo RanaldoS at msn.com -------------- next part -------------- A non-text attachment was scrubbed... Name: sample_html_4Ranaldo.py Type: application/octet-stream Size: 1409 bytes Desc: not available URL: From collinsjames9 at gmail.com Mon Jun 2 19:03:40 2008 From: collinsjames9 at gmail.com (james collins) Date: Mon, 2 Jun 2008 13:03:40 -0400 Subject: [Tutor] env variable Message-ID: just wondering about how to set up an env variable for MacPython. How do i become a member? From kent37 at tds.net Tue Jun 3 03:42:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 2 Jun 2008 21:42:35 -0400 Subject: [Tutor] env variable In-Reply-To: References: Message-ID: <1c2a2c590806021842g1306e0f0q94b6e6f15e8de836@mail.gmail.com> On Mon, Jun 2, 2008 at 1:03 PM, james collins wrote: > How do i become a member? Just go to http://mail.python.org/mailman/listinfo/tutor and subscribe to the list. Kent From alan.gauld at btinternet.com Tue Jun 3 01:58:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jun 2008 00:58:05 +0100 Subject: [Tutor] Open link in browser from mx Dialog References: Message-ID: "RaNaldo Shorter" wrote > If you will, share the path or Internet reference that will allow me > to open > a Web link from a mxPython dialog window. I'm not sure what mxPython is but assuming it is closely related to standard Python you might be able to use the standard webbrowser module. Failing that we will need more information about which OS you are using, and possibly which browser you expect to open. > My project is typical Hmm, a typical Python project is hard to define. I've been using Python for nearly 12 years now but have never actually needed to open a web browser, yet... But obviously many do or there would be no browser module in the library! :-) > The code is attached. As you can see I've attempted and have not yet > the > complete path or string. OK, it seems that mxPython is probably a typo for wxPython. The obvious fault in the code is the lack of parentheses after webbrowser.open In particular the docs suggest that the open call expects the url as a parameter. But it would help if you told us what error you get. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jun 3 09:56:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jun 2008 08:56:57 +0100 Subject: [Tutor] env variable References: Message-ID: "james collins" wrote > just wondering about how to set up an env variable for MacPython. You can set an env variable in your bash .profile file using export var=val where var is the name of the variable and val is its value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Tue Jun 3 11:13:02 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 3 Jun 2008 02:13:02 -0700 Subject: [Tutor] finding special character string Message-ID: Yes, I'm happy because I found a non-regex way to solve the problem (see below). No, I'm not a student or worn out but wish I was back at college and partying! Yes, this is an interesting problem and here is the requirement: - A text document contains special words that start and end with a period ("."), the word between the start and end periods contain no punctuation or spaces except a hyphen in some special words. - Examples of special words include ".thrfore.", ".because.", '.music-sharp.", ".music-flat.", ".dbd.", ".vertline.", ".uparw.", ".hoarfrost." etc. - In most cases, the special words have a space (" ") before and after. - In some cases, a special word will be followed by one or two other special words eg. ".dbd..vertline." or ".music-flat..dbd..vertline." - In some cases, a special word will be followed by an ordinary word (with or without punctuation) eg. ".music-flat.mozart" or ".vertline.isn't" - A special word followed by an ordinary word (with or without punctuation) could be the end of a sentence and hence have a full-stop (".") eg. ".music-flat.mozart." or ".vertline.isn't." - The number of characters in a special word excluding the two periods is > 1 - Find and remove all special words from the text document (by processing one line at a time) How did I solve it? I found a list of all the special words, created a set of special words and then checked if each word in the text belonged to the set of special words. If we assume that the list of special words doesn't exist then the problem is interesting in itself to solve. Cheers! Dinesh -------------------------------------------------------------------------------- Date: Sun, 1 Jun 2008 21:56:26 -0400 From: "Kent Johnson" Subject: Re: [Tutor] finding special character string To: "Marilyn Davis" Cc: tutor at python.org Message-ID: <1c2a2c590806011856x1875665ep690353c7c2ebc3da at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Sun, Jun 1, 2008 at 9:41 PM, Marilyn Davis wrote: > Yeh, we need a better spec. I was wondering if the stuff between the text > ought not include white space, or even a word boundary. A character class > might be better, if we knew. Hmm, yes, my regex will find many ordinary sentences in plain text. > Anyhow, I think we wore out the student. :^) He went away happy after my first reply. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jun 3 11:47:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Jun 2008 05:47:23 -0400 Subject: [Tutor] finding special character string In-Reply-To: References: Message-ID: <1c2a2c590806030247m2b021349w91d78ea1b3c7b4b2@mail.gmail.com> On Tue, Jun 3, 2008 at 5:13 AM, Dinesh B Vadhia wrote: > Yes, I'm happy because I found a non-regex way to solve the problem (see > below). > How did I solve it? I found a list of all the special words, created a set > of special words and then checked if each word in the text belonged to the > set of special words. If we assume that the list of special words doesn't > exist then the problem is interesting in itself to solve. Even with the list of special words I would still use a regex and process the whole file at once. If the list is in the variable 'specials' and the file data in 'data', then build and apply a regex like this: import re specialsRe = re.compile('|'.join(r'\.%s\.' % re.escape(s) for s in specials)) data = specialsRe.sub(data, '') The regex just escapes any special chars in the words, brackets them with "." and joins them with "|" in between. But without the list of specials it is still easy with a regex. This works on your explanatory text: data = re.sub(r'\.[a-zA-Z-]{2,}\.', '', data) Kent From michael at yavarsity.com Tue Jun 3 15:18:39 2008 From: michael at yavarsity.com (Michael yaV) Date: Tue, 3 Jun 2008 09:18:39 -0400 Subject: [Tutor] How to Think Like a Computer Scientist... Message-ID: <302704B2-FD95-4AE1-9CED-98E98095A5F8@yavarsity.com> The green horn that I am, last week I started to go through the "How to Think Like a Computer Scientist" tutorial. I have gotten to Chapter 3 --Functions' 3.8 Exercises. I think I have the 1st exercise correct but I'm really not sure. Is their any answer sheet I can go to to make sure i am getting the right answers the correct way? Thanks for any help, Michael From andreas at kostyrka.org Tue Jun 3 17:23:33 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 3 Jun 2008 17:23:33 +0200 Subject: [Tutor] How to Think Like a Computer Scientist... In-Reply-To: <302704B2-FD95-4AE1-9CED-98E98095A5F8@yavarsity.com> References: <302704B2-FD95-4AE1-9CED-98E98095A5F8@yavarsity.com> Message-ID: <200806031723.33747.andreas@kostyrka.org> On Tuesday 03 June 2008 15:18:39 Michael yaV wrote: > The green horn that I am, last week I started to go through the "How > to Think Like a Computer Scientist" tutorial. I have gotten to Chapter > 3 --Functions' 3.8 Exercises. I think I have the 1st exercise correct > but I'm really not sure. Is their any answer sheet I can go to to make > sure i am getting the right answers the correct way? > > Thanks for any help, Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Not that I would know personally, but you are welcome to post the question and your answer to this mailing list. Or if it's to big, links to it. Andreas From nkemonye at hotmail.com Tue Jun 3 20:53:37 2008 From: nkemonye at hotmail.com (nkem onyemachi) Date: Tue, 3 Jun 2008 19:53:37 +0100 Subject: [Tutor] How to think like a computerscientist Message-ID: Well did you run it with the interpreter cos that you sound like you did not and it is quite simple _____________________________ Sent from my phone using flurry - Get free mobile email and news at: http://www.flurry.com _________________________________________________________________ News, entertainment and everything you care about at Live.com. Get it now! http://www.live.com/getstarted.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Tue Jun 3 21:24:21 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 3 Jun 2008 12:24:21 -0700 (PDT) Subject: [Tutor] finding special character string In-Reply-To: References: Message-ID: <16984.66.201.58.8.1212521061.squirrel@mail.tigertech.net> On Tue, June 3, 2008 2:13 am, Dinesh B Vadhia wrote: > Yes, I'm happy because I found a non-regex way to solve the problem (see > below). > > No, I'm not a student or worn out but wish I was back at college and > partying! > > Yes, this is an interesting problem and here is the requirement: > > > - A text document contains special words that start and end with a period > ("."), the word between the start and end periods contain no punctuation > or spaces except a hyphen in some special words. - Examples of special > words include ".thrfore.", ".because.", '.music-sharp.", ".music-flat.", > ".dbd.", ".vertline.", ".uparw.", ".hoarfrost." etc. > - In most cases, the special words have a space (" ") before and after. Here I might think that I should capture leading and trailing white space and be careful to not put two spaces in a row in the result. > - In some cases, a special word will be followed by one or two other > special words eg. ".dbd..vertline." or ".music-flat..dbd..vertline." - In > some cases, a special word will be followed by an ordinary word (with or > without punctuation) eg. ".music-flat.mozart" or ".vertline.isn't" - A > special word followed by an ordinary word (with or without punctuation) > could be the end of a sentence and hence have a full-stop (".") eg. > ".music-flat.mozart." or ".vertline.isn't." > - The number of characters in a special word excluding the two periods is > > 1 > - Find and remove all special words from the text document (by processing > one line at a time) > > How did I solve it? I found a list of all the special words, created a And here I might think that finding a list of all special words, unless you found them using Python on the text file, isn't quite what was intended. It is really hard to write specifications. It seems like you learned a lot! Marilyn Davis > set of special words and then checked if each word in the text belonged > to the set of special words. If we assume that the list of special words > doesn't exist then the problem is interesting in itself to solve. > > Cheers! > > > Dinesh > > > > ------------------------------------------------------------------------- > ------- > > > Date: Sun, 1 Jun 2008 21:56:26 -0400 > From: "Kent Johnson" > Subject: Re: [Tutor] finding special character string > To: "Marilyn Davis" > Cc: tutor at python.org > Message-ID: > <1c2a2c590806011856x1875665ep690353c7c2ebc3da at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > > On Sun, Jun 1, 2008 at 9:41 PM, Marilyn Davis > wrote: > > >> Yeh, we need a better spec. I was wondering if the stuff between the >> text ought not include white space, or even a word boundary. A >> character class might be better, if we knew. > > Hmm, yes, my regex will find many ordinary sentences in plain text. > > >> Anyhow, I think we wore out the student. :^) >> > > He went away happy after my first reply. > > > Kent From collinsjames9 at gmail.com Tue Jun 3 21:39:18 2008 From: collinsjames9 at gmail.com (james collins) Date: Tue, 3 Jun 2008 15:39:18 -0400 Subject: [Tutor] env variable Message-ID: <73B41197-7FB5-465D-B4FA-9F3737B830AE@gmail.com> have a question about setting up an env. variable. i own a macbook pro laptop running mac os x 10.5.2. i downloaded MacPython 2.5. my problem is that when i go to run a script which i have saved in my home directory in a folder which i called python, my IDLE does not recognize the script which i am trying to import, here is a sample session in my IDLE: >>> import script1 Traceback (most recent call last): File "", line 1, in import script1 ImportError: No module named script1 i was told that i have to set the env. variable path, so my computer knows where to find the scripts i am working on. one solution i was told about which worked was to type in the following code when i start my IDLE: import sys sys.path.append( "/users/jamescollins/python/" ) this worked for me, but i thought there should be a more elegant way to import scripts i am working on, than to have to write this code in each time i want to run a script. i also was told of a way to modify my python path env variable, and this is what i want to do, but i am unsure of how to do this? I was told: "Or you can modify python path by setting PYTHONPATH env variable. In bash shell: $ export PYTHONPATH=.:$HOME/python:$PYTHONPATH Usually one does it by including the above line in .bash_profile file." i went into terminal, which is mac os x command line, and opened .bash_profile file into textedit. the file was hidden but i was able to open it, i then tried adding the line which i was told to add: $ export PYTHONPATH=.:$HOME/python:$PYTHONPATH but when i went into my python IDLE i got error messages to the extent that my IDLE couldn't find the scripts i was trying to import. one thing i will mention is that i added the above line exactly as it is written above. can anyone help me set up the path so my computer looks in a certain directory for the scripts i am working on? -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Tue Jun 3 23:45:06 2008 From: washakie at gmail.com (washakie) Date: Tue, 3 Jun 2008 14:45:06 -0700 (PDT) Subject: [Tutor] create numpy array from list of strings Message-ID: <17634509.post@talk.nabble.com> Hello, I have a list of strings: data = [ '33386.47 2.22 -1.11 0.43' '33386.67 3.33 -1.23 0.54' ... '46728.47 0.1 -1.87 -0.54' '46728.47 9.7 5.68 0.38' '46729.47 -0.17 -0.47 0.23'] I wish to convert it to a numpy array of floats. How do I accomplish this? THanks!! -- View this message in context: http://www.nabble.com/create-numpy-array-from-list-of-strings-tp17634509p17634509.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Wed Jun 4 00:23:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jun 2008 23:23:09 +0100 Subject: [Tutor] env variable References: <73B41197-7FB5-465D-B4FA-9F3737B830AE@gmail.com> Message-ID: "james collins" wrote > home directory in a folder which i called python, my IDLE does not > recognize the script which i am trying to import, here is a sample > session in my IDLE: You need to set PYTHONPATH not PATH PATH tells the OS where to find executables like python PYTHONPATH tells Python where to find modules to import > one solution i was told about which worked was to type in the > following code when i start my IDLE: > > import sys > sys.path.append( "/users/jamescollins/python/" ) Thats fine as a temporary measure but you would need to do it in every script. As you discovered! > "Or you can modify python path by setting PYTHONPATH env variable. > In > bash shell: > $ export PYTHONPATH=.:$HOME/python:$PYTHONPATH Note this says "in the bash shell" The $ at the beginning is the conventional way of describing prompt displayed by bash. You do not type it in. > $ export PYTHONPATH=.:$HOME/python:$PYTHONPATH > > but when i went into my python IDLE i got error messages to the > extent > that my IDLE couldn't find the scripts i was trying to import. one > thing i will mention is that i added the above line exactly as it is > written above. Enter the line in your profile as: export PYTHONPATH=.:$HOME/python:$PYTHONPATH Which tells Python to look for modules in the current directory(the dot), in the python folder of your home directory ($HOME/python) and in whatever folders were already set up ($PYTHONPATH) The 'export' simply makes the setting visible outside of the profile script. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Wed Jun 4 00:26:01 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Jun 2008 18:26:01 -0400 Subject: [Tutor] create numpy array from list of strings In-Reply-To: <17634509.post@talk.nabble.com> References: <17634509.post@talk.nabble.com> Message-ID: <4845C4F9.5000000@gmail.com> washakie wrote: > Hello, I have a list of strings: > data = > [ '33386.47 2.22 -1.11 0.43' > '33386.67 3.33 -1.23 0.54' > ... > '46728.47 0.1 -1.87 -0.54' > '46728.47 9.7 5.68 0.38' > '46729.47 -0.17 -0.47 0.23'] > If the above is intended to be Python code, it has problems. Rewrite it thusly?: data = [ '33386.47 2.22 -1.11 0.43', '33386.67 3.33 -1.23 0.54', # ... '46728.47 0.1 -1.87 -0.54', '46728.47 9.7 5.68 0.38', '46729.47 -0.17 -0.47 0.23'] Then let a numpy expert finish the task. -- Bob Gailer 919-636-4239 Chapel Hill, NC From dyoo at cs.wpi.edu Wed Jun 4 00:04:22 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 3 Jun 2008 18:04:22 -0400 (EDT) Subject: [Tutor] create numpy array from list of strings In-Reply-To: <17634509.post@talk.nabble.com> References: <17634509.post@talk.nabble.com> Message-ID: > Hello, I have a list of strings: > data = > [ '33386.47 2.22 -1.11 0.43' > '33386.67 3.33 -1.23 0.54' > ... > '46728.47 0.1 -1.87 -0.54' > '46728.47 9.7 5.68 0.38' > '46729.47 -0.17 -0.47 0.23'] > > I wish to convert it to a numpy array of floats. How do I accomplish > this? Pointers: * Give a name to the thing you're trying to define. It sounds like you're trying to define a function that takes a list of strings and converts it to a numpy array. Give it a good, concise name. For example, "convertStringsToNumpyArray" might be a bit wordy, but it works. * Write out your expectations on what this function will do on small examples. That way, once you have the function written, you can test it. For example: convertStringsToNumpyArray['42'] ==> the singleton array containing 42 convertStringToNumpyArray['3 1 4'] ==> the row array containing 3, 1, and 4. Cook up a few more examples for yourself. * Try to simplify the problem slightly. If you had a list of the number rows, would you be able to turn that into a numpy array? i.e. if you were given: data = [[1, 2], ## row 1 [3, 4], ## row 2 ] could you write a function that consumes that data and converts it into a numpy array? From stevemiddendorf at hotmail.com Wed Jun 4 00:34:20 2008 From: stevemiddendorf at hotmail.com (Steve Middendorf) Date: Wed, 4 Jun 2008 08:34:20 +1000 Subject: [Tutor] env variable In-Reply-To: <73B41197-7FB5-465D-B4FA-9F3737B830AE@gmail.com> References: <73B41197-7FB5-465D-B4FA-9F3737B830AE@gmail.com> Message-ID: ________________________________ > From: collinsjames9 at gmail.com > To: tutor at python.org > Date: Tue, 3 Jun 2008 15:39:18 -0400 > Subject: [Tutor] env variable > > have a question about setting up an env. variable. > i own a macbook pro laptop running mac os x 10.5.2. > i downloaded MacPython 2.5. > my problem is that when i go to run a script which i have saved in my home directory in a folder which i called python, my IDLE does not recognize the script which i am trying to import, here is a sample session in my IDLE: > >>>> import script1 > > Traceback (most recent call last): > File " I found this solution at www.keitr.com/tutorials/macosx_path Adding directories to the Mac OS X PATH variable by Keito Uchiyama This tutorial shows you how to add directories to your Mac OS X PATH variable. Open the Terminal application. It can be found in the Utilities directory inside the Applications directory. Type the following: echo 'export PATH=YOURPATHHERE:$PATH'>> ~/.profile, replacing "YOURPATHHERE" with the name of the directory you want to add. Make certain that you use ">>" instead of one ">". Hit Enter. Close the Terminal and reopen. Your new Terminal session should now use the new PATH. _________________________________________________________________ Never miss another e-mail with Hotmail on your mobile. http://www.livelife.ninemsn.com.au/article.aspx?id=343869 From washakie at gmail.com Wed Jun 4 01:03:52 2008 From: washakie at gmail.com (washakie) Date: Tue, 3 Jun 2008 16:03:52 -0700 (PDT) Subject: [Tutor] create numpy array from list of strings In-Reply-To: References: <17634509.post@talk.nabble.com> Message-ID: <17635787.post@talk.nabble.com> Thanks, I'm not really trying to create a function. I actually thought this would be as simple as the 'load' command to get the data in from a file. But I just couldn't find the documentation online to do it once i have the data already 'inside' of python as a list. So, my options are: 1) write the data block out to a temporary file and read it in using 'load' - which is really simple (see: http://www.scipy.org/Cookbook/InputOutput) 2) I've done the following, but I doubt it is the most efficient method: tempDATA=[] for i in data[stind:-1]: #this is the data block from the file tempDATA.append([float(j) for j in i.split()]) outdata=array(tempDATA).transpose() Is there a better way? -- View this message in context: http://www.nabble.com/create-numpy-array-from-list-of-strings-tp17634509p17635787.html Sent from the Python - tutor mailing list archive at Nabble.com. From dyoo at cs.wpi.edu Wed Jun 4 02:56:09 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 3 Jun 2008 20:56:09 -0400 (EDT) Subject: [Tutor] create numpy array from list of strings In-Reply-To: <17635787.post@talk.nabble.com> References: <17634509.post@talk.nabble.com> <17635787.post@talk.nabble.com> Message-ID: > I actually thought this would be as simple as the 'load' command to get > the data in from a file. But I just couldn't find the documentation > online to do it once i have the data already 'inside' of python as a > list. So, my options are: Hello, If you already have the values as a list of rows, where each row is a list of numbers, then the 'array' function may be appropriate. http://www.scipy.org/Cookbook/BuildingArrays I see that you already know about array() from your second solution. > 1) write the data block out to a temporary file and read it in using 'load' > - which is really simple (see: http://www.scipy.org/Cookbook/InputOutput) Alhtough it's simple, if you can avoid I/O, do so: touching disk can raise its own problems. I like your second approach much better. > 2) I've done the following, but I doubt it is the most efficient method: > > tempDATA=[] > for i in data[stind:-1]: #this is the data block from the file > tempDATA.append([float(j) for j in i.split()]) > > outdata=array(tempDATA).transpose() > > Is there a better way? This looks good. I'm not sure I understand the transpose() call, although I suspect it's because that's the next step you want to do to process your array. But just to follow up on what you said earlier: > I'm not really trying to create a function. It's actually very easy to turn what you have there into a function. I'd recommend doing so. Here's what it looks like. ####################################################### def convert(data): tempDATA = [] for i in data: tempDATA.append([float(j) for j in i.split()]) return array(tempDATA) ####################################################### To get back the same behavior as your code above, you can call this function as: outdata = convert(data[stind:-1]).transpose() Functions give you a way to bundle up a collection of related operations. More importantly, that 'tempDATA' variable doesn't stick around hanging out in space: it only lives in the convert() function. From listas.condhor at gmail.com Wed Jun 4 04:15:44 2008 From: listas.condhor at gmail.com (Laureano Arcanio) Date: Tue, 3 Jun 2008 23:15:44 -0300 Subject: [Tutor] Intercepting methods calls Message-ID: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> Hi all Is there any way to intercept calls to methods ? like the __setattribute__ medthod does ? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Wed Jun 4 04:35:22 2008 From: washakie at gmail.com (washakie) Date: Tue, 3 Jun 2008 19:35:22 -0700 (PDT) Subject: [Tutor] create numpy array from list of strings In-Reply-To: References: <17634509.post@talk.nabble.com> <17635787.post@talk.nabble.com> Message-ID: <17637945.post@talk.nabble.com> Thank you again. I can see your point about not wanting the tempDATA var hanging around, so I guess this is better as a function. And yes, the transpose is for the 'next step' - sorry if that cause anyone confusion. Danny Yoo-3 wrote: > > > If you already have the values as a list of rows, where each row is a list > of numbers, then the 'array' function may be appropriate. > > http://www.scipy.org/Cookbook/BuildingArrays > > I see that you already know about array() from your second solution. > > Yes, I printed that out today to have a closer look at! "Danny Yoo-3 wrote: > > Alhtough it's simple, if you can avoid I/O, do so: touching disk can raise > its own problems. I like your second approach much better. > > I know, besides, it certainly seems to slow things down - particularly with large arrays / files. "Danny Yoo-3 wrote: > > >> 2) I've done the following, but I doubt it is the most efficient method: >> >> >> Is there a better way? > > This looks good. > > Wow, really? I guess I assumed there would be a way to 'nest' list comprehension somehow. "Danny Yoo-3 wrote: > > It's actually very easy to turn what you have there into a function. I'd > recommend doing so. Here's what it looks like. > > ####################################################### > def convert(data): > tempDATA = [] > for i in data: > tempDATA.append([float(j) for j in i.split()]) > return array(tempDATA) > ####################################################### > > To get back the same behavior as your code above, you can call this > function as: > > outdata = convert(data[stind:-1]).transpose() > > Functions give you a way to bundle up a collection of related operations. > More importantly, that 'tempDATA' variable doesn't stick around hanging > out in space: it only lives in the convert() function. > Good point! Thanks again! -- View this message in context: http://www.nabble.com/create-numpy-array-from-list-of-strings-tp17634509p17637945.html Sent from the Python - tutor mailing list archive at Nabble.com. From dyoo at cs.wpi.edu Wed Jun 4 05:24:35 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 3 Jun 2008 23:24:35 -0400 (EDT) Subject: [Tutor] create numpy array from list of strings In-Reply-To: <17637945.post@talk.nabble.com> References: <17634509.post@talk.nabble.com> <17635787.post@talk.nabble.com> <17637945.post@talk.nabble.com> Message-ID: On Tue, 3 Jun 2008, washakie wrote: >>> 2) I've done the following, but I doubt it is the most efficient method: >>> >>> Is there a better way? >> >> This looks good. > > Wow, really? I guess I assumed there would be a way to 'nest' list > comprehension somehow. I'm assuming you already have good familiarity with list comprehensions. Given that you've already used to them, if what you're trying to do doesn't immediately admit a solution with list comprehensions, that's usually a good mental warning sign: don't! >> "Danny Yoo-3 wrote: >> >> Alhtough it's simple, if you can avoid I/O, do so: touching disk can >> raise its own problems. I like your second approach much better. > > I know, besides, it certainly seems to slow things down - particularly > with large arrays / files. It's because disk access is much slower than memory access. That's why you want to avoid touching disk unless you really need to: it will kill your program's performance. Other general reasons include: * You may need to worry about access control. Do you have write permission to the tmp directory? Do you care that other people can see it? * You may accidently fill up the disk. * Concurrency issue: If two copies of your scripts are running at the same time, will bad things happen? The 'tmpfile' module tries to deal with this by making unique names, but it still can be a problem. > "Danny Yoo-3 wrote: By the way, I'm flattered. Can I be the new Number 2 next time? From alan.gauld at btinternet.com Wed Jun 4 07:16:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jun 2008 06:16:49 +0100 Subject: [Tutor] Intercepting methods calls References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> Message-ID: "Laureano Arcanio" wrote > Is there any way to intercept calls to methods ? like the > __setattribute__ > medthod does ? There are several variations on how to do that kind of thing. Can you give us some more background on what you are trying to achieve that makes you need to do that? Then we can offer advice as to the best approach. Alan G From marilyn at deliberate.com Wed Jun 4 07:41:49 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 3 Jun 2008 22:41:49 -0700 (PDT) Subject: [Tutor] Intercepting methods calls In-Reply-To: References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> Message-ID: <50444.66.218.47.125.1212558109.squirrel@mail.tigertech.net> On Tue, June 3, 2008 10:16 pm, Alan Gauld wrote: > "Laureano Arcanio" wrote > > >> Is there any way to intercept calls to methods ? like the >> __setattribute__ >> medthod does ? > > There are several variations on how to do that kind of thing. > Can you give us some more background on what you are > trying to achieve that makes you need to do that? Great question, Alan. But, whatever the answer, I'd like to see the variations listed, if you have time. Showing my ignorance, I can only think of inheritance/overriding. Or maybe I don't understand the question. Marilyn Davis > > Then we can offer advice as to the best approach. > > > Alan G > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Wed Jun 4 10:09:41 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 4 Jun 2008 10:09:41 +0200 Subject: [Tutor] Intercepting methods calls In-Reply-To: <50444.66.218.47.125.1212558109.squirrel@mail.tigertech.net> References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> <50444.66.218.47.125.1212558109.squirrel@mail.tigertech.net> Message-ID: <200806041009.44765.andreas@kostyrka.org> On Wednesday 04 June 2008 07:41:49 Marilyn Davis wrote: > On Tue, June 3, 2008 10:16 pm, Alan Gauld wrote: > > "Laureano Arcanio" wrote > > > >> Is there any way to intercept calls to methods ? like the > >> __setattribute__ > >> medthod does ? > > > > There are several variations on how to do that kind of thing. > > Can you give us some more background on what you are > > trying to achieve that makes you need to do that? > > Great question, Alan. But, whatever the answer, I'd like to see the > variations listed, if you have time. Well, let's start the ball rolling then. __getattribute__ __getattr__ Metaclasses decorators properties __init__ The basic working is that you've got a function, and that get's wrapped. In the "normal case", the function is a (__get__ only) property, and this __get__ is what makes Bound/Unbound methods out of a function object. (you can check it out, SomeClass.method versus SomeClass.__dict__["method"] versus SomeClass().method) Now the above listing is basically a list of points were you can effect a change of behaviour. One of the classical uses for that messy business is usually some kind of automatically constructed "proxy" class. (Proxy is rather general, e.g. RPC, or ORM classes come to mind) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From kent37 at tds.net Wed Jun 4 12:34:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Jun 2008 06:34:16 -0400 Subject: [Tutor] create numpy array from list of strings In-Reply-To: <17637945.post@talk.nabble.com> References: <17634509.post@talk.nabble.com> <17635787.post@talk.nabble.com> <17637945.post@talk.nabble.com> Message-ID: <1c2a2c590806040334i2afc004eg3c141de2cfab6c81@mail.gmail.com> On Tue, Jun 3, 2008 at 10:35 PM, washakie wrote: > I guess I assumed there would be a way to 'nest' list > comprehension somehow. Sure, just nest them. You have: tempDATA=[] for i in data[stind:-1]: tempDATA.append([float(j) for j in i.split()]) This has the form tempDATA=[] for i in sequence: tempDATA.append(expr(i)) Code in this form can become the list comprehension tempDATA = [ expr(i) for i in sequence ] which in your case becomes tempDATA=[ [float(j) for j in i.split()] for i in data[stind:-1] ] You can also have multiple loops in a single list comp; if you wanted a single list of floats, instead of a list of lists, you could write tempDATA=[ float(j) for i in data[stind:-1] for j in i.split() ] Note that the order of 'for' clauses is reversed; it is the same order as you would use with nested for loops. Kent From snovak at snovak.com Wed Jun 4 13:53:14 2008 From: snovak at snovak.com (Sean Novak) Date: Wed, 4 Jun 2008 07:53:14 -0400 Subject: [Tutor] turbo gears Message-ID: <64439ACD-40D2-400B-81CE-FDB282A9E1FC@snovak.com> I was curious as to what the you pythonistas thought about Turbo Gears. I've been moving through a pretty good book on the subject. But, I thought I would get some opinions before really committing a lot of time to learning their workflow. I am writing web apps, which is what drew me to this book http://acmsel.safaribooksonline.com/0131583999 . At first, I'm feeling completely naked without PHP, MySQL, and Apache. I guess I'm looking for reassurance that I'm doing the right thing.. ie. applying my time wisely and not stepping on my own toe, figuratively speaking. Thanks! Sean From kent37 at tds.net Wed Jun 4 14:29:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Jun 2008 08:29:27 -0400 Subject: [Tutor] turbo gears In-Reply-To: <64439ACD-40D2-400B-81CE-FDB282A9E1FC@snovak.com> References: <64439ACD-40D2-400B-81CE-FDB282A9E1FC@snovak.com> Message-ID: <1c2a2c590806040529nd811deeo2f9a9826750cac13@mail.gmail.com> On Wed, Jun 4, 2008 at 7:53 AM, Sean Novak wrote: > I was curious as to what the you pythonistas thought about Turbo Gears. > > At first, I'm feeling completely naked without PHP, MySQL, and Apache. I > guess I'm looking for reassurance that I'm doing the right thing.. ie. > applying my time wisely and not stepping on my own toe, figuratively > speaking. No, you are not stepping on your toe. TurboGears is a mature and popular Python web framework. Other choices are Django and Pylons. Django and TG are both very popular. Pylons uses many of the same components as TG but with (I think) a different way of gluing them together. Kent From jtp at nc.rr.com Wed Jun 4 16:00:46 2008 From: jtp at nc.rr.com (James) Date: Wed, 4 Jun 2008 10:00:46 -0400 Subject: [Tutor] Grabbing data from changing website Message-ID: All, I'd like to write a script that parses through a website that constantly changes (i.e., stock prices listed on a flat html page). Is there a good module to 'grab' data from a page and dump it into a data structure? The parsing will likely be rather easy. :) Many thanks. :) - james From kent37 at tds.net Wed Jun 4 16:26:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Jun 2008 10:26:31 -0400 Subject: [Tutor] Grabbing data from changing website In-Reply-To: References: Message-ID: <1c2a2c590806040726u1da34e16wdd92d3888f778ea6@mail.gmail.com> On Wed, Jun 4, 2008 at 10:00 AM, James wrote: > Is there a good module to 'grab' data from a page and dump it into a > data structure? The parsing will likely be rather easy. :) urllib2 will grab the HTML. BeautifulSoup will parse it and allow fairly easy access. My writeup on each: http://personalpages.tds.net/~kent37/kk/00010.html http://personalpages.tds.net/~kent37/kk/00009.html Kent From jtp at nc.rr.com Wed Jun 4 16:48:04 2008 From: jtp at nc.rr.com (James) Date: Wed, 4 Jun 2008 10:48:04 -0400 Subject: [Tutor] Grabbing data from changing website In-Reply-To: <1c2a2c590806040726u1da34e16wdd92d3888f778ea6@mail.gmail.com> References: <1c2a2c590806040726u1da34e16wdd92d3888f778ea6@mail.gmail.com> Message-ID: Thanks for the prompt reply, Kent! On Wed, Jun 4, 2008 at 10:26 AM, Kent Johnson wrote: > On Wed, Jun 4, 2008 at 10:00 AM, James wrote: > >> Is there a good module to 'grab' data from a page and dump it into a >> data structure? The parsing will likely be rather easy. :) > > urllib2 will grab the HTML. BeautifulSoup will parse it and allow > fairly easy access. My writeup on each: > http://personalpages.tds.net/~kent37/kk/00010.html > http://personalpages.tds.net/~kent37/kk/00009.html > > Kent > From mjain at buzzient.com Wed Jun 4 20:21:01 2008 From: mjain at buzzient.com (Mohit Jain) Date: Wed, 4 Jun 2008 14:21:01 -0400 Subject: [Tutor] thread.error: can't start new thread Message-ID: <6847d99f0806041121s730bfb07na9e41df48f8176e1@mail.gmail.com> Hello guys, I am new to python (started programming a week back). I am trying to run a piece of text analysis code over a database which contain more than 10,000,00 rows. I decided to run the program in a threaded way. So i created a thread pool. However, code gives me the error thread.error: can't start new thread. I am running my code on Fedora Core 3 on VMPlayer. I wanted to know that is the problem due to less virtual memory allocated to Vmplayer. Is it dependent on OS or is it a limitation of python itself. Thanks in advance Regards Mohit -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Wed Jun 4 20:21:55 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 4 Jun 2008 20:21:55 +0200 Subject: [Tutor] Intercepting methods calls In-Reply-To: <759f137c0806041012i5e0c5475ha8f25199904ecb23@mail.gmail.com> References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> <200806041009.44765.andreas@kostyrka.org> <759f137c0806041012i5e0c5475ha8f25199904ecb23@mail.gmail.com> Message-ID: <200806042022.42234.andreas@kostyrka.org> Simple (untested in the mailer typed): class A: def __getattr__(self, key): if key.startswith("user"): def func(): return key[4:] return func raise AttributeError assert A().userabc() == "abc" Something like that? On Wednesday 04 June 2008 19:12:16 you wrote: > Sorry, i doesn't explain my question how i should. > > What I'm trying to accomplish is to add methods dynamically at class > instances. but i what to create them whe a A().someMethod() is called ( > someMethod doesn't exist ) > > Like as with attributes. > > So far i try with ( at instance and at class level ): > > def foo(): > return lambda: 'foo' > > class A(object): pass > > a = A() > a.foo = foo() > > --------------------------- > > def foo(): > return lambda self: 'foo' > > class A(object): pass > > A.foo = foo() > a= A() > > This works, but i really like to be able of bound those functions using a > sintax like: > > a = A() > a.someMethod() # This should bound the somethod to a function. > > > Thaks in advance -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From alan.gauld at btinternet.com Wed Jun 4 21:15:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jun 2008 20:15:23 +0100 Subject: [Tutor] turbo gears References: <64439ACD-40D2-400B-81CE-FDB282A9E1FC@snovak.com> Message-ID: "Sean Novak" wrote >I was curious as to what the you pythonistas thought about Turbo >Gears. I've been moving through a pretty good book on the subject. If its the Prentice Hall one then I've read that too. Its OK but has a few errors in it. But TurboGears is well proven albeit evolving. It has reasonable support forums etc. > At first, I'm feeling completely naked without PHP, MySQL, and > Apache. I guess I'm looking for reassurance that I'm doing the > right thing.. Once you gwet used to it it will be more productive and more scaleable than PHP. You can of course use MySql with TG so no loss of skills there. The other big favourite is Django which is a less component focussed approach more akin to RubyOnRails. I'm only just starting to play with it. I have used a couple of other web frameworks and all are more productive for big projects than vanilla CGI/PHP style scripting. They all tend to share concepts by having a templating system to separate HTML/presentation from application logic, a server engine to translate URLs to function/method calls and usually an ORM to map objects to database tables. They will generally come with a web admin tool and some basic functionality such as user access control functionality pre written. If you need to do real work soon just pick any popular one and start working with it. Once you learn one, moving to another is no more difficult than learning a new programming language - a matter of a couple of weeks of effort and practice. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jun 4 21:23:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jun 2008 20:23:45 +0100 Subject: [Tutor] Intercepting methods calls References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> <50444.66.218.47.125.1212558109.squirrel@mail.tigertech.net> Message-ID: "Marilyn Davis" wrote > > Great question, Alan. But, whatever the answer, I'd like to see > > the > > variations listed, if you have time. > > Well, let's start the ball rolling then. > > __getattribute__ > __getattr__ > Metaclasses > decorators > properties > __init__ > > The basic working is that you've got a function, and that get's > wrapped. One more: You can write an explicit dispatch method (often called send) with a dictionary lookup of the methods. This is usually done as a class method. This is the classic approach in languages like C++ without dynamic introspection. Its also somewhat similar to Objective Cs approach. But it could be done in Python too. The send method simply delegates the call to the approproate real method via a lookup table. Thus allows some of the fancier Lisp or Eiffel style tricks like multiple dispatch, multi-methods, multi-named methods, changing calling sequence in inheritance etc etc. But it requires much more work in the class definition of course, so should be used sparingly!!! I've mainly used it in dynamic database creation (mapping new table or column names to generic getter/setter methods) and in AI applications using C++. Alan G From alan.gauld at btinternet.com Wed Jun 4 21:30:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jun 2008 20:30:12 +0100 Subject: [Tutor] thread.error: can't start new thread References: <6847d99f0806041121s730bfb07na9e41df48f8176e1@mail.gmail.com> Message-ID: "Mohit Jain" wrote > I am new to python (started programming a week back). I assume from what follows that you are not new to programming and have experience of threads in other languages(maybe Java?) If not and you are new to programming then back off from threads for now! They are not a good place for beginners to go! :-) > piece of text analysis code over a database which contain more than > 10,000,00 rows. I decided to run the program in a threaded way. Are you actually processing multiple rows at once or are you just launching a single (or few) long lived thread(s)? The latter approach should not give any problems. The former is likely to run into resource issues of all sorts. Could be database, OS, file handles etc etc. as well as Python. > thread.error: can't start new thread. Can you show us the entire error including the stack trace plus some contextual code around the error. Specifically how you are starting the threads. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Jun 4 21:35:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Jun 2008 15:35:04 -0400 Subject: [Tutor] thread.error: can't start new thread In-Reply-To: <6847d99f0806041121s730bfb07na9e41df48f8176e1@mail.gmail.com> References: <6847d99f0806041121s730bfb07na9e41df48f8176e1@mail.gmail.com> Message-ID: <1c2a2c590806041235h467155d8rc6f211b4026d5a0c@mail.gmail.com> On Wed, Jun 4, 2008 at 2:21 PM, Mohit Jain wrote: > Hello guys, > > I am new to python (started programming a week back). I am trying to run a > piece of text analysis code over a database which contain more than > 10,000,00 rows. I decided to run the program in a threaded way. So i created > a thread pool. However, code gives me the error > > thread.error: can't start new thread. Please show us - the code that causes the error - the complete error message including the stack trace You might want to use someone else's thread pool, especially if you are brand-new to programming. There are several possibilities in the Python Cookbook, search for thread pool. http://aspn.activestate.com/ASPN/Cookbook/Python Kent From bryan.fodness at gmail.com Wed Jun 4 22:47:05 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Wed, 4 Jun 2008 16:47:05 -0400 Subject: [Tutor] trying to change the number of elements in array while preserving data Message-ID: I tried posting this to numpy, but my posts never show up. So, I was hoping someone here might be able to help me. I have two arrays that are different sizes and i would like to be able to add them for plotting. If I have an array a and b, [[1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9]] [[0 0 0 0 0] [0 3 3 3 0] [0 3 3 3 0] [0 3 3 3 0] [0 0 0 0 0]] but I would like to change b to look like this, [[0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0] [0 0 3 3 3 3 3 0 0] [0 0 3 3 3 3 3 0 0] [0 0 3 3 3 3 3 0 0] [0 0 3 3 3 3 3 0 0] [0 0 3 3 3 3 3 0 0] [0 0 3 3 3 3 3 0 0] [0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0]] so I can get the sum of a and b. My data will not be regular like these. I have a 400x60 array with irregular data that I would like as a 400x400 array. Does anybody know of an easy way to accomplish this? Bryan -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Thu Jun 5 00:18:55 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed, 4 Jun 2008 15:18:55 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Intercepting methods calls] Message-ID: <29655.66.201.58.8.1212617935.squirrel@mail.tigertech.net> I keep forgetting to reply-to the list. I wish it was the default. On Wed, June 4, 2008 11:21 am, Andreas Kostyrka wrote: > Simple (untested in the mailer typed): > > > class A: def __getattr__(self, key): if key.startswith("user"): def func(): > return key[4:] return func raise AttributeError > > assert A().userabc() == "abc" > > Something like that? Yes it works! Brilliant. You listed __init__ and I'm not sure I know what you mean. I was thinking of not having access to the original class/method so I did this awful thing: a_def.py class A: def SaySomething(self): print 'this' ____ import a_def def SayElse(dummy=None): print 'that' a_def.A.SaySomething = SayElse a_def.A().SaySomething() --- and 'that' came out. I guess the A class could have been written to prevent that from happening. Thank you for the info and thoughts. Marilyn Davis > > > > On Wednesday 04 June 2008 19:12:16 you wrote: > >> Sorry, i doesn't explain my question how i should. >> >> >> What I'm trying to accomplish is to add methods dynamically at class >> instances. but i what to create them whe a A().someMethod() is called ( >> someMethod doesn't exist ) >> >> Like as with attributes. >> >> >> So far i try with ( at instance and at class level ): >> >> >> def foo(): return lambda: 'foo' >> >> class A(object): pass >> >> a = A() a.foo = foo() >> >> --------------------------- >> >> >> def foo(): return lambda self: 'foo' >> >> class A(object): pass >> >> A.foo = foo() >> a= A() >> >> This works, but i really like to be able of bound those functions using >> a sintax like: >> >> a = A() a.someMethod() # This should bound the somethod to a >> function. >> >> >> Thaks in advance >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Jun 5 01:22:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jun 2008 00:22:08 +0100 Subject: [Tutor] trying to change the number of elements in array whilepreserving data References: Message-ID: "Bryan Fodness" wrote > but I would like to change b to look like this, > > [[0 0 0 0 0 0 0 0 0] > [0 0 3 3 3 3 3 0 0] > [0 0 3 3 3 3 3 0 0] > My data will not be regular like these. I have a 400x60 array with > irregular data that I would like as a 400x400 array. I'm not quite sure the significance of the last bit but it looks like you just want to pad equally on both sides with zeros? N = (400-60)/2 # = 70 padded = [[0]*N + row + [0]*N for row in oldarray] Untried and maybe not too fast but simple. Or am I missing a complication? Alan G. From alan.gauld at btinternet.com Thu Jun 5 09:38:31 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 5 Jun 2008 07:38:31 +0000 (GMT) Subject: [Tutor] Fw: turbo gears Message-ID: <247285.42513.qm@web86704.mail.ukl.yahoo.com> It wasn't me asked the question so I've forwarded the message to the tutor list. Please use ReplyAll when responding. ----- Forwarded Message ---- From: Laureano Arcanio To: Alan Gauld Sent: Thursday, 5 June, 2008 5:07:49 AM Subject: Re: [Tutor] turbo gears I've using Turbogears for the last months, i found that they have a very friendly community and a fast evolving project. So far you got TG 1.0.4 .4, a very well tested and featured stable release. All the effort is right now focused in a near release of TG 2, this one it's built on top of Pylons. I think this frameworks is a great one, at last for me the productivity time increased a lot. As a comment, you might consider using an ORM like SqlAlchemy, this tools are very handy and they provide a set of tools to dynamically build your forms from your model ( FormAlchemy, DBSProckets for instance ). Once you get use to them, you start loving them. Cheers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From broek at cc.umanitoba.ca Thu Jun 5 10:21:22 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Thu, 05 Jun 2008 03:21:22 -0500 Subject: [Tutor] OT: tutor list equivalent for lisp? Message-ID: <20080605032122.aucwdzpwzk440008@webware.cc.umanitoba.ca> Hi all, I've an off-topic query; hope no one minds. I've poked into the lisp world a bit before (started SICP, etc., but never used it in anger), and put it on my `when I've more time' shelf. Well, my desire to extend emacs has made me want to get more serious about it. Does anyone know of a lisp list similar in mission to this one? (I know the lisp world is fractured (elsip != scheme != CL != ....) but also figure I'd be better off with a list for the `wrong' dialect than no list at all.) We now return you to your regularly scheduled programming. Best, Brian vdB From alan.gauld at btinternet.com Thu Jun 5 11:23:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jun 2008 10:23:24 +0100 Subject: [Tutor] tutor list equivalent for lisp? References: <20080605032122.aucwdzpwzk440008@webware.cc.umanitoba.ca> Message-ID: wrote > Well, my desire to extend emacs has made me want to get more > serious about it. The emacs community is pretty good for supporting elispers but I don't know of any tutor style lists. ( So far as I know this list is fairly unique! There is something like it for PHP but it didn't seem to cater for total newbies to the same exxtent.) > know the lisp world is fractured (elsip != scheme != CL != ....) but > also figure I'd be better off with a list for the `wrong' dialect > than no list at all.) My experience is the best support for learning was in Scheme. They had the easiest IDEs, good forums/newsgroups (ie not too many RTFMs!) But i only play with Lisp these days so am well out of date. The best Lisp tutorial IMHO is the How To Design Programs web site/book (htdp.org?) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From andreas at kostyrka.org Thu Jun 5 12:06:34 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 5 Jun 2008 12:06:34 +0200 Subject: [Tutor] Intercepting methods calls In-Reply-To: References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> <200806041009.44765.andreas@kostyrka.org> Message-ID: <200806051206.39792.andreas@kostyrka.org> On Wednesday 04 June 2008 18:18:04 you wrote: > > Well, let's start the ball rolling then. > > > > __getattribute__ > > __getattr__ > > Metaclasses > > decorators > > properties > > __init__ > > Okay, I'll bite. I asked here a week or two ago about creating a > custom dummy object that returns a blank string no matter what you do > with it, or what attribute you try to call on it. Very helpful answers > led to the following: > > > class Dummy(object): > def __init__(self,**atts): > self.__dict__.update(atts) > > def __repr__(self): > return '' > > def __getattr__(self, attr): > return '' > > The resulting object return a blank string for everything, except > attributes created by keyword args you pass to __init__. But if you > try to call a random method on a Dummy, say: > > d = Dummy() > d.notamethod() > > You get "str object is not callable", ie 'notamethod' is first caught > by __getattr__, turned into an empty string, and called. So what > recourse do I have here to detect that the attribute is getting > called, and have that return a blank string too? well, don't return a string :-P class CallableString(str): def __call__(self, *args, **kw): return self And now instead of return '', write return CallableString('') Problem solved. Andreas > > Curious, > E -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From andreas at kostyrka.org Thu Jun 5 12:52:55 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 5 Jun 2008 12:52:55 +0200 Subject: [Tutor] Intercepting methods calls In-Reply-To: References: <759f137c0806031915p18797f42y160155d311a165d4@mail.gmail.com> <200806051206.39792.andreas@kostyrka.org> Message-ID: <200806051252.57936.andreas@kostyrka.org> On Thursday 05 June 2008 12:31:56 you wrote: > On Jun 5, 2008, at 6:06 PM, Andreas Kostyrka wrote: > > well, don't return a string :-P > > > > class CallableString(str): > > def __call__(self, *args, **kw): > > return self > > > > And now instead of return '', write return CallableString('') > > Whoa, trippy. > > That certainly works, but it's a workaround to the original question ? > is there actually any way to 'detect' an attribute/method call? No, because there are no "method calls" in Python. obj.method() means: locate obj in locals/globals. locate method on obj call the found thing. obj => obj.method => obj.method() Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From qsqgeekyogdty at tiscali.co.uk Thu Jun 5 14:06:59 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 5 Jun 2008 13:06:59 +0100 (GMT+01:00) Subject: [Tutor] TypeError: argument 1 must be string or read-only character buffer, not instance Message-ID: <33343124.1212667619742.JavaMail.root@ps28> Hello, I am still fighting with parsing out the html text and this is what I have so far, but seems I keep hitting my head against a barrier. >>> import os >>> from BeautifulSoup import BeautifulSoup >>> file = '/home/david/test/stack.html' >>> html = open(file, 'r') >>> soup = BeautifulSoup(html) >>> table = soup.find('table', {'class': 'order_tbl'}) >>> for row in table.findAll('td', {'class': 'order_tbl_price'}): >>> for td in row: >>> price = float(td.contents[1].lstrip(' $')) >>> td.contents[1].replaceWith('$%0.2f' % (price * 0.85)) My question now is do I have to close the html before I write to it, so that: >>> html.close() >>> html = open(file, 'w') >>> html.write(soup) Traceback (most recent call last): File "", line 1, in TypeError: argument 1 must be string or read-only character buffer, not instance >>> What am I doing wrong here? Thank you David ____________________________________________________ Guard your email - http://www.tiscali.co.uk/products/securemail/ ____________________________________________________ From rduenasp at gmail.com Thu Jun 5 16:45:41 2008 From: rduenasp at gmail.com (=?ISO-8859-1?Q?Ricardo_Due=F1as_Parada?=) Date: Thu, 5 Jun 2008 09:45:41 -0500 Subject: [Tutor] Python in symbian (NOKIA E50) Message-ID: <559102030806050745j396f3c0dk22c1e2cc0450fd55@mail.gmail.com> Hi all, I want to write an script to send messages from my phone (Nokia E50) to my computer via bluetooth, i'm kind of new in bluetooth applications in phones, so, can you recommend some document, web page, script, something to start? Thanks, _Ricardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Thu Jun 5 16:55:15 2008 From: onyxtic at gmail.com (Evans Anyokwu) Date: Thu, 5 Jun 2008 15:55:15 +0100 Subject: [Tutor] Python in symbian (NOKIA E50) In-Reply-To: <559102030806050745j396f3c0dk22c1e2cc0450fd55@mail.gmail.com> References: <559102030806050745j396f3c0dk22c1e2cc0450fd55@mail.gmail.com> Message-ID: See this is of any help! http://www.devshed.com/c/a/Python/Bluetooth-Programming-using-Python/ Evans http://www.javawug.org On Thu, Jun 5, 2008 at 3:45 PM, Ricardo Due?as Parada wrote: > Hi all, > > I want to write an script to send messages from my phone (Nokia E50) to my > computer > via bluetooth, i'm kind of new in bluetooth applications in phones, so, can > you recommend > some document, web page, script, something to start? > > Thanks, > > _Ricardo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Thu Jun 5 17:03:08 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 5 Jun 2008 17:03:08 +0200 Subject: [Tutor] Stackless Python and CPython code compatibility Message-ID: Hi guys, Could someone please explain whether or not using Stackless Python with CPython affects compatibility across code versions? e.g. if one wanted Stackless for web development, would Cheetah, Django, Zope, Plone et al play nicely with it? Regards, -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jun 5 17:15:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Jun 2008 11:15:40 -0400 Subject: [Tutor] TypeError: argument 1 must be string or read-only character buffer, not instance In-Reply-To: <33343124.1212667619742.JavaMail.root@ps28> References: <33343124.1212667619742.JavaMail.root@ps28> Message-ID: <1c2a2c590806050815m5ba86f8djc49c653afd0bce5b@mail.gmail.com> On Thu, Jun 5, 2008 at 8:06 AM, qsqgeekyogdty at tiscali.co.uk wrote: >>>> import os >>>> from BeautifulSoup import BeautifulSoup >>>> file = '/home/david/test/stack.html' >>>> html = open(file, 'r') >>>> soup = BeautifulSoup(html) >>>> table = soup.find('table', {'class': 'order_tbl'}) >>>> for row in table.findAll('td', {'class': 'order_tbl_price'}): >>>> for td in row: >>>> price = float(td.contents[1].lstrip(' $')) >>>> td.contents[1].replaceWith('$%0.2f' % (price * 0.85)) > > My question now is do I have to close the html before I write to it, Yes, it's a good idea. > so that: > >>>> html.close() >>>> html = open(file, 'w') >>>> html.write(soup) > Traceback (most recent call last): > File "", line 1, in > TypeError: argument 1 must be string or read-only character buffer, > not instance The error message is actually pretty informative. Argument 1 means the argument you are passing to write(). It says it has to be a string or a character buffer. You are passing it 'soup' with is an instance of BeautifulSoup, not a string. The fix is to ask for the soup as a string: html.write(str(soup)) Kent From dyoo at cs.wpi.edu Thu Jun 5 17:47:21 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Thu, 5 Jun 2008 11:47:21 -0400 (EDT) Subject: [Tutor] tutor list equivalent for lisp? In-Reply-To: References: <20080605032122.aucwdzpwzk440008@webware.cc.umanitoba.ca> Message-ID: > But i only play with Lisp these days so am well out of date. > > The best Lisp tutorial IMHO is the How To Design Programs > web site/book (htdp.org?) Yes, HTDP is one of the very good ones. I'd strongly recommend it. As a full disclosure thing: I'm involved with the folks doing HTDP: I'm not a neutral party. :) Just to clarify: HTDP does not focus on teaching Lisp per say. In fact, all of the the languages it uses are, in some sense, even smaller than Scheme. It's more focused on teaching good habits of programming. HTDP uses the PLT Scheme distribution, which you can find here: http://www.plt-scheme.org/ You might want to wait for the pending release of 4.0 release of PLT Scheme. It's about to arrive in a few days; the PLT Scheme folks are right in the middle of testing their release-candidate. The support mailing list for PLT Scheme is at: http://list.cs.brown.edu/mailman/listinfo/plt-scheme/ That mailing list is the main discussion group for PLT Scheme. In that sense, it doesn't play quite the same role as tutor at python.org. Still, there are a lot of helpful people on that list. From alan.gauld at btinternet.com Thu Jun 5 18:34:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jun 2008 17:34:41 +0100 Subject: [Tutor] Stackless Python and CPython code compatibility References: Message-ID: "OkaMthembo" wrote > Could someone please explain whether or not using > Stackless Python with CPython affects compatibility across > code versions? e.g. if one wanted Stackless for web development, > would Cheetah, Django, Zope, Plone et al play > nicely with it? I've never tried, but I would not be surprised if you ran into compatibility problems. Particularly where any of the modules were compiled C rather than pure python. Alan G. From andreas at kostyrka.org Thu Jun 5 18:39:33 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 5 Jun 2008 18:39:33 +0200 Subject: [Tutor] [Fwd: Re: Intercepting methods calls] In-Reply-To: <29655.66.201.58.8.1212617935.squirrel@mail.tigertech.net> References: <29655.66.201.58.8.1212617935.squirrel@mail.tigertech.net> Message-ID: <200806051839.36442.andreas@kostyrka.org> On Thursday 05 June 2008 00:18:55 Marilyn Davis wrote: > > You listed __init__ and I'm not sure I know what you mean. > Well, __init__ can assign attributes to the instance that are callable. Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From jtp at nc.rr.com Thu Jun 5 19:56:25 2008 From: jtp at nc.rr.com (James) Date: Thu, 5 Jun 2008 13:56:25 -0400 Subject: [Tutor] Have Python Update Forms Message-ID: All, I'm helping a buddy write a program and could use a few pointers. :) I know this is a bit 'off-topic,' but hopefully someone can shed some light on how to go about doing this. First some background information: there's a web tool which keeps track of a 'to do' list. The to-do list has a database backend that a user can interact with by using a set of very mature web tools already in production. One of the fields in each 'to-do list item' is 'last updated'. Each to-do list item is tracked by a number. The goal is to write a program that will the 'last updated' field in the to-do list. A user can edit the 'to-do item' by accessing a web interface (where you can change status, priority, etc. of the to-do list item): http://site/todoUpdate.do?item=225532 There's a form field in this web tool interface where the 'last updated' field (a *date* field) can be manually modified by a user. Thus, when a user makes a modification to the item, the date field for 'last updated' has to be manually changed. A user can also see an overview of all to-do items by going to a URL similar to the following: http://site/todoList.do?user=testUser I want to write a program that will update the 'last updated' field on *every* item. This will require some sort of 'post' to the web server and interaction with the existing web tools and its back-end. I can probably whip up a program (using the advice Kent gave yesterday in a thread on this mailing list :)) to gather the entire list of items that needs to be modified (all the to-do list item numbers, that is). I'm not sure, however, how to mimic manually updating the last-updated field. Any thoughts? - james From cappy2112 at gmail.com Thu Jun 5 21:03:23 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 5 Jun 2008 12:03:23 -0700 Subject: [Tutor] Grabbing data from changing website Message-ID: <8249c4ac0806051203y72a22270p52c3dfb35c74ade1@mail.gmail.com> ------------------------------ > > Message: 4 > Date: Wed, 4 Jun 2008 10:00:46 -0400 > From: James > Subject: [Tutor] Grabbing data from changing website > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > > >>urllib2 will grab the HTML. BeautifulSoup will parse it and allow > >>fairly easy access. My writeup on each: > I'll second Kent's vote for BeautifulSoup. I had never done any web programming, but using BS I quickly wrote a small program that downloads an image from a site. The image changes daily, and the filename & directory are obviously unique. BS made it very easy. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdeambulemorose at gmail.com Thu Jun 5 22:14:23 2008 From: jdeambulemorose at gmail.com (Blaise Morose) Date: Thu, 5 Jun 2008 22:14:23 +0200 Subject: [Tutor] __del__ exception Message-ID: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> Hi, I have this silly piece of code that I am experimenting with: #!/usr/bin/python class Person: population = 0 def __init__(self, name): self.name = name print '%s has been added' %self.name Person.population += 1 def __del__(self): print '%s is leaving' % self.name Person.population -= 1 print 'population = %d' %Person.population p = Person('Jean') d = Person('Michael') Output: Jean has been added Michael has been added Michael is leaving population = 1 Jean is leaving *Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored* So once all objects have been destroyed, an exception is triggered on class variable 'population'. Any more logical explanation and work around? I just need to understand what python is doing here Thx Blaise -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 5 23:52:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jun 2008 22:52:09 +0100 Subject: [Tutor] Have Python Update Forms References: Message-ID: "James" wrote > I want to write a program that will update the 'last updated' field > on > *every* item. This will require some sort of 'post' to the web > server Have you considered doing it in JavaScript on the client. You could esily do this in the onSubmit handler function. The only snag is if the client PC is out of synch with the server dates. The alternative is to catch the form submission and force the date update. If the user does manually change the date which takes precedence? The users value or the current date? Since this is a working app you will likely be easiest working in the same language that the orioginal was written in! > I'm not sure, however, how to mimic manually updating the > last-updated > field. JavaScript can do that within the browser. Whatever language is used at the server side can do it direct to the database. Does that help? Alan G From mlangford.cs03 at gtalumni.org Thu Jun 5 23:57:50 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 5 Jun 2008 17:57:50 -0400 Subject: [Tutor] __del__ exception In-Reply-To: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> References: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> Message-ID: <82b4f5810806051457j7fa4032co6c93ecfb13c229b0@mail.gmail.com> There is no remaining referent to your class at the point when the last instance has started to be deleted. This allows the class itself to be garbage collected. Changing the code to the following will prevent this. #!/usr/bin/python class Person: population = 0 def __init__(self, name): self.name = name print '%s has been added' %self.name Person.population += 1 def __del__(self): print '%s is leaving' % self.name Person.population -= 1 print 'population = %d' %Person.population cls = Person p = Person('Jean') d = Person('Michael') --Michael On Thu, Jun 5, 2008 at 4:14 PM, Blaise Morose wrote: > Hi, > > I have this silly piece of code that I am experimenting with: > > #!/usr/bin/python > > class Person: > population = 0 > > def __init__(self, name): > self.name = name > print '%s has been added' %self.name > > Person.population += 1 > > def __del__(self): > print '%s is leaving' % self.name > > Person.population -= 1 > > print 'population = %d' %Person.population > > > p = Person('Jean') > d = Person('Michael') > > Output: > > Jean has been added > Michael has been added > Michael is leaving > population = 1 > Jean is leaving > Exception exceptions.AttributeError: "'NoneType' object has no attribute > 'population'" in at 0xb7dadacc>> ignored > > So once all objects have been destroyed, an exception is triggered on class > variable 'population'. > > Any more logical explanation and work around? I just need to understand what > python is doing here > > Thx > > Blaise > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From wescpy at gmail.com Thu Jun 5 23:59:31 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 5 Jun 2008 14:59:31 -0700 Subject: [Tutor] __del__ exception In-Reply-To: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> References: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> Message-ID: <78b3a9580806051459w2ad2d8bfp5a0d546f4408f9a5@mail.gmail.com> > class Person: > population = 0 > > def __init__(self, name): > self.name = name > print '%s has been added' %self.name > Person.population += 1 > > def __del__(self): > print '%s is leaving' % self.name > Person.population -= 1 > print 'population = %d' %Person.population > > p = Person('Jean') > d = Person('Michael') > > Output: > Jean has been added > Michael has been added > Michael is leaving > population = 1 > Jean is leaving > Exception exceptions.AttributeError: "'NoneType' object has no attribute > 'population'" in at 0xb7dadacc>> ignored > > So once all objects have been destroyed, an exception is triggered on class > variable 'population'. not quite. if you look back carefully, the exception is really about Person no longer existing, hence the reason why a get on None.population fails. > Any more logical explanation and work around? I just need to understand what > python is doing here it is generally recommended that people do *not* implement an __del__() method, esp. if the program is exiting. many people are under the misconception that this method is called whenever an object goes out-of-scope, but that may not necessarily be true... it is only called when the reference count of the object goes to zero. details here: http://docs.python.org/ref/customization.html the sidebar boxes on this page also point out that when programs end, exceptions are ignored in this method because some objects may have already been deallocated by the time this code is reached, i.e. Person, and are no longer available. hope this helps! -- 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 alan.gauld at btinternet.com Fri Jun 6 00:02:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jun 2008 23:02:17 +0100 Subject: [Tutor] __del__ exception References: <206cc2050806051314v61fa28ai690175a8927271c9@mail.gmail.com> Message-ID: "Blaise Morose" wrote > I have this silly piece of code that I am experimenting with: I'm not certain but... based on this quote from the Python docs: ------ Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called. ---------------------------- > class Person: > > p = Person('Jean') > d = Person('Michael') Because you don't explicitly kill the objects the interpreter may have deleted the class object before the instance __del__ gets called. What happens iof you explicity del(p) and del(d)? Just a thought. Alan G. From kent37 at tds.net Fri Jun 6 02:43:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Jun 2008 20:43:30 -0400 Subject: [Tutor] Have Python Update Forms In-Reply-To: References: Message-ID: <1c2a2c590806051743t263bf1d3w71f438b06e736733@mail.gmail.com> On Thu, Jun 5, 2008 at 1:56 PM, James wrote: > I want to write a program that will update the 'last updated' field on > *every* item. This will require some sort of 'post' to the web server > and interaction with the existing web tools and its back-end. I can > probably whip up a program (using the advice Kent gave yesterday in a > thread on this mailing list :)) to gather the entire list of items > that needs to be modified (all the to-do list item numbers, that is). > I'm not sure, however, how to mimic manually updating the last-updated > field. You have to find out how the browser talks to the backend. Most likely it is a POST with the form data. If so, you can simulate this in Python. See the section on POST here: http://personalpages.tds.net/~kent37/kk/00010.html There are various complications - authentication, hidden fields and JavaScript, for example - but essentially you want to write a Python program that mimics the interaction the browser has with the server. Tools that let you inspect the browser interaction are very helpful but I will leave you to ferret those out yourself. There are Firefox plugins that will do that. Kent From technorapture at gmail.com Fri Jun 6 06:07:09 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Fri, 6 Jun 2008 00:07:09 -0400 Subject: [Tutor] Error-handling for a large modular program Message-ID: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> I'm currently working on a research project where we'll be developing a moderately complex piece of software. We're designing with extensibility in mind. One of the problems I can see right now is that our program can potentially create a large number of very different errors, some fatal, some not. Part of this is because the front end of the program is essentially a parser for a moderately complex configuration language, which means that there are a variety of syntax/semantics errors possible. Since the project is in the beginning stages, I've only implemented basic error handling through a number of try/except blocks and if/elses. However I feel that the code might become increasingly inelegant if I keep adding a try/except for every possible error (and breaking up the code to make it be a specific as possible about the errors). Is there some more generic, high-level approach I could use? One approach I have thought of is creating a error handler class where each class method corresponds to a particular error. An instance of this class would be created at the start of the program and each error would run a method in the class. This would allow us to have elaborate error handling code, without cluttering the actual working code. We'd still need try/catch blocks, but the catches wouldn't be anything more than method calls. Since we have 3-4 people, each working on a different part of the program, we could each add to this error handler as needed. Since this is my first real world application that I'm writing as a team, I have no idea how error handling is actually done in large applications. So any suggestions would be appreciated. Thanks for your help, Shrutarshi -- The ByteBaker : http://www.bytebaker.com From saluk64007 at gmail.com Fri Jun 6 08:49:17 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Thu, 5 Jun 2008 23:49:17 -0700 Subject: [Tutor] Fw: turbo gears In-Reply-To: <247285.42513.qm@web86704.mail.ukl.yahoo.com> References: <247285.42513.qm@web86704.mail.ukl.yahoo.com> Message-ID: Yeah, I like turbogears as well. I was using cherrypy before turbogears borrowed it, and have a hard time remembering that turbogears has more than just cherrypy (pretty much just use cherrypy still, even though it's called tg). It's a bit weird with TG2 now moving to pylons - which is not cherrypy. I don't know how I feel about that lol! But no, you won't be wasting your time. Many of the python frameworks do share similar concepts, even if they come at it from different perspectives. And they are all better than plain php, although many of my php developer friends would argue that whatever php framework they use is just as good :) Turbogears will be around for a long while, even if it seems django is winning at the moment. There are many developers and many people using it, so it has a long life ahead. Even if it didn't get expanded though, what's there currently is plenty to support any web application you would want to make. In my experience php bugs are harder to spot than python bugs. Generally, most python bugs will cause an error while most php bugs wont. But this is a python developers perspective of php and not the other way around, soyour milage may vary. But be on the lookout for this anyway. You cant just let an error pass by and test a different part of the page. It's a bit different development style than php. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 6 09:51:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jun 2008 08:51:57 +0100 Subject: [Tutor] Have Python Update Forms References: Message-ID: "James" wrote > I want to write a program that will update the 'last updated' field > on > *every* item. This will require some sort of 'post' to the web > server I think I misunderstood your request. I thought you wanted to add some new web browser functions but it looks like you may want a batch update facility? If so why not write directly to the database? Simulating a GUI or web form is an intrinsicly unreliable way of doing things and if possible you should go directly to the datyabase. It will also be much quicker and have less resource hit on your server. Or is here a reason you cannot talk to the database? Alan G From alan.gauld at btinternet.com Fri Jun 6 10:13:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jun 2008 09:13:00 +0100 Subject: [Tutor] Error-handling for a large modular program References: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> Message-ID: "Shrutarshi Basu" wrote > I'm currently working on a research project where we'll be > developing > a moderately complex piece of software. We're designing with > extensibility in mind. One of the problems I can see right now is > that > our program can potentially create a large number of very different > errors, some fatal, some not. That's not unusual. I have worked on projects with over a thousand exception classes (in C++ and Java). > I've only implemented basic error handling through a > number of try/except blocks and if/elses. Thats the best way to proceed but... > However I feel that the code might become increasingly inelegant > if I keep adding a try/except for every possible error > (and breaking up the code to make it be a specific as possible > about the errors). Is there some more generic, > high-level approach I could use? How are you using try/except. One of the big advantages of try/except is that it does not break up your main code flow. All the excepts sit outside of that. If you put your main code in a function that raises the errors then the error handling can come out to a higher level with try: mainprocessingHere() except error1: ... except error2: ... ... except error999: You can also make things somewhat more manageable by designing your error heirarchy carefully to use inheritance to catch superclass errors then in the handlers using if/else to determine the solution - seeral subclasses may share a solution. But to be honest I prefer the explicit except error1,error2,error3: approach for that. > One approach I have thought of is creating a error handler class > where > each class method corresponds to a particular error. An instance of > this class would be created at the start of the program and each > error > would run a method in the class. But if you extend your program you have to modify your error handler class to add a new method and your main code will have dependencies on the class throughout. And if you reuse the class in other related projects they will be impacted too. By keeping each exception class distinct its easy to add new error types without affecting existing code too much and not affecting other projects at all. > error handling code, without cluttering the actual working code. I'm concerned at the fact you seeem to be "cluttering" the code. The point of try/except is to keep the main code as uncluttered as possible. Of course sometimes you want to handle an error in-flow and an inline try/except of if/else is unavoidable but those are usually minority cases. > still need try/catch blocks, but the catches wouldn't be > anything more than method calls. They can still be that. Or simpler use vanilla functions. I'm not a believer in writing classes just as a hold-all for a set of functions. Thats what Python modules are for! But your functions should probably aim to handle several related error types. > Since we have 3-4 people, each working on a > different part of the program, we could each add to this error > handler > as needed. Yes, if its a module it can hold the exception classes and the handler functions. In fact if you want to be fancy you could put the handler in the exception class but personally I think thats a bad idea since the handler might be diffrent in other projects. I prefer to keep the handlers and exceptions separate. > Since this is my first real world application that I'm writing as a > team, I have no idea how error handling is actually done in large > applications. Its not uncommon in large apps for the error handling to be more than half the code. When new grads or other inexperienced programmers join a big project for the first time they are often amazed at how much error code there is. The key is to keep it together and as far away from the main flow as possible and that's what try/except gives you. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From snovak at snovak.com Fri Jun 6 14:28:29 2008 From: snovak at snovak.com (Sean Novak) Date: Fri, 6 Jun 2008 08:28:29 -0400 Subject: [Tutor] Grabbing data from changing website In-Reply-To: <8249c4ac0806051203y72a22270p52c3dfb35c74ade1@mail.gmail.com> References: <8249c4ac0806051203y72a22270p52c3dfb35c74ade1@mail.gmail.com> Message-ID: I've recently been writing a web app with libxml2dom ( http://www.boddie.org.uk/python/libxml2dom.html ). I had a look at BeautifulSoup and found the two very similar. I ended up sticking with libxml2dom because of a quote from its website...... "Performance is fairly respectable since libxml2dom makes direct use of libxml2mod - the low-level wrapping of libxml2 for Python."..... I figured the app might parse through a little faster. I guess the only way to tell is to benchmark the two against eachother. Does anyone have input on defining differences? Reasons to use one over the other? Opinions welcome. On Jun 5, 2008, at 3:03 PM, Tony Cappellini wrote: > > > ------------------------------ > > Message: 4 > Date: Wed, 4 Jun 2008 10:00:46 -0400 > From: James > Subject: [Tutor] Grabbing data from changing website > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > > >>urllib2 will grab the HTML. BeautifulSoup will parse it and allow > >>fairly easy access. My writeup on each: > > I'll second Kent's vote for BeautifulSoup. > I had never done any web programming, but using BS I quickly wrote a > small program that downloads an image from a site. > The image changes daily, and the filename & directory are obviously > unique. BS made it very easy. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtp at nc.rr.com Fri Jun 6 14:58:25 2008 From: jtp at nc.rr.com (James) Date: Fri, 6 Jun 2008 08:58:25 -0400 Subject: [Tutor] Have Python Update Forms In-Reply-To: <1c2a2c590806051743t263bf1d3w71f438b06e736733@mail.gmail.com> References: <1c2a2c590806051743t263bf1d3w71f438b06e736733@mail.gmail.com> Message-ID: Thanks for the response. Ahhh, now we're going to get really off-topic. ;) The only one that I've been able to scrape up for now was the infamous DOM Inspector. Using the DOM Inspector, I can see: - action ('/tool/update/todoUpdate.do') - method is post - name is 'todo' There's a specific input (of type text). In fact, when I look at the details for this field, I see: - type (text) - class (text) - value (this is what I want to change) - size - maxlength - name (lastUpdate) Is this all the information I need to actually interact directly with the webserver using Python to mimic POST functionality? Also, are there any specific keywords I should be looking for in terms of Firefox extensions to help me with whipping up a dirty hack like this? :) Thanks! On Thu, Jun 5, 2008 at 8:43 PM, Kent Johnson wrote: > On Thu, Jun 5, 2008 at 1:56 PM, James wrote: >> I want to write a program that will update the 'last updated' field on >> *every* item. This will require some sort of 'post' to the web server >> and interaction with the existing web tools and its back-end. I can >> probably whip up a program (using the advice Kent gave yesterday in a >> thread on this mailing list :)) to gather the entire list of items >> that needs to be modified (all the to-do list item numbers, that is). >> I'm not sure, however, how to mimic manually updating the last-updated >> field. > > You have to find out how the browser talks to the backend. Most likely > it is a POST with the form data. If so, you can simulate this in > Python. See the section on POST here: > http://personalpages.tds.net/~kent37/kk/00010.html > > There are various complications - authentication, hidden fields and > JavaScript, for example - but essentially you want to write a Python > program that mimics the interaction the browser has with the server. > > Tools that let you inspect the browser interaction are very helpful > but I will leave you to ferret those out yourself. There are Firefox > plugins that will do that. > > Kent > From jtp at nc.rr.com Fri Jun 6 15:00:40 2008 From: jtp at nc.rr.com (James) Date: Fri, 6 Jun 2008 09:00:40 -0400 Subject: [Tutor] Have Python Update Forms In-Reply-To: References: Message-ID: Thanks for the response, Alan. Unfortunately direct access to the database is not a possibility. ;) It's one of those things where the folks running the database don't want to share the necessary credentials. I guess I've resorted to this "POST hack" in an effort to make life easier, even without the database password. - james On Fri, Jun 6, 2008 at 3:51 AM, Alan Gauld wrote: > > "James" wrote > >> I want to write a program that will update the 'last updated' field on >> *every* item. This will require some sort of 'post' to the web server > > I think I misunderstood your request. I thought you wanted to > add some new web browser functions but it looks like you may > want a batch update facility? > > If so why not write directly to the database? Simulating a GUI > or web form is an intrinsicly unreliable way of doing things > and if possible you should go directly to the datyabase. > It will also be much quicker and have less resource hit on > your server. Or is here a reason you cannot talk to the > database? > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Jun 6 15:37:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Jun 2008 09:37:27 -0400 Subject: [Tutor] Have Python Update Forms In-Reply-To: References: <1c2a2c590806051743t263bf1d3w71f438b06e736733@mail.gmail.com> Message-ID: <1c2a2c590806060637ga32206fx556ca1467678b81d@mail.gmail.com> On Fri, Jun 6, 2008 at 8:58 AM, James wrote: > Thanks for the response. > > Ahhh, now we're going to get really off-topic. ;) > > The only one that I've been able to scrape up for now was the infamous > DOM Inspector. You really want to be looking at the transaction with the server, not the contents of the web page. Firebug might do this, or Tamper Data, I'm not sure what I have used in the past. Kent From jtp at nc.rr.com Fri Jun 6 15:46:21 2008 From: jtp at nc.rr.com (James) Date: Fri, 6 Jun 2008 09:46:21 -0400 Subject: [Tutor] Have Python Update Forms In-Reply-To: <1c2a2c590806060637ga32206fx556ca1467678b81d@mail.gmail.com> References: <1c2a2c590806051743t263bf1d3w71f438b06e736733@mail.gmail.com> <1c2a2c590806060637ga32206fx556ca1467678b81d@mail.gmail.com> Message-ID: Phenomenal, Kent. I'll poke around and see if I can figure out what kind of communication is going on between the server and the browser and go from there. :) I appreciate your and Alan's help, as always! On Fri, Jun 6, 2008 at 9:37 AM, Kent Johnson wrote: > On Fri, Jun 6, 2008 at 8:58 AM, James wrote: >> Thanks for the response. >> >> Ahhh, now we're going to get really off-topic. ;) >> >> The only one that I've been able to scrape up for now was the infamous >> DOM Inspector. > > You really want to be looking at the transaction with the server, not > the contents of the web page. Firebug might do this, or Tamper Data, > I'm not sure what I have used in the past. > > Kent > From amit.pureenergy at gmail.com Fri Jun 6 16:26:29 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 6 Jun 2008 19:56:29 +0530 Subject: [Tutor] (no subject) Message-ID: Hi, I am a student new to python . I had a project idea in mind that I want to implement in my break using python . Can anyone give me an idea of libraries available in python for transcribing music and signal processing. Good tutorials with examples would also help. If any body has experience in the field it would be nice if you could give me some guidance . And also direct me to articles , references ,essays on the subject of pattern recognition and music summary . Also I would like to look at open source projects related to the above . Thank you everyone . -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Jun 6 18:08:46 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 06 Jun 2008 12:08:46 -0400 Subject: [Tutor] Error-handling for a large modular program In-Reply-To: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> References: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> Message-ID: <4849610E.9000800@gmail.com> Shrutarshi Basu wrote: > the front end of the program is essentially a parser for a moderately complex configuration language, which means that there are a variety of syntax/semantics errors possible. In my experience with parsers there is little or no need for try-except blocks. Could you give us an example of how you'd use try-except in your parser? Also are you aware that there are a lot of parser programs out there (some in Python) that might save you time / effort? -- Bob Gailer 919-636-4239 Chapel Hill, NC From odispam at sonic.net Fri Jun 6 20:26:15 2008 From: odispam at sonic.net (odispam at sonic.net) Date: Fri, 6 Jun 2008 11:26:15 -0700 (PDT) Subject: [Tutor] TurtleWorld Windows issue Message-ID: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> I am working through _Think Python_ in spare time at work on a Windows machine (so another OS is not an option). I can't get TurtleWorld to run as described in the book (http://www.greenteapress.com/thinkpython/html/book005.html). I'm replicating the issue described here: http://www.gamedev.net/community/forums/topic.asp?topic_id=481091 Using Windows XP, Idle v. 1.2.2, Python 2.5.2, Swampy 1.1. After adding Swampy to the modules path: >>> from TurtleWorld import * >>> TurtleWorld() No new window appears, or if it appears, it closes nearly instantaneously. >>> bob = Turtle() >>> A new but empty window appears, titled "TurtleWorld (Not Responding)" Opening and running the TurtleWorld module through the Idle GUI menu produces a functioning TurtleWorld window, but this is not useful for the purposes of the exercises. This is probably more of an Idle/Windows issue than a python issue, but I won't be able to get through Think Python unless I resolve it. Does anyone have an answer? Thanks! Oliver From srilyk at gmail.com Fri Jun 6 21:41:16 2008 From: srilyk at gmail.com (W W) Date: Fri, 6 Jun 2008 14:41:16 -0500 Subject: [Tutor] TurtleWorld Windows issue In-Reply-To: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> References: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> Message-ID: <333efb450806061241h5669e8cfi3e53d1156cfef84d@mail.gmail.com> You could always use a linux live cd ;) Heck some of them can even emulate linux in windows! That's my best solution in the short time I've got. HTH, Wayne On Fri, Jun 6, 2008 at 1:26 PM, wrote: > I am working through _Think Python_ in spare time at work on a Windows > machine (so another OS is not an option). I can't get TurtleWorld to run > as described in the book > (http://www.greenteapress.com/thinkpython/html/book005.html). > > I'm replicating the issue described here: > > http://www.gamedev.net/community/forums/topic.asp?topic_id=481091 > > Using Windows XP, Idle v. 1.2.2, Python 2.5.2, Swampy 1.1. > > After adding Swampy to the modules path: > >>>> from TurtleWorld import * >>>> TurtleWorld() > > > No new window appears, or if it appears, it closes nearly instantaneously. > >>>> bob = Turtle() >>>> > > A new but empty window appears, titled "TurtleWorld (Not Responding)" > > Opening and running the TurtleWorld module through the Idle GUI menu > produces a functioning TurtleWorld window, but this is not useful for the > purposes of the exercises. > > This is probably more of an Idle/Windows issue than a python issue, but I > won't be able to get through Think Python unless I resolve it. Does anyone > have an answer? > > Thanks! > > Oliver > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From abstractpoetry at gmail.com Fri Jun 6 21:45:38 2008 From: abstractpoetry at gmail.com (Anthony Parks) Date: Fri, 6 Jun 2008 15:45:38 -0400 Subject: [Tutor] how to read a program Message-ID: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> ive been using diveintopython to learn how to write programs but i want to sink my teeth into reading some bigger programs, to study them and maybe pick up something new, especially from programs where the development isn't well document (unlike something like pidgin's development documentation which is insanely detailed). are there any specific pieces of software written in python you would recommend a novice to read? programs that illustrate python at its finest, beautiful stretches of code? thanks for any help anthony -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 6 22:43:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Jun 2008 16:43:40 -0400 Subject: [Tutor] TurtleWorld Windows issue In-Reply-To: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> References: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> Message-ID: <1c2a2c590806061343u62b7b995x7f69e712581bd85a@mail.gmail.com> On Fri, Jun 6, 2008 at 2:26 PM, wrote: > I am working through _Think Python_ in spare time at work on a Windows > machine (so another OS is not an option). I can't get TurtleWorld to run > as described in the book Try using TurtleWorld without IDLE. IDLE is a Tkinter program itself and it doesn't always play well with other Tkinter programs such as TurtleWorld. I was able to use TW from a DOS window on WinXP. Kent From mjain at buzzient.com Fri Jun 6 23:52:05 2008 From: mjain at buzzient.com (Mohit Jain) Date: Fri, 6 Jun 2008 17:52:05 -0400 Subject: [Tutor] Batch insert Message-ID: <6847d99f0806061452v7681bfffudcfc46f4cfd31850@mail.gmail.com> Hello all, I am new to python. I wanted to know how can i do batch insert into Mysql using python. A code snippet would be really helpful. Thanks a lot Mohit -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Sat Jun 7 00:37:25 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 7 Jun 2008 00:37:25 +0200 Subject: [Tutor] [Fwd: Re: Intercepting methods calls] In-Reply-To: <33587.66.218.47.125.1212769163.squirrel@mail.tigertech.net> References: <29655.66.201.58.8.1212617935.squirrel@mail.tigertech.net> <200806051839.36442.andreas@kostyrka.org> <33587.66.218.47.125.1212769163.squirrel@mail.tigertech.net> Message-ID: <200806070037.30232.andreas@kostyrka.org> On Friday 06 June 2008 18:19:23 you wrote: > On Thu, June 5, 2008 9:39 am, Andreas Kostyrka wrote: > > On Thursday 05 June 2008 00:18:55 Marilyn Davis wrote: > >> You listed __init__ and I'm not sure I know what you mean. > > > > Well, __init__ can assign attributes to the instance that are callable. > > Oh, well, Python is such a wide-open system. It keeps blowing my mind. Well, there is basically nothing that you cannot force the object system of Python to do, almost. E.g. transplanting methods from class A to class B: B.__dict__["method"] = A.__dict__["method"] Or deriving a class from itself (although a better name would be "from a class that happened to be named the same). class A: pass class A(A): pass print A.__bases__ Now, as an observation, you will notice that most experienced Python developers usually stay away from all this "magic" stuff. Rules of thumb include "explicit is good, implicit is bad", and so on. Clearly stuff tagged as "you really should know what you are doing". > > I'm thinking that if you can provide an __init__ you can intercept methods > the regular way, by providing them the regular way, and overriding them. Nope, I mentioned it, because this has been way back, when Python was young and slow, this was a technique to speed up method lookup. Actually, it seems to work with py2.5 too, for oldstyle classes: andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def m(self): pass' 10000000 loops, best of 3: 0.0675 usec per loop andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def m(self): pass' -s 'a=A()' 'a.m()' 1000000 loops, best of 3: 0.747 usec per loop andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def m(self): pass' -s 'a=A()' -s 'a.m=a.m' 'a.m()' 1000000 loops, best of 3: 0.575 usec per loop andreas at andi-lap:~/Videos$ python -m timeit -s 'class A(object):' -s ' def m(self): pass' -s 'a=A()' 'a.m()' 1000000 loops, best of 3: 0.671 usec per loop andreas at andi-lap:~/Videos$ python -m timeit -s 'class A(object):' -s ' def m(self): pass' -s 'a=A()' -s 'a.m=a.m' 'a.m()' 1000000 loops, best of 3: 0.641 usec per loop The reason for this is, that the instance dictionary is the first place that Python looks when looking for a.m. > > Thank you Andreas. This has been really interesting and instructive. Yeah, but please consider my comment. I think every developer should have seen the possibilities, but in most cases forget about that ugly stuff. You will get a headache, especially if you try to use the full "power" that Python provides. One can usually be quite productive without relying on these mechanisms. Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From alan.gauld at btinternet.com Sat Jun 7 01:16:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jun 2008 00:16:46 +0100 Subject: [Tutor] how to read a program References: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> Message-ID: "Anthony Parks" wrote > which is insanely detailed). are there any specific pieces of > software > written in python you would recommend a novice to read? programs > that > illustrate python at its finest, beautiful stretches of code? thanks > for any > help You could start with the Python standard library. Many of the modules there are fairly sparecly documented, partly because they are quite well written! Then look at the tools that ship with Python. Then just search SourceForge for python projects. Alan G From alan.gauld at btinternet.com Sat Jun 7 01:18:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jun 2008 00:18:54 +0100 Subject: [Tutor] Batch insert References: <6847d99f0806061452v7681bfffudcfc46f4cfd31850@mail.gmail.com> Message-ID: "Mohit Jain" wrote > I am new to python. I wanted to know how can i do batch insert into > Mysql > using python. A code snippet would be really helpful. If you can do it in SQL then it should be possible. Do you know the SQL commands? Have you tried using them like any other SQL command? What happened? I've never really used MySql much so don;t kniow for sure, but it seems to me that it should just work. Alan G. From alan.gauld at btinternet.com Sat Jun 7 01:22:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jun 2008 00:22:53 +0100 Subject: [Tutor] TurtleWorld Windows issue References: <22146.149.136.25.254.1212776775.squirrel@webmail.sonic.net> Message-ID: wrote > machine (so another OS is not an option). I can't get TurtleWorld > to run > as described in the book > (http://www.greenteapress.com/thinkpython/html/book005.html). I know nothing of TurtleWorld but... >>>> from TurtleWorld import * >>>> TurtleWorld() > > > No new window appears, or if it appears, it closes nearly > instantaneously. Thats what I'd expect... >>>> bob = Turtle() > A new but empty window appears, titled "TurtleWorld (Not > Responding)" Thats also what I'd expect since you have created a turtle but not drawn anything yet. Check the methjods, you may need to make the turtle visible, put the pen down, and move it around a bit. If pen down is default(it usually is) try doing bob.forward(50) Does that do anything? Presumably thre are some drawing examples in the book... Alan G > > Opening and running the TurtleWorld module through the Idle GUI menu > produces a functioning TurtleWorld window, but this is not useful > for the > purposes of the exercises. > > This is probably more of an Idle/Windows issue than a python issue, > but I > won't be able to get through Think Python unless I resolve it. Does > anyone > have an answer? > > Thanks! > > Oliver > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From marilyn at deliberate.com Sat Jun 7 01:27:23 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 6 Jun 2008 16:27:23 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Intercepting methods calls] In-Reply-To: <200806070037.30232.andreas@kostyrka.org> References: <29655.66.201.58.8.1212617935.squirrel@mail.tigertech.net> <200806051839.36442.andreas@kostyrka.org> <33587.66.218.47.125.1212769163.squirrel@mail.tigertech.net> <200806070037.30232.andreas@kostyrka.org> Message-ID: <53586.66.218.47.125.1212794843.squirrel@mail.tigertech.net> On Fri, June 6, 2008 3:37 pm, Andreas Kostyrka wrote: > On Friday 06 June 2008 18:19:23 you wrote: > >> On Thu, June 5, 2008 9:39 am, Andreas Kostyrka wrote: >> >>> On Thursday 05 June 2008 00:18:55 Marilyn Davis wrote: >>> >>>> You listed __init__ and I'm not sure I know what you mean. >>>> >>> >>> Well, __init__ can assign attributes to the instance that are >>> callable. >> >> Oh, well, Python is such a wide-open system. It keeps blowing my >> mind. > > Well, there is basically nothing that you cannot force the object system > of Python to do, almost. > > E.g. transplanting methods from class A to class B: > > > B.__dict__["method"] = A.__dict__["method"] Oh dear. > > > Or deriving a class from itself (although a better name would be "from a > class that happened to be named the same). > > class A: pass class A(A): pass print A.__bases__ Oh dear. > > Now, as an observation, you will notice that most experienced Python > developers usually stay away from all this "magic" stuff. Rules of thumb > include "explicit is good, implicit is bad", and so on. Clearly stuff > tagged as "you really should know what you are doing". > >> >> I'm thinking that if you can provide an __init__ you can intercept >> methods the regular way, by providing them the regular way, and >> overriding them. > > Nope, I mentioned it, because this has been way back, when Python was > young and slow, this was a technique to speed up method lookup. > > Actually, it seems to work with py2.5 too, for oldstyle classes: > > > andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def > m(self): pass' > 10000000 loops, best of 3: 0.0675 usec per loop > andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def > m(self): pass' -s 'a=A()' 'a.m()' > 1000000 loops, best of 3: 0.747 usec per loop > andreas at andi-lap:~/Videos$ python -m timeit -s 'class A:' -s ' def > m(self): pass' -s 'a=A()' -s 'a.m=a.m' 'a.m()' > 1000000 loops, best of 3: 0.575 usec per loop Wow. > andreas at andi-lap:~/Videos$ python -m timeit -s 'class A(object):' -s ' > def m(self): pass' -s 'a=A()' 'a.m()' 1000000 loops, best of 3: 0.671 usec > per loop andreas at andi-lap:~/Videos$ python -m timeit -s 'class A(object):' > -s ' def m(self): pass' -s 'a=A()' -s 'a.m=a.m' 'a.m()' > 1000000 loops, best of 3: 0.641 usec per loop > > > The reason for this is, that the instance dictionary is the first place > that Python looks when looking for a.m. I see. Well, that is interesting. I'm glad I asked. > >> >> Thank you Andreas. This has been really interesting and instructive. >> > > Yeah, but please consider my comment. I think every developer should > have seen the possibilities, but in most cases forget about that ugly > stuff. You will get a headache, especially if you try to use the full > "power" that Python provides. One can usually be quite productive without > relying on these mechanisms. Yes, and if you consider the poor readers of your code, and/or if speed isn't so critical, it would be best to forget it. But, thank you for showing this to me. Do you have anything else really interesting to share? Marilyn Davis > > Andreas From abstractpoetry at gmail.com Sat Jun 7 01:34:31 2008 From: abstractpoetry at gmail.com (Anthony Parks) Date: Fri, 6 Jun 2008 19:34:31 -0400 Subject: [Tutor] how to read a program In-Reply-To: References: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> Message-ID: <837dd880806061634p6f5cd8f1ocdc31e2e588360a1@mail.gmail.com> that sounds like good advice, but i think what i meant is something along the lines of: "what are particularly great programs to *read*. not like great software, but great source code. somewhat like treating source code as a literature, what are the classics? On Fri, Jun 6, 2008 at 7:16 PM, Alan Gauld wrote: > > "Anthony Parks" wrote > > which is insanely detailed). are there any specific pieces of software >> written in python you would recommend a novice to read? programs that >> illustrate python at its finest, beautiful stretches of code? thanks for >> any >> help >> > > You could start with the Python standard library. Many of the modules > there are fairly sparecly documented, partly because they are quite > well written! > > Then look at the tools that ship with Python. > > Then just search SourceForge for python projects. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Sat Jun 7 01:38:39 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 6 Jun 2008 16:38:39 -0700 (PDT) Subject: [Tutor] how to read a program In-Reply-To: <837dd880806061634p6f5cd8f1ocdc31e2e588360a1@mail.gmail.com> References: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> <837dd880806061634p6f5cd8f1ocdc31e2e588360a1@mail.gmail.com> Message-ID: <53718.66.218.47.125.1212795519.squirrel@mail.tigertech.net> This is pretty cool: http://aspn.activestate.com/ASPN/Python/Cookbook/ Marilyn Davis On Fri, June 6, 2008 4:34 pm, Anthony Parks wrote: > that sounds like good advice, but i think what i meant is something along > the lines of: > > "what are particularly great programs to *read*. not like great software, > but great source code. somewhat like treating source code as a > literature, what are the classics? > > On Fri, Jun 6, 2008 at 7:16 PM, Alan Gauld > wrote: > > >> >> "Anthony Parks" wrote >> >> >> which is insanely detailed). are there any specific pieces of software >>> written in python you would recommend a novice to read? programs that >>> illustrate python at its finest, beautiful stretches of code? thanks >>> for any help >>> >> >> You could start with the Python standard library. Many of the modules >> there are fairly sparecly documented, partly because they are quite well >> written! >> >> Then look at the tools that ship with Python. >> >> >> Then just search SourceForge for python projects. >> >> >> Alan G >> >> >> _______________________________________________ >> 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 pk.python at gmail.com Sat Jun 7 04:28:22 2008 From: pk.python at gmail.com (Prosenjit Kundu) Date: Sat, 07 Jun 2008 07:58:22 +0530 Subject: [Tutor] how to read a program In-Reply-To: <53718.66.218.47.125.1212795519.squirrel@mail.tigertech.net> References: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> <837dd880806061634p6f5cd8f1ocdc31e2e588360a1@mail.gmail.com> <53718.66.218.47.125.1212795519.squirrel@mail.tigertech.net> Message-ID: <4849F246.3070408@gmail.com> Marilyn Davis wrote: > This is pretty cool: > > http://aspn.activestate.com/ASPN/Python/Cookbook/ > > Marilyn Davis > > On Fri, June 6, 2008 4:34 pm, Anthony Parks wrote: > > >> that sounds like good advice, but i think what i meant is something along >> the lines of: >> >> "what are particularly great programs to *read*. not like great software, >> but great source code. somewhat like treating source code as a >> literature, what are the classics? >> >> On Fri, Jun 6, 2008 at 7:16 PM, Alan Gauld >> wrote: >> >> >> >>> "Anthony Parks" wrote >>> >>> >>> which is insanely detailed). are there any specific pieces of software >>> >>>> written in python you would recommend a novice to read? programs that >>>> illustrate python at its finest, beautiful stretches of code? thanks >>>> for any help >>>> >>>> >>> You could start with the Python standard library. Many of the modules >>> there are fairly sparecly documented, partly because they are quite well >>> written! >>> >>> Then look at the tools that ship with Python. >>> >>> >>> Then just search SourceForge for python projects. >>> >>> >>> Alan G >>> >>> >>> _______________________________________________ >>> 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 > try this to fetch all code : ############################################## import urllib,re,sys,string fileInName = raw_input('Enter the drive and the full path name, with trailing backslash where the Python .py files will end up-->') for x in range(1,2206,20): url = 'http://aspn.activestate.com/ASPN/Cookbook/Python?query_start=' + str(x) f = urllib.urlopen(url) s = f.read() f.close() matches = re.findall("/ASPN/Cookbook/Python/Recipe/(\d*)",s) pattern = '/ASPN/Cookbook/Python/Recipe/.*.(?=<)' name_matches = re.findall(pattern,s) for z in range (len(name_matches)): try: if int(matches[z]) < int(100000): end = 36 else: end = 37 except: end = 36 name_matches[z] = '_' + str(re.sub("[\[\`\~\!\@\#\$\%\ \^\&\*\(\)\_\+\-\=\{\}\\\:\;\<\>\,\.\?\/\|\'\"\]]",'_',name_matches[z][end:])) name_matches[z] = string.rstrip(name_matches[z],'_a') while '__' in name_matches[z]: name_matches[z] = string.replace(name_matches[z], '__', '_') name_matches[z] = '_' + matches[z] + name_matches[z] + '.py' name_matches[z] = string.replace(name_matches[z], '_py.py', '.py') name_matches[z] = string.replace(name_matches[z], '_by.py', '.py') name_matches[z] = string.replace(name_matches[z], 'quot_', '') url = 'http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/' + str(matches[z]) + '/index_txt' f = urllib.urlopen(url) s = f.read() f.close() fileOutName = str(fileInName) + str(name_matches[z]) fileOut = open(fileOutName, 'w') fileOut.write(s) fileOut.close() print "I'm finished."; - Prosenjit From alan.gauld at btinternet.com Sat Jun 7 10:04:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jun 2008 09:04:16 +0100 Subject: [Tutor] how to read a program References: <837dd880806061245i12792997m1a8901efb18e5cd9@mail.gmail.com> <837dd880806061634p6f5cd8f1ocdc31e2e588360a1@mail.gmail.com> Message-ID: "Anthony Parks" wrote > "what are particularly great programs to *read*. not like great > software, > but great source code. somewhat like treating source code as a > literature, > what are the classics? I don't know anything specific in Python but one of the greatest pieces of programming code ever is Donald Knuth's TeX program, upon which LaTeX is built. For a long time (maybe still) Knuth offered cash rewards for anyone who could find a bug in TeX... a few were found but not many. There is a good write up on TeX on wikipedia explaining many of the important new concepts it introduced, most important in this context being the idea ogf literate programming - programs specifically designed to be easy to read... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Sat Jun 7 17:27:15 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 7 Jun 2008 08:27:15 -0700 Subject: [Tutor] zip and rar files Message-ID: Does the Python zipfile module work on rar archives? If not, does a similar module exist for rar archives? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From technorapture at gmail.com Sat Jun 7 19:04:45 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Sat, 7 Jun 2008 13:04:45 -0400 Subject: [Tutor] Error-handling for a large modular program In-Reply-To: <4849610E.9000800@gmail.com> References: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> <4849610E.9000800@gmail.com> Message-ID: <376fbdcf0806071004g129698e1i6b0dcf8ad5e42acb@mail.gmail.com> Yes I am aware of the various Python parser packages. But at the current moment the language is changing so I'm just writing a parser as I go along. It probably isn't very good as it combines syntactical analysis with some calculations as it goes along (which isn't really good practice). Once the language design is finalized, I might look into using a proper parser and performing the calculations separately. From ahagenbruch at googlemail.com Sat Jun 7 18:01:38 2008 From: ahagenbruch at googlemail.com (Andre Hagenbruch) Date: Sat, 07 Jun 2008 18:01:38 +0200 Subject: [Tutor] zip and rar files In-Reply-To: References: Message-ID: <484AB0E2.8000803@gmail.com> Dinesh B Vadhia schrieb: Hi Dinesh, > Does the Python zipfile module work on rar archives? If not, does a > similar module exist for rar archives? I don't think so, but pypi is your friend: http://pypi.python.org/pypi?%3Aaction=search&term=rar&submit=search HTH, A. From dave6502 at googlemail.com Sun Jun 8 10:54:13 2008 From: dave6502 at googlemail.com (dave selby) Date: Sun, 8 Jun 2008 09:54:13 +0100 Subject: [Tutor] doc string format ? Message-ID: Hi All, I am trying to improve my code quality and have started using doc strings. What format do you guys use for your doc strings ? I have 'made up' the following general format ... Cheers Dave def gen_vhost(kmotion_dir): """ Generate the kmotion vhost file from vhost_template expanding %directory% strings to their full paths as defined in kmotion.rc arguments : kmotion_dir ... the 'root' directory of kmotion exceptions: exit ... if kmotion.rc cannot be read returns: """ parser = ConfigParser.SafeConfigParser() parsed = parser.read('%s/core/kmotion.rc' % kmotion_dir) try: images_dbase_dir = parser.get('dirs', 'images_dbase_dir') port = parser.get('misc', 'port') LDAP_enabled = parser.get('LDAP', 'enabled') in ['true', 'True', 'yes', 'Yes'] LDAP_url = parser.get('LDAP', 'AuthLDAPUrl') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): ............ -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From dineshbvadhia at hotmail.com Sun Jun 8 12:04:13 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 8 Jun 2008 03:04:13 -0700 Subject: [Tutor] zip and rar files Message-ID: the zipfile module does work or rar zip archives. ----- Original Message ----- From: Dinesh B Vadhia To: tutor at python.org Sent: Saturday, June 07, 2008 8:27 AM Subject: zip and rar files Does the Python zipfile module work on rar archives? If not, does a similar module exist for rar archives? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Sun Jun 8 12:46:37 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 8 Jun 2008 12:46:37 +0200 Subject: [Tutor] Why not to use include? Message-ID: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> I am moving a website from php to python gradually. The first step is replacing the page headers and footers. Currently, each page begins with which contains the porton of the html and the html code to present the website name and logo. Each page ends with which includes a footer note and the closing body and html tags. Of course this is a generalization, but the point is that I need to do something similar in Python. Python discourages the use of includes, and I would like to know why so that I can either rethink my page strategy, or decide to go against the 'recommended practices'. Please enlighten me. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From kent37 at tds.net Sun Jun 8 14:16:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Jun 2008 08:16:18 -0400 Subject: [Tutor] doc string format ? In-Reply-To: References: Message-ID: <1c2a2c590806080516v724a0506t8209e1477bc2eb5e@mail.gmail.com> On Sun, Jun 8, 2008 at 4:54 AM, dave selby wrote: > Hi All, > > I am trying to improve my code quality and have started using doc > strings. What format do you guys use for your doc strings ? PEP 257 has some general recommendations: http://www.python.org/dev/peps/pep-0257/ The standard library has lots of examples. > I have 'made up' the following general format ... > """ > Generate the kmotion vhost file from vhost_template expanding %directory% > strings to their full paths as defined in kmotion.rc > > arguments : > kmotion_dir ... the 'root' directory of kmotion > > exceptions: > exit ... if kmotion.rc cannot be read > > returns: > """ If you are going to use a structured format you might consider a format recognized by a documentation generator such as epydoc: http://epydoc.sourceforge.net/ http://epydoc.sourceforge.net/relatedprojects.html Kent From kent37 at tds.net Sun Jun 8 14:32:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Jun 2008 08:32:36 -0400 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> Message-ID: <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> On Sun, Jun 8, 2008 at 6:46 AM, Dotan Cohen wrote: > I am moving a website from php to python gradually. The first step is > replacing the page headers and footers. I'm not sure how you plan to do this. PHP programs are embedded into web pages. Python web programs output the contents of the web page. This is pretty different. > Currently, each page begins > with which contains the porton > of the html and the html code to present the website name and logo. > Each page ends with which includes a > footer note and the closing body and html tags. Of course this is a > generalization, but the point is that I need to do something similar > in Python. Python discourages the use of includes Python doesn't have anything that functions like an include to incorporate a literal block of text from an external file. I guess you could call that discouragement.... > , and I would like to > know why so that I can either rethink my page strategy, or decide to > go against the 'recommended practices'. You should probably find a Python template package that uses syntax similar to PHP. There is a comparison of three modern template packages here: http://lucumr.pocoo.org/cogitations/2008/01/01/python-template-engine-comparison/ A more complete list is here: http://wiki.python.org/moin/Templating?highlight=%28genshi%29 If your website is complex you might also want to consider a full web framework such as Django or TurboGears. Kent From dotancohen at gmail.com Sun Jun 8 17:13:21 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 8 Jun 2008 18:13:21 +0300 Subject: [Tutor] Why not to use include? In-Reply-To: <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> Message-ID: <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> 2008/6/8 Kent Johnson : > On Sun, Jun 8, 2008 at 6:46 AM, Dotan Cohen wrote: >> I am moving a website from php to python gradually. The first step is >> replacing the page headers and footers. > > I'm not sure how you plan to do this. PHP programs are embedded into > web pages. Python web programs output the contents of the web page. > This is pretty different. Very little of the pages are PHP, most is HTML. I understand that Python can be used as a web scripting language, so I assume that Python can be run in Apache from a page with an .html extension. Is this not the case, with an .httaccess directive? >> Currently, each page begins >> with which contains the porton >> of the html and the html code to present the website name and logo. >> Each page ends with which includes a >> footer note and the closing body and html tags. Of course this is a >> generalization, but the point is that I need to do something similar >> in Python. Python discourages the use of includes > > Python doesn't have anything that functions like an include to > incorporate a literal block of text from an external file. I guess you > could call that discouragement.... Could I do something similar with a function? Something like printHeader() and I would define that function in a class? >> , and I would like to >> know why so that I can either rethink my page strategy, or decide to >> go against the 'recommended practices'. > > You should probably find a Python template package that uses syntax > similar to PHP. There is a comparison of three modern template > packages here: > http://lucumr.pocoo.org/cogitations/2008/01/01/python-template-engine-comparison/ > > A more complete list is here: > http://wiki.python.org/moin/Templating?highlight=%28genshi%29 Thanks, I will go through those. > If your website is complex you might also want to consider a full web > framework such as Django or TurboGears. Since half the reason for the website to exist is for me to learn to program (just for fun) then I would rather not use an existing framework. Thanks for the suggestion, though. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From marilyn at deliberate.com Sun Jun 8 18:48:07 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 8 Jun 2008 09:48:07 -0700 (PDT) Subject: [Tutor] doc string format ? In-Reply-To: References: Message-ID: <36078.209.232.112.211.1212943687.squirrel@mail.tigertech.net> On Sun, June 8, 2008 1:54 am, dave selby wrote: > Hi All, > > > I am trying to improve my code quality and have started using doc > strings. What format do you guys use for your doc strings ? I have 'made > up' the following general format ... Your made-up format looks good. It's great that you give thought to it. I've seen the style-guide where it is suggested that the first line of the doc string for a function is a very short description, starting with a verb, like you did. That description should fit on one line. Then there's a blank line. Then there's the bigger explanation, calling instructions, return values, exceptions raised, copyright notice, maybe. A good thing is to type help("your_module") in the interpreter so that you can see if you like the doc string and if it meshes nicely with what the help facility provides for free. But, mostly, I have to say that your instinct is good. Marilyn Davis > > Cheers > > > Dave > > > > > def gen_vhost(kmotion_dir): """ > Generate the kmotion vhost file from vhost_template expanding %directory% > strings to their full paths as defined in kmotion.rc > > arguments : kmotion_dir ... the 'root' directory of kmotion > > exceptions: > exit ... if kmotion.rc cannot be read > > returns: > """ > parser = ConfigParser.SafeConfigParser() parsed = > parser.read('%s/core/kmotion.rc' % kmotion_dir) try: > images_dbase_dir = parser.get('dirs', 'images_dbase_dir') port = > parser.get('misc', 'port') LDAP_enabled = parser.get('LDAP', 'enabled') in > ['true', > 'True', 'yes', 'Yes'] > LDAP_url = parser.get('LDAP', 'AuthLDAPUrl') > except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): > ............ > -- > > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From amit.pureenergy at gmail.com Sun Jun 8 19:40:08 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Sun, 8 Jun 2008 23:10:08 +0530 Subject: [Tutor] handling MIDI in python Message-ID: Can someone tell me about the libraries that can handle MIDI files and also is their a way in which I can convert an mp3 and wav file into a Midi file within a python program -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Sun Jun 8 19:48:12 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 8 Jun 2008 19:48:12 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> Message-ID: <200806081948.15925.andreas@kostyrka.org> On Sunday 08 June 2008 17:13:21 Dotan Cohen wrote: > 2008/6/8 Kent Johnson : > > On Sun, Jun 8, 2008 at 6:46 AM, Dotan Cohen wrote: > >> I am moving a website from php to python gradually. The first step is > >> replacing the page headers and footers. > > > > I'm not sure how you plan to do this. PHP programs are embedded into > > web pages. Python web programs output the contents of the web page. > > This is pretty different. > > Very little of the pages are PHP, most is HTML. I understand that > Python can be used as a web scripting language, so I assume that > Python can be run in Apache from a page with an .html extension. Is > this not the case, with an .httaccess directive? Generally no. Furthermore, Python is pretty bad language to embed in HTML, as whitespace is significant in Python. > > >> Currently, each page begins > >> with which contains the porton > >> of the html and the html code to present the website name and logo. > >> Each page ends with which includes a > >> footer note and the closing body and html tags. Of course this is a > >> generalization, but the point is that I need to do something similar > >> in Python. Python discourages the use of includes > > > > Python doesn't have anything that functions like an include to > > incorporate a literal block of text from an external file. I guess you > > could call that discouragement.... > > Could I do something similar with a function? Something like > printHeader() and I would define that function in a class? Consult http://wiki.python.org/moin/WebProgramming first, please ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From kent37 at tds.net Sun Jun 8 20:05:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Jun 2008 14:05:52 -0400 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> Message-ID: <1c2a2c590806081105w1d5143e0o396c60658d543828@mail.gmail.com> On Sun, Jun 8, 2008 at 11:13 AM, Dotan Cohen wrote: > Very little of the pages are PHP, most is HTML. I understand that > Python can be used as a web scripting language, so I assume that > Python can be run in Apache from a page with an .html extension. Is > this not the case, with an .httaccess directive? Maybe you want Python Server Pages? http://www.modpython.org/live/current/doc-html/pyapi-psp.html > >>> Currently, each page begins >>> with which contains the porton >>> of the html and the html code to present the website name and logo. >>> Each page ends with which includes a >>> footer note and the closing body and html tags. Of course this is a >>> generalization, but the point is that I need to do something similar >>> in Python. Maybe the parse() function in PSP would do this. > Could I do something similar with a function? Something like > printHeader() and I would define that function in a class? Yes, probably. You don't need to put it in a class, though. There are many different ways to create web pages in Python and the answers to your questions will be different depending on which method you choose so it's hard to be specific here. Kent From abstractpoetry at gmail.com Sun Jun 8 20:15:17 2008 From: abstractpoetry at gmail.com (Anthony Parks) Date: Sun, 8 Jun 2008 14:15:17 -0400 Subject: [Tutor] handling MIDI in python In-Reply-To: References: Message-ID: <837dd880806081115k51943aa2vadeef929116fe3b9@mail.gmail.com> regarding conversion between wav and midi, ive looked into it. like the following article says, you can't. http://www.hitsquad.com/smm/news/9903_101/ i mean, it is possible, but wav and midi are fundamentally different things. midi files contain commands that play sounds based on software synthesizers or synthesizers controlled by external devices, while wav files play recordings. a midi file doesn't have any sound in it, just commands. now its possible to analyze a recording and break it down into a composition of different notes that could generate a midi file, but this is insane and kudos to the few developers who have been able to design such software. On Sun, Jun 8, 2008 at 1:40 PM, amit sethi wrote: > > Can someone tell me about the libraries that can handle MIDI files and also > is their a way in which I can convert an mp3 and wav file into a Midi file > within a python program > > -- > A-M-I-T S|S > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Sun Jun 8 21:11:34 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 8 Jun 2008 22:11:34 +0300 Subject: [Tutor] Why not to use include? In-Reply-To: <200806081948.15925.andreas@kostyrka.org> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> Message-ID: <880dece00806081211y1feaf159v8807b98109e2cee7@mail.gmail.com> 2008/6/8 Andreas Kostyrka : >> Very little of the pages are PHP, most is HTML. I understand that >> Python can be used as a web scripting language, so I assume that >> Python can be run in Apache from a page with an .html extension. Is >> this not the case, with an .httaccess directive? > > Generally no. Oh. > Furthermore, Python is pretty bad language to embed in HTML, as whitespace is > significant in Python. That is one of the things that drew me to Python, actually. I like the indentation structure and in any case I structure my PHP code with indentation as well as {}. >> Could I do something similar with a function? Something like >> printHeader() and I would define that function in a class? > > Consult http://wiki.python.org/moin/WebProgramming first, please ;) Thank you! Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dotancohen at gmail.com Sun Jun 8 21:14:22 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 8 Jun 2008 22:14:22 +0300 Subject: [Tutor] Why not to use include? In-Reply-To: <200806081948.15925.andreas@kostyrka.org> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> Message-ID: <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> 2008/6/8 Andreas Kostyrka : >> Very little of the pages are PHP, most is HTML. I understand that >> Python can be used as a web scripting language, so I assume that >> Python can be run in Apache from a page with an .html extension. Is >> this not the case, with an .httaccess directive? > > Generally no. If this is not the case, then why are there so many "PHP vs. Python" flame wars? PHP is designed for _only_ programming web pages, so far as I understand, so if Python cannot do that why are the two languages compared so often? Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From hedetet at gmail.com Sun Jun 8 21:34:20 2008 From: hedetet at gmail.com (S. Doron) Date: Sun, 8 Jun 2008 22:34:20 +0300 Subject: [Tutor] Adding ctypes to an application with python 2.2 Message-ID: <4711a4d60806081234g359d10e9hfab595821a8f0d46@mail.gmail.com> Hello, I'm new to this list. What I'd like to do is add support for pointers to an old version of python (2.2) in an existing application (a game). Searching around the web, I found the ctypes module which is supposed to add this capability to python. However, I didn't quite understand if and how this could be added (installed) to an existing application which uses python. Alternatively, if it's possible (or easier) to just replace the preexisting version of python with 2.5 by messing around with the dll's somehow, instructions on how to do so would be welcome. Some background information - I'm somewhere between a novice and an intermediate programmer (took intro to C course in university, some highschool programming, and online python tutorials), but have little experience in interfacing with windows, dlls, files, etc. In case you're wondering what I need the pointers for, it's for accessing lower-level functions from the game's console/script files, that aren't otherwise available (I've used dir() to get a list of object methods). -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlangford.cs03 at gtalumni.org Sun Jun 8 22:38:56 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 8 Jun 2008 16:38:56 -0400 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> Message-ID: <82b4f5810806081338j3eecece4y3d28476304a7f1cf@mail.gmail.com> Python makes web pages just fine. There are both embedded technologies (such as the python server pages Kent mentioned above) and template engines based on callbacks (such as django's templates, djangos the whole way, etc). Its extremely easy to make your own templating engine if you don't like python server pages yet you like templating. (Using mod_python or mod_wsgi[recommended] and the substitute function). I suggest you really give wsgi (and mod_wsgi) a good hard look to start off with, as its the python web standard now that all the other toolkits are starting to conform to (or already do). http://www.wsgi.org/wsgi/ Also, be very careful with memory in web python frameworks. Most php processes die every time they are invoked from the web. Often python web frameworks are more persistent then that: http://blog.ianbicking.org/2008/01/12/what-php-deployment-gets-right/ --Michael On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: > 2008/6/8 Andreas Kostyrka : >>> Very little of the pages are PHP, most is HTML. I understand that >>> Python can be used as a web scripting language, so I assume that >>> Python can be run in Apache from a page with an .html extension. Is >>> this not the case, with an .httaccess directive? >> >> Generally no. > > If this is not the case, then why are there so many "PHP vs. Python" > flame wars? PHP is designed for _only_ programming web pages, so far > as I understand, so if Python cannot do that why are the two languages > compared so often? > > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Sun Jun 8 22:40:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Jun 2008 16:40:41 -0400 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> Message-ID: <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: > If this is not the case, then why are there so many "PHP vs. Python" > flame wars? PHP is designed for _only_ programming web pages, so far > as I understand, so if Python cannot do that why are the two languages > compared so often? Python is a general purpose language that can, among other things, be used to generate web pages in many different ways. Possibly none of these ways match your pre-conceptions. Please do some reading. Probably the simplest way to generate a web page from Python is with a cgi module. Here is a simple example: http://wiki.python.org/moin/CgiScripts Kent From dotancohen at gmail.com Sun Jun 8 23:24:14 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 00:24:14 +0300 Subject: [Tutor] Why not to use include? In-Reply-To: <82b4f5810806081338j3eecece4y3d28476304a7f1cf@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <82b4f5810806081338j3eecece4y3d28476304a7f1cf@mail.gmail.com> Message-ID: <880dece00806081424p4e2bb02ewe7963018f4878f4e@mail.gmail.com> 2008/6/8 Michael Langford : > Python makes web pages just fine. There are both embedded technologies > (such as the python server pages Kent mentioned above) and template > engines based on callbacks (such as django's templates, djangos the > whole way, etc). > > Its extremely easy to make your own templating engine if you don't > like python server pages yet you like templating. (Using mod_python or > mod_wsgi[recommended] and the substitute function). > > I suggest you really give wsgi (and mod_wsgi) a good hard look to > start off with, as its the python web standard now that all the other > toolkits are starting to conform to (or already do). > http://www.wsgi.org/wsgi/ > > Also, be very careful with memory in web python frameworks. Most php > processes die every time they are invoked from the web. Often python > web frameworks are more persistent then that: > http://blog.ianbicking.org/2008/01/12/what-php-deployment-gets-right/ > Thank you very much, I will keep that in mind. If I do not have root access, what is the best way to check memory usage? I do have SSH access, of course. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dotancohen at gmail.com Sun Jun 8 23:25:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 00:25:06 +0300 Subject: [Tutor] Why not to use include? In-Reply-To: <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> Message-ID: <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> 2008/6/8 Kent Johnson : > On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: >> If this is not the case, then why are there so many "PHP vs. Python" >> flame wars? PHP is designed for _only_ programming web pages, so far >> as I understand, so if Python cannot do that why are the two languages >> compared so often? > > Python is a general purpose language that can, among other things, be > used to generate web pages in many different ways. Possibly none of > these ways match your pre-conceptions. Please do some reading. > > Probably the simplest way to generate a web page from Python is with a > cgi module. Here is a simple example: > http://wiki.python.org/moin/CgiScripts > I see, it is not exactly what I was expecting. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dineshbvadhia at hotmail.com Mon Jun 9 00:39:58 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 8 Jun 2008 15:39:58 -0700 Subject: [Tutor] Extracting text from XML document Message-ID: I want to extract text from XML (and SGML) documents. I found one program by Paul Prescod (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65128) from 2001. Does anyone know of any programs that are more recent? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 9 01:02:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jun 2008 00:02:41 +0100 Subject: [Tutor] Adding ctypes to an application with python 2.2 References: <4711a4d60806081234g359d10e9hfab595821a8f0d46@mail.gmail.com> Message-ID: "S. Doron" wrote > Hello, I'm new to this list. What I'd like to do is add support for > pointers > to an old version of python (2.2) in an existing application (a > game). What do you mean by "add support for pointers"? Pointers are a very low level memory specific thing in C. In Pascal they are a much higher level logical concept. In Python every variable is a reference to a value, a pointer if you like. So what kind of pointer do you want and why? What do you intend to do with these pointers? > I found the ctypes module which is supposed to add > this capability to python. Not exactly. As the name suggests ctypes allows Python to access code written in C. On Windows that usually means code stored in a DLL. It does not add any new pointer capability to Python itself. > Alternatively, if it's possible (or easier) to just replace the > preexisting > version of python with 2.5 by messing around with the dll's somehow, > instructions on how to do so would be welcome. Again, I don't know what replacing 2.2 with 2.5 would give you that you need? > highschool programming, and online python tutorials), but have > little > experience in interfacing with windows, dlls, files, etc. In case > you're > wondering what I need the pointers for, it's for accessing > lower-level > functions from the game's console/script files, that aren't > otherwise > available (I've used dir() to get a list of object methods). OK, that probably does need ctypes which wuill let you access the functions and convert from the C types to the more usual Python types. There are some ctypes tutorials and examples around which should help. Alan G. From kent37 at tds.net Mon Jun 9 01:21:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Jun 2008 19:21:14 -0400 Subject: [Tutor] Extracting text from XML document In-Reply-To: References: Message-ID: <1c2a2c590806081621t11709555pd9227d38edd26881@mail.gmail.com> On Sun, Jun 8, 2008 at 6:39 PM, Dinesh B Vadhia wrote: > I want to extract text from XML (and SGML) documents. I found one program > by Paul Prescod > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65128) from 2001. > Does anyone know of any programs that are more recent? That recipe looks pretty good to me. If you need more control (e.g. extracting text only from specific elements) look at ElementTree (now in the standard lib). Kent From srilyk at gmail.com Mon Jun 9 14:21:41 2008 From: srilyk at gmail.com (W W) Date: Mon, 9 Jun 2008 07:21:41 -0500 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> Message-ID: <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> Python can *too* import from a txt file (even if it contains HTML): f = open("myfile.html", "r") x = f.read() print x f.close() It even retains formatting (as far as I can tell)... HTH, Wayne On Sun, Jun 8, 2008 at 4:25 PM, Dotan Cohen wrote: > 2008/6/8 Kent Johnson : >> On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: >>> If this is not the case, then why are there so many "PHP vs. Python" >>> flame wars? PHP is designed for _only_ programming web pages, so far >>> as I understand, so if Python cannot do that why are the two languages >>> compared so often? >> >> Python is a general purpose language that can, among other things, be >> used to generate web pages in many different ways. Possibly none of >> these ways match your pre-conceptions. Please do some reading. >> >> Probably the simplest way to generate a web page from Python is with a >> cgi module. Here is a simple example: >> http://wiki.python.org/moin/CgiScripts >> > > I see, it is not exactly what I was expecting. Thanks. > > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From dave6502 at googlemail.com Mon Jun 9 15:04:57 2008 From: dave6502 at googlemail.com (dave selby) Date: Mon, 9 Jun 2008 14:04:57 +0100 Subject: [Tutor] clipping file to size ? Message-ID: Hi All, I need to read parse and re-write the parsed file. I am opening with f = open(file_rc, 'r+') reading file .... f.seek(0) resetting file pointer ... print >> f, section writing smaller file... and I end up with the remnants of the old larger file at the end. any idea how to clip the file to the newer smaller size without closing it and reopening it as a 'w' ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From amit.pureenergy at gmail.com Mon Jun 9 15:20:28 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Mon, 9 Jun 2008 18:50:28 +0530 Subject: [Tutor] (no subject) Message-ID: Hi , Are there any python bindings for sox(sound Exchange). -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jun 9 15:34:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Jun 2008 09:34:42 -0400 Subject: [Tutor] clipping file to size ? In-Reply-To: References: Message-ID: <1c2a2c590806090634q5ce50762pe54d4fd8fbdf7793@mail.gmail.com> On Mon, Jun 9, 2008 at 9:04 AM, dave selby wrote: > writing smaller file... > > and I end up with the remnants of the old larger file at the end. > any idea how to clip the file to the newer smaller size without > closing it and reopening it as a 'w' ? f.truncate() ? Why not re-open the file? Kent From qsqgeekyogdty at tiscali.co.uk Mon Jun 9 16:25:02 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Mon, 9 Jun 2008 15:25:02 +0100 (GMT+01:00) Subject: [Tutor] Empty list validation Message-ID: <15826604.1213021502197.JavaMail.root@ps38> Hello Sorry if this is a basic question, but how do I check if list is empty or not and return True or False ;) Thanks David From srilyk at gmail.com Mon Jun 9 16:54:42 2008 From: srilyk at gmail.com (W W) Date: Mon, 9 Jun 2008 09:54:42 -0500 Subject: [Tutor] Empty list validation In-Reply-To: <15826604.1213021502197.JavaMail.root@ps38> References: <15826604.1213021502197.JavaMail.root@ps38> Message-ID: <333efb450806090754n817b09dl1961fe1034cbc499@mail.gmail.com> >>> def empty_or_not(mylist): ... if mylist: ... print "Not empty" ... elif not mylist: ... print "Empty!" ... >>> empty_or_not([]) Empty! >>> foo = [] >>> empty_or_not(foo) Empty! >>> foo.append('hi') >>> empty_or_not(foo) Not empty My guess is that if any object is empty, it's considered "not". HTH, Wayne On Mon, Jun 9, 2008 at 9:25 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hello > Sorry if this is a basic question, but how do I check if list is empty > or not and return True or False ;) > Thanks > David > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From jikanter at gmail.com Mon Jun 9 16:57:51 2008 From: jikanter at gmail.com (Jordan Kanter) Date: Mon, 9 Jun 2008 09:57:51 -0500 Subject: [Tutor] Why not to use include? In-Reply-To: <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> Message-ID: Another thing you can do is use django templates. they "work" to be similarly to php in the browser, and have something called an "extends" clause (see http://www.djangoproject.com/documentation/templates/) but in the background it is completely python (i.e. the template compiler), so it is not as straight forward as "preprocessing" html, but it amounts to the same. Let me know if that helps, Jordan On Mon, Jun 9, 2008 at 7:21 AM, W W wrote: > Python can *too* import from a txt file (even if it contains HTML): > > f = open("myfile.html", "r") > x = f.read() > print x > f.close() > > It even retains formatting (as far as I can tell)... > > HTH, > Wayne > > On Sun, Jun 8, 2008 at 4:25 PM, Dotan Cohen wrote: >> 2008/6/8 Kent Johnson : >>> On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: >>>> If this is not the case, then why are there so many "PHP vs. Python" >>>> flame wars? PHP is designed for _only_ programming web pages, so far >>>> as I understand, so if Python cannot do that why are the two languages >>>> compared so often? >>> >>> Python is a general purpose language that can, among other things, be >>> used to generate web pages in many different ways. Possibly none of >>> these ways match your pre-conceptions. Please do some reading. >>> >>> Probably the simplest way to generate a web page from Python is with a >>> cgi module. Here is a simple example: >>> http://wiki.python.org/moin/CgiScripts >>> >> >> I see, it is not exactly what I was expecting. Thanks. >> >> Dotan Cohen >> >> http://what-is-what.com >> http://gibberish.co.il >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> >> A: Because it messes up the order in which people normally read text. >> Q: Why is top-posting such a bad thing? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Jordan Kanter email: jikanter |at| gmail |dot| com mobile: (847)436-6388 IRC(Freenode): jikanter From jikanter at gmail.com Mon Jun 9 16:59:04 2008 From: jikanter at gmail.com (Jordan Kanter) Date: Mon, 9 Jun 2008 09:59:04 -0500 Subject: [Tutor] Why not to use include? In-Reply-To: References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> Message-ID: sorry about the spelling. that second sentence should be "the work out to be similar to php in the browser". On Mon, Jun 9, 2008 at 9:57 AM, Jordan Kanter wrote: > Another thing you can do is use django templates. they "work" to be > similarly to php in the browser, and have something called an > "extends" clause (see > http://www.djangoproject.com/documentation/templates/) but in the > background it is completely python (i.e. the template compiler), so it > is not as straight forward as > "preprocessing" html, but it amounts to the same. > > Let me know if that helps, > > Jordan > > On Mon, Jun 9, 2008 at 7:21 AM, W W wrote: >> Python can *too* import from a txt file (even if it contains HTML): >> >> f = open("myfile.html", "r") >> x = f.read() >> print x >> f.close() >> >> It even retains formatting (as far as I can tell)... >> >> HTH, >> Wayne >> >> On Sun, Jun 8, 2008 at 4:25 PM, Dotan Cohen wrote: >>> 2008/6/8 Kent Johnson : >>>> On Sun, Jun 8, 2008 at 3:14 PM, Dotan Cohen wrote: >>>>> If this is not the case, then why are there so many "PHP vs. Python" >>>>> flame wars? PHP is designed for _only_ programming web pages, so far >>>>> as I understand, so if Python cannot do that why are the two languages >>>>> compared so often? >>>> >>>> Python is a general purpose language that can, among other things, be >>>> used to generate web pages in many different ways. Possibly none of >>>> these ways match your pre-conceptions. Please do some reading. >>>> >>>> Probably the simplest way to generate a web page from Python is with a >>>> cgi module. Here is a simple example: >>>> http://wiki.python.org/moin/CgiScripts >>>> >>> >>> I see, it is not exactly what I was expecting. Thanks. >>> >>> Dotan Cohen >>> >>> http://what-is-what.com >>> http://gibberish.co.il >>> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >>> >>> A: Because it messes up the order in which people normally read text. >>> Q: Why is top-posting such a bad thing? >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> -- >> To be considered stupid and to be told so is more painful than being >> called gluttonous, mendacious, violent, lascivious, lazy, cowardly: >> every weakness, every vice, has found its defenders, its rhetoric, its >> ennoblement and exaltation, but stupidity hasn't. - Primo Levi >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Jordan Kanter > email: jikanter |at| gmail |dot| com > mobile: (847)436-6388 > IRC(Freenode): jikanter > -- Jordan Kanter email: jikanter |at| gmail |dot| com mobile: (847)436-6388 IRC(Freenode): jikanter From csshyamsundar at gmail.com Mon Jun 9 17:08:18 2008 From: csshyamsundar at gmail.com (C S Shyam Sundar) Date: Mon, 9 Jun 2008 20:38:18 +0530 Subject: [Tutor] Empty list validation In-Reply-To: <333efb450806090754n817b09dl1961fe1034cbc499@mail.gmail.com> References: <15826604.1213021502197.JavaMail.root@ps38> <333efb450806090754n817b09dl1961fe1034cbc499@mail.gmail.com> Message-ID: <7a8039fa0806090808h500194cau1d56eb8cc3daab2d@mail.gmail.com> One another simple method is to check its count using the *len *method. eg: if len(mylist) == 0: print "empty list" This is particularly useful in situations where checking emptiness alone is not enough. On Mon, Jun 9, 2008 at 8:24 PM, W W wrote: > >>> def empty_or_not(mylist): > ... if mylist: > ... print "Not empty" > ... elif not mylist: > ... print "Empty!" > ... > >>> empty_or_not([]) > Empty! > >>> foo = [] > >>> empty_or_not(foo) > Empty! > >>> foo.append('hi') > >>> empty_or_not(foo) > Not empty > > My guess is that if any object is empty, it's considered "not". > > HTH, > Wayne > > > On Mon, Jun 9, 2008 at 9:25 AM, qsqgeekyogdty at tiscali.co.uk > wrote: > > Hello > > Sorry if this is a basic question, but how do I check if list is empty > > or not and return True or False ;) > > Thanks > > David > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- C S Shyam Sundar [mobile] +91-97877-SHYAM | [voip] +1-425-998-1134 "It's easy to tell the difference between right and wrong. What's hard is choosing the wrong that's more right." -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Mon Jun 9 17:09:52 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 9 Jun 2008 09:09:52 -0600 Subject: [Tutor] Why not to use include? In-Reply-To: <82b4f5810806081338j3eecece4y3d28476304a7f1cf@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com><1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com><880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com><200806081948.15925.andreas@kostyrka.org><880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <82b4f5810806081338j3eecece4y3d28476304a7f1cf@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D027C452F@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Michael Langford > Sent: Sunday, June 08, 2008 2:39 PM > To: Dotan Cohen > Cc: tutor at python.org > Subject: Re: [Tutor] Why not to use include? > > Python makes web pages just fine. There are both embedded technologies > (such as the python server pages Kent mentioned above) and template > engines based on callbacks (such as django's templates, djangos the > whole way, etc). > > Its extremely easy to make your own templating engine if you don't > like python server pages yet you like templating. (Using mod_python or > mod_wsgi[recommended] and the substitute function). > Other than a learning exercise or having a different idea about templating, I'd go with an existing template solution like Cheetah, Mako, Kid, Genshi. Mike From kent37 at tds.net Mon Jun 9 17:23:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Jun 2008 11:23:09 -0400 Subject: [Tutor] Empty list validation In-Reply-To: <15826604.1213021502197.JavaMail.root@ps38> References: <15826604.1213021502197.JavaMail.root@ps38> Message-ID: <1c2a2c590806090823q1168c51eg73aedfe0baba3e13@mail.gmail.com> On Mon, Jun 9, 2008 at 10:25 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hello > Sorry if this is a basic question, but how do I check if list is empty > or not and return True or False ;) You can test the list directly, if it is empty it will evaluate to False: if (myList): print 'Something in list' else: print 'list is empty' All containers (list, dict, set, string, etc) work this way: "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true." http://docs.python.org/ref/Booleans.html If you really need a boolean value for some reason, use bool(myList). Kent From simozack at yahoo.it Mon Jun 9 17:51:23 2008 From: simozack at yahoo.it (simone) Date: Mon, 09 Jun 2008 17:51:23 +0200 Subject: [Tutor] Empty list validation In-Reply-To: <15826604.1213021502197.JavaMail.root@ps38> References: <15826604.1213021502197.JavaMail.root@ps38> Message-ID: <484D517B.8010403@yahoo.it> qsqgeekyogdty at tiscali.co.uk ha scritto: > Sorry if this is a basic question, but how do I check if list is empty > or not and return True or False ;) Normally, in Python, there are these evaluation: 1) True == 1 2) False == 0 3) Empty or have not value == False == 0 4) Not empty or have value == True == 1 So, consider this example: >>> def isEmpty(l): if l: print "The list is NOT empty!" else: print "The list is empty!" >>> list = [] >>> isEmpty(list) The list is empty! >>> list = ['hi'] >>> isEmpty(list) The list is NOT empty! >>> HTH, Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From srilyk at gmail.com Mon Jun 9 17:51:25 2008 From: srilyk at gmail.com (W W) Date: Mon, 9 Jun 2008 10:51:25 -0500 Subject: [Tutor] Controlling applications Message-ID: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Hi, I've done some cursory searches, and it doesn't appear that what I want to do is popular, if it's even possible. I'm trying to control other applications via python (specifically my web browser). My hope is there is some way to emulate a series of keypresses. My goal is to have a script that will automatically retrieve my banking information. Originally I was planning to use urllib to post/retrieve the data, but as far as I can tell, the bank uses several variables and some javascript to authenticate everything, and it seems overly complicated to try and manually figure it all out. Is there a way to utilize python to perform keypresses? And does anyone know of a tutorial for such a thing? I'm running the most recently updated Ubuntu 8.04. TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From dotancohen at gmail.com Mon Jun 9 17:54:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 17:54:06 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> Message-ID: <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> 2008/6/9 W W : > Python can *too* import from a txt file (even if it contains HTML): > > f = open("myfile.html", "r") > x = f.read() > print x > f.close() > > It even retains formatting (as far as I can tell)... > > HTH, > Wayne > Thanks, Wayne, I am actually aware of this method. But it seems that what I really want _is_ a function, and not a simple include. The header prints, among other things, the page title which I pass to the include as a simple variable in PHP. I never realized how broken of a design that is until now. One thing I've just learned: the arguments that PHP encourages bad programming are true (not to knock the language, which I happen to enjoy). I must learn about these things, I've discovered, in this order: 1) How to use Python as an apache module, not as cgi. Each page, at least to the outside world, must have an .html extension. 2) I must learn about classes, and how to include classes in specific pages. 3) How to access GET, POST, and environmental values in Python. By environmental values I mean the requesting page's IP address, UA details such as preferred language and charset (which I use to serve the homepage in one of two languages), the query string, etc. 4) How to access and work with MySQL. I am familiar with SQL, it is just the python integration I need to learn (how to send a query, how to parse the reply). 5) How to work with cookies in Python. 6) How to send mail with Python and sendmail. 7) How to manipulate images with Python. From what I understand this is _not_ possible, so I may have to stick with php on this one. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dotancohen at gmail.com Mon Jun 9 17:55:38 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 17:55:38 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> Message-ID: <880dece00806090855m251f502qbb09300ba58c17a7@mail.gmail.com> 2008/6/9 Jordan Kanter : > Another thing you can do is use django templates. they "work" to be > similarly to php in the browser, and have something called an > "extends" clause (see > http://www.djangoproject.com/documentation/templates/) but in the > background it is completely python (i.e. the template compiler), so it > is not as straight forward as > "preprocessing" html, but it amounts to the same. > > Let me know if that helps, > > Jordan > Thanks, Jordan, I don't exactly understand but I will start googling and I'll see if django fits my needs. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From srilyk at gmail.com Mon Jun 9 18:15:13 2008 From: srilyk at gmail.com (W W) Date: Mon, 9 Jun 2008 11:15:13 -0500 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> Message-ID: <333efb450806090915j5400c422o7e80e15ec86b3c6b@mail.gmail.com> > Thanks, Wayne, I am actually aware of this method. But it seems that > what I really want _is_ a function, and not a simple include. When you say function, exactly what are you referring to? Because really all a function *is* is a set of statements that takes input* does something* gives output* *optional For instance, in PHP, include('header.php') is a function that works similar to the few lines of code I wrote earlier. the input to the include function is the filename, the process or "does something" is it opens the file, and the output is returning it into the php file. -Wayne From dotancohen at gmail.com Mon Jun 9 18:21:23 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 18:21:23 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: <333efb450806090915j5400c422o7e80e15ec86b3c6b@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> <333efb450806090915j5400c422o7e80e15ec86b3c6b@mail.gmail.com> Message-ID: <880dece00806090921p5d0b7febt3a6a2dafe72b39bc@mail.gmail.com> 2008/6/9 W W : >> Thanks, Wayne, I am actually aware of this method. But it seems that >> what I really want _is_ a function, and not a simple include. > > When you say function, exactly what are you referring to? Because > really all a function *is* is a set of statements that > > takes input* > does something* > gives output* > > *optional > > For instance, in PHP, include('header.php') is a function that works > similar to the few lines of code I wrote earlier. > > the input to the include function is the filename, the process or > "does something" is it opens the file, and the output is returning it > into the php file. > I was doing this in PHP: $title="Page title"; include"/path/to/header.php"; In Python I suppose that I will do something like this: makeHeader("Page title") I would define makeHeader() in a class, so that I could use it (and other functions) across multiple pages. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From qsqgeekyogdty at tiscali.co.uk Mon Jun 9 18:21:55 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Mon, 9 Jun 2008 17:21:55 +0100 (GMT+01:00) Subject: [Tutor] Empty list validation Message-ID: <27660372.1213028515529.JavaMail.root@ps38> Thank you all for the replies. the 'else' is this necessary, surely when you have an: >>> if x: ... print 'x' ... print 'y' is this correct? From srilyk at gmail.com Mon Jun 9 18:52:44 2008 From: srilyk at gmail.com (W W) Date: Mon, 9 Jun 2008 11:52:44 -0500 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806090921p5d0b7febt3a6a2dafe72b39bc@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> <333efb450806090915j5400c422o7e80e15ec86b3c6b@mail.gmail.com> <880dece00806090921p5d0b7febt3a6a2dafe72b39bc@mail.gmail.com> Message-ID: <333efb450806090952r791513bauecbae70d74b6e401@mail.gmail.com> On Mon, Jun 9, 2008 at 11:21 AM, Dotan Cohen wrote: > 2008/6/9 W W : > I was doing this in PHP: > $title="Page title"; > include"/path/to/header.php"; > So in your header.php you had some source: echo "$title\n"; or something to that effect? > In Python I suppose that I will do something like this: > makeHeader("Page title") > > I would define makeHeader() in a class, so that I could use it (and > other functions) across multiple pages. Though I'm not entirely sure how you would (and I'm sure one of the other web frameworks probably already does such a thing), you could probably create methods (just a function inside a class, from what I've been told) that could do something along the lines of: makeHeader.title("Page title") makeHeader.bgcolor("#000000") makeHeader.css("css/mystyle.css") or any other various types of header information you use, if that sort of thing fits into your needs/wants. Or even like many functions in python: makeHeader.body("#00ff00", 0, 0, "images/bgnew.gif"), though my guess is that again, some other web framework already has those features. HTH, Wayne From hedetet at gmail.com Mon Jun 9 19:48:10 2008 From: hedetet at gmail.com (S. Doron) Date: Mon, 9 Jun 2008 20:48:10 +0300 Subject: [Tutor] Adding ctypes to an application with python 2.2 In-Reply-To: References: <4711a4d60806081234g359d10e9hfab595821a8f0d46@mail.gmail.com> Message-ID: <4711a4d60806091048l18532081w2b51108b8fb22298@mail.gmail.com> On Mon, Jun 9, 2008 at 2:02 AM, Alan Gauld wrote: > "S. Doron" wrote > > Hello, I'm new to this list. What I'd like to do is add support for >> pointers >> to an old version of python (2.2) in an existing application (a game). >> > > What do you mean by "add support for pointers"? > Pointers are a very low level memory specific thing in C. > In Pascal they are a much higher level logical concept. > In Python every variable is a reference to a value, a pointer if you like. > > So what kind of pointer do you want and why? > What do you intend to do with these pointers? > > I found the ctypes module which is supposed to add >> this capability to python. >> > > Not exactly. As the name suggests ctypes allows Python > to access code written in C. On Windows that usually means > code stored in a DLL. It does not add any new pointer > capability to Python itself. > > Alternatively, if it's possible (or easier) to just replace the >> preexisting >> version of python with 2.5 by messing around with the dll's somehow, >> instructions on how to do so would be welcome. >> > > Again, I don't know what replacing 2.2 with 2.5 would give you > that you need? > > highschool programming, and online python tutorials), but have little >> experience in interfacing with windows, dlls, files, etc. In case you're >> wondering what I need the pointers for, it's for accessing lower-level >> functions from the game's console/script files, that aren't otherwise >> available (I've used dir() to get a list of object methods). >> > > OK, that probably does need ctypes which wuill let you access the > functions and convert from the C types to the more usual Python types. > There are some ctypes tutorials and examples around which should help. > > Alan G. > > I've tried reading tutorials, but I can't make heads or tails of the installation instructions. For instance, I'm not sure whether the installation instructions included in ctypes are even relevant. Do I need to set it up if I just want to add the module to the application, or do I just copy relevant .py files? Am I supposed to compile anything? The ctypes\__init__.py file tries to import _ctypes, but there is no _ctypes.py file (there is a _ctypes.c file, though). And do I need libffi installed if I'm using windows? If so, where and how do I install it? (the libffi readme is kind of fuzzy) Lastly, should the need to compile the _ctypes.c file arise, what free C compiler would you recommend? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jun 9 19:48:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Jun 2008 13:48:50 -0400 Subject: [Tutor] Why not to use include? In-Reply-To: <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> Message-ID: <1c2a2c590806091048s1c5ebcf1rccbcdd83fe6c74ae@mail.gmail.com> On Mon, Jun 9, 2008 at 11:54 AM, Dotan Cohen wrote: > I must learn about these things, I've discovered, in this order: I suggest you look at Django, it helps with most of this. Probably TurboGears does also but I'm not familiar with it. > 1) How to use Python as an apache module, not as cgi. Each page, at > least to the outside world, must have an .html extension. No problem, your URLs can look however you like. > 2) I must learn about classes, and how to include classes in specific pages. This sounds like general programming stuff but if you are talking about your header includes, Django template inheritance provides a good way to include boilerplate on each page. http://www.djangoproject.com/documentation/0.96/templates/#template-inheritance > 3) How to access GET, POST, and environmental values in Python. By > environmental values I mean the requesting page's IP address, UA In the Django request: http://www.djangoproject.com/documentation/0.96/request_response/#attributes > details such as preferred language and charset (which I use to serve > the homepage in one of two languages), the query string, etc. Also in the request, if I understand correctly. > 4) How to access and work with MySQL. I am familiar with SQL, it is > just the python integration I need to learn (how to send a query, how > to parse the reply). http://www.djangoproject.com/documentation/db-api/ > 5) How to work with cookies in Python. Not sure why you need this but Django has support for cookie-based authentication. > 6) How to send mail with Python and sendmail. http://code.djangoproject.com/browser/django/trunk/django/core/mail.py > 7) How to manipulate images with Python. From what I understand this > is _not_ possible, so I may have to stick with php on this one. See Python Imaging Library http://www.pythonware.com/library/pil/handbook/index.htm Kent From dotancohen at gmail.com Mon Jun 9 20:02:32 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 20:02:32 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: <333efb450806090952r791513bauecbae70d74b6e401@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> <333efb450806090915j5400c422o7e80e15ec86b3c6b@mail.gmail.com> <880dece00806090921p5d0b7febt3a6a2dafe72b39bc@mail.gmail.com> <333efb450806090952r791513bauecbae70d74b6e401@mail.gmail.com> Message-ID: <880dece00806091102w446a9dcdx2e8a62b37d1980da@mail.gmail.com> 2008/6/9 W W : > On Mon, Jun 9, 2008 at 11:21 AM, Dotan Cohen wrote: >> 2008/6/9 W W : >> I was doing this in PHP: >> $title="Page title"; >> include"/path/to/header.php"; >> > > So in your header.php you had some source: > > echo "$title\n"; > > or something to that effect? Yes, in general. >> In Python I suppose that I will do something like this: >> makeHeader("Page title") >> >> I would define makeHeader() in a class, so that I could use it (and >> other functions) across multiple pages. > > Though I'm not entirely sure how you would (and I'm sure one of the > other web frameworks probably already does such a thing), you could > probably create methods (just a function inside a class, from what > I've been told) that could do something along the lines of: > > makeHeader.title("Page title") > makeHeader.bgcolor("#000000") > makeHeader.css("css/mystyle.css") > > or any other various types of header information you use, if that sort > of thing fits into your needs/wants. Or even like many functions in > python: makeHeader.body("#00ff00", 0, 0, "images/bgnew.gif"), though > my guess is that again, some other web framework already has those > features. > At what point in the script does the header get output? After the last makeHeader.something call? I actually do have several variables that I send to the header include. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dotancohen at gmail.com Mon Jun 9 20:04:27 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 9 Jun 2008 20:04:27 +0200 Subject: [Tutor] Why not to use include? In-Reply-To: <1c2a2c590806091048s1c5ebcf1rccbcdd83fe6c74ae@mail.gmail.com> References: <880dece00806080346v66c697b8u8a64979c1036b172@mail.gmail.com> <1c2a2c590806080532x7a1dfb64k94851685d612c5bb@mail.gmail.com> <880dece00806080813l2ad8abd7jfcb21fd7dd57ad33@mail.gmail.com> <200806081948.15925.andreas@kostyrka.org> <880dece00806081214u2c6bb072vc62694a34aa8c11f@mail.gmail.com> <1c2a2c590806081340o6bf1642fk9493849b0a545989@mail.gmail.com> <880dece00806081425s2cff62d0k8345eae5a33f0053@mail.gmail.com> <333efb450806090521u624d1642r52f3509a36627046@mail.gmail.com> <880dece00806090854g5012b48aq9cc393ae3670ffb@mail.gmail.com> <1c2a2c590806091048s1c5ebcf1rccbcdd83fe6c74ae@mail.gmail.com> Message-ID: <880dece00806091104w7ca7c536p368f0684a18de11e@mail.gmail.com> 2008/6/9 Kent Johnson : > On Mon, Jun 9, 2008 at 11:54 AM, Dotan Cohen wrote: >> I must learn about these things, I've discovered, in this order: > > I suggest you look at Django, it helps with most of this. Probably > TurboGears does also but I'm not familiar with it. > >> 1) How to use Python as an apache module, not as cgi. Each page, at >> least to the outside world, must have an .html extension. > > No problem, your URLs can look however you like. > >> 2) I must learn about classes, and how to include classes in specific pages. > > This sounds like general programming stuff but if you are talking > about your header includes, Django template inheritance provides a > good way to include boilerplate on each page. > http://www.djangoproject.com/documentation/0.96/templates/#template-inheritance > >> 3) How to access GET, POST, and environmental values in Python. By >> environmental values I mean the requesting page's IP address, UA > > In the Django request: > http://www.djangoproject.com/documentation/0.96/request_response/#attributes > >> details such as preferred language and charset (which I use to serve >> the homepage in one of two languages), the query string, etc. > > Also in the request, if I understand correctly. > >> 4) How to access and work with MySQL. I am familiar with SQL, it is >> just the python integration I need to learn (how to send a query, how >> to parse the reply). > > http://www.djangoproject.com/documentation/db-api/ > >> 5) How to work with cookies in Python. > > Not sure why you need this but Django has support for cookie-based > authentication. > >> 6) How to send mail with Python and sendmail. > > http://code.djangoproject.com/browser/django/trunk/django/core/mail.py > >> 7) How to manipulate images with Python. From what I understand this >> is _not_ possible, so I may have to stick with php on this one. > > See Python Imaging Library > http://www.pythonware.com/library/pil/handbook/index.htm > > Kent > You have me very convinced, Kent, and you've pointed me to some very helpful docs. I think that I will use django, as it seems to be designed for what I intend to do. I though up until now that _python_ is similar to php, but it seems that django with python is what is similar to php. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From alan.gauld at btinternet.com Mon Jun 9 21:13:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jun 2008 20:13:35 +0100 Subject: [Tutor] Controlling applications References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Message-ID: "W W" wrote > I'm trying to control other applications via python (specifically my > web browser). The webbrowser module will maybe give you a start? > My hope is there is some way to emulate a series of keypresses. I know how to do that in Windows but not in Linux! > Is there a way to utilize python to perform keypresses? And does > anyone know of a tutorial for such a thing? I'm running the most > recently updated Ubuntu 8.04. You need to find an API that lets you work at the X windows protocol level. I don;t know of one but will be surprised if there isn't such a beast around somewhere! If you could use a text based browser like lynx it would probably be easier since you could work at the terminal or curses level. Sorry I can't help more, Alan G. From mlangford.cs03 at gtalumni.org Mon Jun 9 21:26:04 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 9 Jun 2008 15:26:04 -0400 Subject: [Tutor] Controlling applications In-Reply-To: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Message-ID: <82b4f5810806091226m446b3257h1210147793c3e399@mail.gmail.com> You're looking for mechanize http://wwwsearch.sourceforge.net/mechanize/ On Mon, Jun 9, 2008 at 11:51 AM, W W wrote: > Hi, > > I've done some cursory searches, and it doesn't appear that what I > want to do is popular, if it's even possible. > > I'm trying to control other applications via python (specifically my > web browser). > > My hope is there is some way to emulate a series of keypresses. My > goal is to have a script that will automatically retrieve my banking > information. Originally I was planning to use urllib to post/retrieve > the data, but as far as I can tell, the bank uses several variables > and some javascript to authenticate everything, and it seems overly > complicated to try and manually figure it all out. > > Is there a way to utilize python to perform keypresses? And does > anyone know of a tutorial for such a thing? I'm running the most > recently updated Ubuntu 8.04. > > TIA, Wayne > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Mon Jun 9 21:48:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Jun 2008 15:48:28 -0400 Subject: [Tutor] Controlling applications In-Reply-To: <82b4f5810806091226m446b3257h1210147793c3e399@mail.gmail.com> References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> <82b4f5810806091226m446b3257h1210147793c3e399@mail.gmail.com> Message-ID: <1c2a2c590806091248x4c8794cblab851282b960c2a@mail.gmail.com> On Mon, Jun 9, 2008 at 3:26 PM, Michael Langford wrote: > You're looking for mechanize > http://wwwsearch.sourceforge.net/mechanize/ Possibly but mechanize emulates a browser, it doesn't control one, which the OP specifically rejected as an option... Kent >> Originally I was planning to use urllib to post/retrieve >> the data, but as far as I can tell, the bank uses several variables >> and some javascript to authenticate everything, and it seems overly >> complicated to try and manually figure it all out. From jeff at drinktomi.com Mon Jun 9 22:18:37 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Mon, 9 Jun 2008 13:18:37 -0700 Subject: [Tutor] Controlling applications In-Reply-To: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Message-ID: <8C9E980A-991C-42F3-BEC7-32B97B0B1C17@drinktomi.com> On Jun 9, 2008, at 8:51 AM, W W wrote: > Originally I was planning to use urllib to post/retrieve > the data, but as far as I can tell, the bank uses several variables > and some javascript to authenticate everything, and it seems overly > complicated to try and manually figure it all out. Raw urllib is a poor way to interact with web sites; it's too low level. Instead you might consider the libraries mechanize and twill. They are essentially web browsers in a library. They won't handle JavaScript, but they do let you retrieve, fill in, and send forms without worrying much about the details of the conversation. You might give them a try before completely giving up on the command line mechanisms. Alas controlling applications is very hard in Unix land and very easy in the Windows world. -jeff From technorapture at gmail.com Mon Jun 9 23:16:48 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 9 Jun 2008 17:16:48 -0400 Subject: [Tutor] Error-handling for a large modular program In-Reply-To: <376fbdcf0806071004g129698e1i6b0dcf8ad5e42acb@mail.gmail.com> References: <376fbdcf0806052107w4feb55edh2cc1a9aef321fa6c@mail.gmail.com> <4849610E.9000800@gmail.com> <376fbdcf0806071004g129698e1i6b0dcf8ad5e42acb@mail.gmail.com> Message-ID: <376fbdcf0806091416v3f037f60s4f9887280e929c9e@mail.gmail.com> Our configuration language has evolved a bit more over the last few days and I've decided to right a recursive descent parser for it. Since this is a learning project for me, I'm writing the parser myself instead of using one of the available packages. I'll see how this affects the error handling. -- The ByteBaker : http://www.bytebaker.com From technorapture at gmail.com Mon Jun 9 23:26:38 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 9 Jun 2008 17:26:38 -0400 Subject: [Tutor] Uniform 'for' behavior for strings and files Message-ID: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> If I do the following: for item in block: where block is a file, then item becomes each line of the file in turn But if block in a large string (let's say the actual text that was in the file), item becomes each character at a time. Is there a way to have a uniform iteration irrespective of whether block is a file or string (ideally one \n-delimited line at a time)? I'm writing a recursive parser, where text is looked at one line at a time, if a block delimiter is found, the block is isolated and the parser is recursively called on the block. I would like to start it off on a file and then each block would be a large string, but the default for behavior is being problematic. I could turn the whole file into a string first, but that might cause problems with large files. Any alternate solutions would be appreciated as well. Thanks, Basu -- The ByteBaker : http://www.bytebaker.com From kent37 at tds.net Tue Jun 10 00:16:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Jun 2008 18:16:51 -0400 Subject: [Tutor] Uniform 'for' behavior for strings and files In-Reply-To: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> References: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> Message-ID: <1c2a2c590806091516i3547eec4wcfdac981f423edfe@mail.gmail.com> On Mon, Jun 9, 2008 at 5:26 PM, Shrutarshi Basu wrote: > If I do the following: > > for item in block: > > where block is a file, then item becomes each line of the file in turn > But if block in a large string (let's say the actual text that was in > the file), item becomes each character at a time. Is there a way to > have a uniform iteration irrespective of whether block is a file or > string (ideally one \n-delimited line at a time)? I would make a smart iterator that distinguishes between a file and a string. For example (untested): def lineIter(fileOrString): if isinstance(fileOrString, file): return iter(fileOrString) return iter(fileOrString.splitlines()) Now you can say for item in lineIter(block): and get lines whether block is a file or a string. Note that lines returned from a file will include newlines while those from a string will not. Kent From demonic.software at gmail.com Tue Jun 10 00:19:06 2008 From: demonic.software at gmail.com (Demonic Software) Date: Mon, 9 Jun 2008 17:19:06 -0500 Subject: [Tutor] Writing a script to interact with an interactive command program Message-ID: Hello, I am trying to write an interactive shell that will pipe input from one source to a shell/program, and then return the input to that source. I have been trying to do this with the os.popen*, and I have not had any success in getting this to work. Here is a basic piece of the code that demonstrates what I am trying to do: # based on code from: http://www.daimi.au.dk/~mailund/css/process-management.html # start a bash shell (cin, cout_cerror) = os.popen4("/bin/bash") # write a command on the input pipe of the shell print "writing ls -all!\n\n" cin.write("ls -all") cin.flush() # print the results of my command print cout_cerror.read() Is there something I should be doing differently to get this behavior. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 10 02:14:27 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 01:14:27 +0100 Subject: [Tutor] Uniform 'for' behavior for strings and files References: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> Message-ID: "Shrutarshi Basu" wrote > for item in block: > > where block is a file, then item becomes each line of the file in > turn > But if block in a large string (let's say the actual text that was > in > the file), item becomes each character at a time. Correct because for iterates over a sequence. It will return whatever the unit of sequence is. So the challenge is to make the sequence represent the data in the units you need. So to make a long string return lines rather than characters you need to break the string into lines. The easiest way to do that is using the split() method: for line in block.read().split(): But of course for files you can just read the lines directly - or indirectly using readlines(). > have a uniform iteration irrespective of whether block is a file or > string (ideally one \n-delimited line at a time)? The for loop is uniform, it is just that the sequence unit is different > default for behavior is being problematic. I could turn the whole > file > into a string first, but that might cause problems with large files. You could write a generator function that returned blocks. That would fit your problem quite well and be memory friendly as well. That way the for would work exactly as you require. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jun 10 02:19:17 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 01:19:17 +0100 Subject: [Tutor] Writing a script to interact with an interactive commandprogram References: Message-ID: "Demonic Software" wrote > (cin, cout_cerror) = os.popen4("/bin/bash") > > # write a command on the input pipe of the shell > print "writing ls -all!\n\n" > cin.write("ls -all") > cin.flush() I would have expected that you needed to pass an explicit newline at the end of the command? Just a guess. Also consider using the subprocess module and the Popen class. os.popen is somewhat deprecated nowadays. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From demonic.software at gmail.com Tue Jun 10 02:55:41 2008 From: demonic.software at gmail.com (Demonic Software) Date: Mon, 9 Jun 2008 19:55:41 -0500 Subject: [Tutor] Writing a script to interact with an interactive commandprogram In-Reply-To: References: Message-ID: Alan, I have been working with the Popen class, and it hangs when I perform the read on the stdout socket. I am not sure how to read from the file object after I perform the write into the process. When I use "communicate" it closes the PIPE and terminates the process. Below are some configurations I tried. # using the Popen.communicate API k = Popen("/bin/bash", shell=True, bufsize=1024, stdin=PIPE, stdout=PIPE, close_fds=True) (stdout, stderr) = k.communicate("ls -all\n") print stdout # Trying to read k.stdout directly k = Popen("/bin/bash", shell=True, bufsize=1024, stdin=PIPE, stdout=PIPE, close_fds=True) k.stdin.write("ls -all\n") k.stdout.read() On Mon, Jun 9, 2008 at 7:19 PM, Alan Gauld wrote: > "Demonic Software" wrote > > (cin, cout_cerror) = os.popen4("/bin/bash") >> >> # write a command on the input pipe of the shell >> print "writing ls -all!\n\n" >> cin.write("ls -all") >> cin.flush() >> > > I would have expected that you needed to pass an explicit newline at the > end of the command? > > Just a guess. > > Also consider using the subprocess module and the Popen class. > os.popen is somewhat deprecated nowadays. > > HTH > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From technorapture at gmail.com Tue Jun 10 05:29:16 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Mon, 9 Jun 2008 23:29:16 -0400 Subject: [Tutor] Uniform 'for' behavior for strings and files In-Reply-To: References: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> Message-ID: <376fbdcf0806092029w22e7c5f2td3295ddef313e734@mail.gmail.com> Thanks for your suggestions, I've decided to go with the smart iterator solution, it's given me the results that I need. The generator solution also seems interesting and I might try it out at a later point. -- The ByteBaker : http://www.bytebaker.com From alan.gauld at btinternet.com Tue Jun 10 10:24:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 09:24:36 +0100 Subject: [Tutor] Writing a script to interact with an interactivecommandprogram References: Message-ID: "Demonic Software" wrote > I have been working with the Popen class, and it hangs when I > perform the > read on the stdout socket. Strange. I get similar results. Yet I've used it successfully in the past. Even simple commands are not returning anything. I will need to do some more digging, I don't know if something changed in v2.5, I don't think I've used subprocess since I upgraded from 2.4 a few weeks ago... Alan G. From gmlists9 at gmail.com Tue Jun 10 12:40:39 2008 From: gmlists9 at gmail.com (glist) Date: Tue, 10 Jun 2008 12:40:39 +0200 Subject: [Tutor] parsing .txt Message-ID: <527df91b0806100340p28db9cc5r6a36a736d8b32f20@mail.gmail.com> Let's say I have a file with this kind of content/lines textdata = ''' %question What is Python? %correct A programming language %wrong A graphical package %wrong An operating system %question Is Computer Science really about computers? %wrong Yes %correct No ''' I want to pose the question to a user and check his answer, so I come up with this solution. Is there a better way thought? I particulary hate that "ptr = -1" hack of mine... questionary = [] ptr = -1 for line in textdata.split('\n'): if line: space = line.find(' ') tag = line[1:space] content = line[space+1:] if tag == "question": ptr += 1 questionary.append({tag : content}) else: questionary[ptr].update({tag : content}) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Jun 10 01:29:34 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 9 Jun 2008 18:29:34 -0500 Subject: [Tutor] Controlling applications In-Reply-To: References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Message-ID: <200806091829.34569.cfuller084@thinkingplanet.net> On Monday 09 June 2008 14:13, Alan Gauld wrote: > You need to find an API that lets you work at the X windows > protocol level. I don;t know of one but will be surprised if > there isn't such a beast around somewhere! This made me think of Tcl's send() function. This web page has some links that may (or not) be useful: http://wiki.tcl.tk/1055 Cheers From snovak at snovak.com Tue Jun 10 13:07:59 2008 From: snovak at snovak.com (Sean Novak) Date: Tue, 10 Jun 2008 07:07:59 -0400 Subject: [Tutor] IDE Message-ID: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> I'm looking for the perfect IDE, preferably open source. I've installed Bluefish, which I find to be a little buggy still. I'm just starting to dive into emacs, which I feel is a little daunting. If someone has tried a few different IDEs and found the one that they love.. I'd be interested in your insight! Thank you! Sean From cfuller084 at thinkingplanet.net Tue Jun 10 04:33:43 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 9 Jun 2008 21:33:43 -0500 Subject: [Tutor] Writing a script to interact with an interactive commandprogram In-Reply-To: References: Message-ID: <200806092133.43119.cfuller084@thinkingplanet.net> On the subject of controlling interactive programs and Tcl, one can hardly forget expect.. now add Python and you probably have what you want: http://www.noah.org/wiki/Pexpect Cheers From limodou.mail at gmail.com Tue Jun 10 13:32:37 2008 From: limodou.mail at gmail.com (mail limodou) Date: Tue, 10 Jun 2008 19:32:37 +0800 Subject: [Tutor] IDE In-Reply-To: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: On Tue, Jun 10, 2008 at 7:07 PM, Sean Novak wrote: > I'm looking for the perfect IDE, preferably open source. I've installed > Bluefish, which I find to be a little buggy still. I'm just starting to > dive into emacs, which I feel is a little daunting. If someone has tried a > few different IDEs and found the one that they love.. I'd be interested in > your insight! > > Maybe you can try ulipad. See my signature below. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ Uliweb <>: http://code.google.com/p/uliweb My Blog: http://hi.baidu.com/limodou -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmniyas at gmail.com Tue Jun 10 13:36:00 2008 From: cmniyas at gmail.com (muhamed niyas) Date: Tue, 10 Jun 2008 17:06:00 +0530 Subject: [Tutor] IDE In-Reply-To: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: You can use either Komodo or Anjuta. Komodo is better than Anjuta. On Tue, Jun 10, 2008 at 4:37 PM, Sean Novak wrote: > I'm looking for the perfect IDE, preferably open source. I've installed > Bluefish, which I find to be a little buggy still. I'm just starting to > dive into emacs, which I feel is a little daunting. If someone has tried a > few different IDEs and found the one that they love.. I'd be interested in > your insight! > > Thank you! > > Sean > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Thanks & Best Regards, Muhamed Niyas C (Core Solutions India) Mobile: +91 9447 468825 URL: www.coresolutionsindia.com Email: niyas at coresolutionsindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Jun 10 13:45:43 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Jun 2008 07:45:43 -0400 Subject: [Tutor] parsing .txt In-Reply-To: <527df91b0806100340p28db9cc5r6a36a736d8b32f20@mail.gmail.com> References: <527df91b0806100340p28db9cc5r6a36a736d8b32f20@mail.gmail.com> Message-ID: <484E6967.8020204@gmail.com> glist wrote: > Let's say I have a file with this kind of content/lines > > textdata = ''' > %question What is Python? > %correct A programming language > %wrong A graphical package > %wrong An operating system > > %question Is Computer Science really about computers? > %wrong Yes > %correct No > ''' > > I want to pose the question to a user and check his answer, so I come > up with this solution. Is there a better > way thought? I particulary hate that "ptr = -1" hack of mine... > > questionary = [] > ptr = -1 > > for line in textdata.split('\n'): > if line: > space = line.find(' ') > tag = line[1:space] > content = line[space+1:] > > if tag == "question": > ptr += 1 > questionary.append({tag : content}) > else: > questionary[ptr].update({tag : content}) questionary = [] for line in textdata.split('\n'): if line: tag, content = line.split(' ', 1) if tag == "question": questionary.append({tag : content}) else: questionary[-1].update({tag : content}) You might even consider making questionary a dictionary keyed by the question. -- Bob Gailer 919-636-4239 Chapel Hill, NC From srilyk at gmail.com Tue Jun 10 14:01:31 2008 From: srilyk at gmail.com (W W) Date: Tue, 10 Jun 2008 07:01:31 -0500 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: <333efb450806100501u4f0c3122t76ff4a890dcc93d8@mail.gmail.com> I use vi/vim. I find it extremely useful/powerful. -Wayne From limodou.mail at gmail.com Tue Jun 10 14:07:09 2008 From: limodou.mail at gmail.com (mail limodou) Date: Tue, 10 Jun 2008 20:07:09 +0800 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: On Tue, Jun 10, 2008 at 7:32 PM, mail limodou wrote: > On Tue, Jun 10, 2008 at 7:07 PM, Sean Novak wrote: > >> I'm looking for the perfect IDE, preferably open source. I've installed >> Bluefish, which I find to be a little buggy still. I'm just starting to >> dive into emacs, which I feel is a little daunting. If someone has tried a >> few different IDEs and found the one that they love.. I'd be interested in >> your insight! >> >> Maybe you can try ulipad. See my signature below. > > There is a video about Ulipad http://showmedo.com/videos/video?name=2670000&fromSeriesID=267 -- I like python! UliPad <>: http://code.google.com/p/ulipad/ Uliweb <>: http://code.google.com/p/uliweb My Blog: http://hi.baidu.com/limodou -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jun 10 14:19:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jun 2008 08:19:27 -0400 Subject: [Tutor] parsing .txt In-Reply-To: <484E6967.8020204@gmail.com> References: <527df91b0806100340p28db9cc5r6a36a736d8b32f20@mail.gmail.com> <484E6967.8020204@gmail.com> Message-ID: <1c2a2c590806100519j530098eftcfb0ccae01717472@mail.gmail.com> On Tue, Jun 10, 2008 at 7:45 AM, bob gailer wrote: > questionary = [] > > for line in textdata.split('\n'): > if line: > tag, content = line.split(' ', 1) tag = tag[1:] # strip leading % > if tag == "question": > questionary.append({tag : content}) > else: > questionary[-1].update({tag : content}) or questionary[-1][tag] = content Kent From kent37 at tds.net Tue Jun 10 14:21:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jun 2008 08:21:44 -0400 Subject: [Tutor] IDE In-Reply-To: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: <1c2a2c590806100521q3e69eadx6249211220892633@mail.gmail.com> On Tue, Jun 10, 2008 at 7:07 AM, Sean Novak wrote: > I'm looking for the perfect IDE, preferably open source. 'Perfect' is in the eye of the beholder! Some suggestions here: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Kent From alan.gauld at btinternet.com Tue Jun 10 14:26:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 13:26:08 +0100 Subject: [Tutor] IDE References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: "Sean Novak" wrote > I'm looking for the perfect IDE, preferably open source. Aren't we all! :-) We used to have editor wars, now its IDE wars... > someone has tried a few different IDEs and found the one that they > love.. I'd be interested in your insight! I've tried many and liked several but none ae perfect. And some suit different tasks better than others. The best of all is probably the Dolphin Smalltalk IDE, but it has the disadvantage of only doing Smalltalk on a Windows box... I also liked the Borland Delphi IDE around version 3. The later versions are based on Eclipse with which I have a love/hate relationship! But Delphi is commercial and doesn't do Python! I liked ObjectCenter on my Sun workstation, but it costs big bucks and doesn't do Python. For Python work, since I assume that's what you are really interested in, I use Pythonwin for small projects. For bigger jobs I use vim with a command prompt and an interactive session. 3 windows and Unix or Cygwin to provide the other tools. Old fashioned, but it's the most productive route for me. Alan G From demonic.software at gmail.com Tue Jun 10 15:48:02 2008 From: demonic.software at gmail.com (Demonic Software) Date: Tue, 10 Jun 2008 08:48:02 -0500 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: I have tried a few and I mainly stick with Eclipse IDE + PyDev for large projects, simply because I develop stuff in other languages and it is X-platform. For small stuff, I might just use Notepad++ (Windows), Kate/(KDE)/ vim, or ipython for rapid python prototyping :) My only dislike about vim is how spacing is interpretted going from editor to editor, so I dont use it very often for python :/ On Tue, Jun 10, 2008 at 7:26 AM, Alan Gauld wrote: > "Sean Novak" wrote > > I'm looking for the perfect IDE, preferably open source. >> > > Aren't we all! :-) > > We used to have editor wars, now its IDE wars... > > someone has tried a few different IDEs and found the one that they love.. >> I'd be interested in your insight! >> > > I've tried many and liked several but none ae perfect. > And some suit different tasks better than others. > > The best of all is probably the Dolphin Smalltalk IDE, but it has > the disadvantage of only doing Smalltalk on a Windows box... > > I also liked the Borland Delphi IDE around version 3. The later > versions are based on Eclipse with which I have a love/hate > relationship! But Delphi is commercial and doesn't do Python! > > I liked ObjectCenter on my Sun workstation, but it costs big > bucks and doesn't do Python. > > For Python work, since I assume that's what you are really > interested in, I use Pythonwin for small projects. For bigger jobs > I use vim with a command prompt and an interactive session. > 3 windows and Unix or Cygwin to provide the other tools. > > Old fashioned, but it's the most productive route for me. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at yavarsity.com Tue Jun 10 16:44:44 2008 From: michael at yavarsity.com (Michael yaV) Date: Tue, 10 Jun 2008 10:44:44 -0400 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> How about for the Mac platform? On Jun 10, 2008, at 8:26 AM, Alan Gauld wrote: > "Sean Novak" wrote > >> I'm looking for the perfect IDE, preferably open source. > > Aren't we all! :-) > > We used to have editor wars, now its IDE wars... > >> someone has tried a few different IDEs and found the one that they >> love.. I'd be interested in your insight! > > I've tried many and liked several but none ae perfect. > And some suit different tasks better than others. > > The best of all is probably the Dolphin Smalltalk IDE, but it has > the disadvantage of only doing Smalltalk on a Windows box... > > I also liked the Borland Delphi IDE around version 3. The later > versions are based on Eclipse with which I have a love/hate > relationship! But Delphi is commercial and doesn't do Python! > > I liked ObjectCenter on my Sun workstation, but it costs big > bucks and doesn't do Python. > > For Python work, since I assume that's what you are really > interested in, I use Pythonwin for small projects. For bigger jobs > I use vim with a command prompt and an interactive session. > 3 windows and Unix or Cygwin to provide the other tools. > > Old fashioned, but it's the most productive route for me. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From Mike.Hansen at atmel.com Tue Jun 10 17:39:21 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 10 Jun 2008 09:39:21 -0600 Subject: [Tutor] IDE In-Reply-To: <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Michael yaV > Sent: Tuesday, June 10, 2008 8:45 AM > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] IDE > > How about for the Mac platform? > Textmate(not open source) but most who program on the mac love it. TextWrangler(not open source, but free) Open source ----------- VIM Emacs(Aquamacs) Eclipse Probably not considered IDEs ---------------------------- Smultron SubEthaEdit Mike From Mike.Hansen at atmel.com Tue Jun 10 17:49:40 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 10 Jun 2008 09:49:40 -0600 Subject: [Tutor] IDE In-Reply-To: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: <7941B2693F32294AAF16C26B679A258D02837987@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Sean Novak > Sent: Tuesday, June 10, 2008 5:08 AM > To: tutor at python.org > Subject: [Tutor] IDE > > I'm looking for the perfect IDE, preferably open source. I've > installed Bluefish, which I find to be a little buggy still. > I'm just > starting to dive into emacs, which I feel is a little daunting. If > someone has tried a few different IDEs and found the one that they > love.. I'd be interested in your insight! > > Thank you! > > Sean Since you mentioned Bluefish, I'm assuming you are on a Linux/Unix system. VIM Emacs SPE(I'm not sure if it's open source, but it's free) Komodo Edit Eclipse w/Pydev Eric4 I use VIM the majority of the time. The company I work for purchased Komodo IDE for me, and I use it off and on. I do my development on a Windows XP machine mostly for web applications that run on a Linux box. Mike From snovak at snovak.com Tue Jun 10 18:44:02 2008 From: snovak at snovak.com (Sean Novak) Date: Tue, 10 Jun 2008 12:44:02 -0400 Subject: [Tutor] IDE References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com> Message-ID: <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> > > Wow.. thanks everyone!! I am on a mac,, currently. But, I often > bounce from one computer to the next.. often Linux. So, I like the > VIM option as it comes pre installed on either OS. One thing that I > like about EMACS, however, is the ability to run the current buffer > interactively to a python command line. Is there a way to set this > up in VIM? Why not just use EMACS? I'm already pretty familiar > with VIM (shocking, I know). But, as is,, I wouldn't consider it an > IDE. It's more of a really really nice text editor. I hope I don't > get flamed for that last one. Does anyone know of a documented > useful workflow using VIM and it's other UNIX compatriots that feels > more like an IDE? Links would be very appreciated!!! Any video > links/tutorials.. I will make you a delicious sandwich. > > Sean > > > On Jun 10, 2008, at 11:39 AM, Hansen, Mike wrote: > >> >> >>> -----Original Message----- >>> From: tutor-bounces at python.org >>> [mailto:tutor-bounces at python.org] On Behalf Of Michael yaV >>> Sent: Tuesday, June 10, 2008 8:45 AM >>> To: Alan Gauld >>> Cc: tutor at python.org >>> Subject: Re: [Tutor] IDE >>> >>> How about for the Mac platform? >>> >> >> Textmate(not open source) but most who program on the mac love it. >> >> TextWrangler(not open source, but free) >> >> Open source >> ----------- >> VIM >> Emacs(Aquamacs) >> Eclipse >> >> Probably not considered IDEs >> ---------------------------- >> Smultron >> SubEthaEdit >> >> Mike >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > From Mike.Hansen at atmel.com Tue Jun 10 19:05:08 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 10 Jun 2008 11:05:08 -0600 Subject: [Tutor] IDE In-Reply-To: <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com> <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> Message-ID: <7941B2693F32294AAF16C26B679A258D02837AB6@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Sean Novak > Sent: Tuesday, June 10, 2008 10:44 AM > To: tutor at python.org > Subject: Re: [Tutor] IDE > > > > > Wow.. thanks everyone!! I am on a mac,, currently. But, I often > > bounce from one computer to the next.. often Linux. So, I > like the > > VIM option as it comes pre installed on either OS. One > thing that I > > like about EMACS, however, is the ability to run the > current buffer > > interactively to a python command line. Is there a way to > set this > > up in VIM? Why not just use EMACS? I'm already pretty familiar > > with VIM (shocking, I know). But, as is,, I wouldn't > consider it an > > IDE. It's more of a really really nice text editor. I > hope I don't > > get flamed for that last one. Does anyone know of a documented > > useful workflow using VIM and it's other UNIX compatriots > that feels > > more like an IDE? Links would be very appreciated!!! Any video > > links/tutorials.. I will make you a delicious sandwich. > > > > Sean Here's a couple of links. I need to explore some of the stuff in Peter's Blog more. http://www.petersblog.org/node/461 http://clipboarded.blogspot.com/2007/10/vim-as-ide.html From dave6502 at googlemail.com Tue Jun 10 19:07:40 2008 From: dave6502 at googlemail.com (dave selby) Date: Tue, 10 Jun 2008 18:07:40 +0100 Subject: [Tutor] do I need f.close() Message-ID: Hi All, Up to now I when I need to write some data to a file I have been purposely using close() f = open(conf, 'w') f.writelines(lines) f.close() Is it as safe to use the following .... open(conf, 'w').writelines(lines) ie no close() to flush the data, but also not assigned an object name so am I right in thinking that as the object is 'reclaimed' close() is automatically called ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From srilyk at gmail.com Tue Jun 10 19:09:06 2008 From: srilyk at gmail.com (W W) Date: Tue, 10 Jun 2008 12:09:06 -0500 Subject: [Tutor] IDE In-Reply-To: <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com> <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> Message-ID: <333efb450806101009r144380e4w868bd39458df7ccf@mail.gmail.com> On Tue, Jun 10, 2008 at 11:44 AM, Sean Novak wrote: >> however, is the ability to run the current buffer interactively to a python >> command line. Is there a way to set this up in VIM? I know there's some python what-nots with vim, but I just do one of a few options: 1) I have two terminal windows open, one with an interactive python prompt, and the other with vim. I play around with whatever small commands in the interactive editor when I want to experiment with something small. When I'm running/testing my script, I just do this: :w :!python myscript.py and it will run your script. That's my most common method, though sometimes I will just run python from within vim: :!python and then exit() the prompt to get back to vim. I've heard tell there are some other ways, but that's always been sufficient for me. -Wayne From srilyk at gmail.com Tue Jun 10 19:12:38 2008 From: srilyk at gmail.com (W W) Date: Tue, 10 Jun 2008 12:12:38 -0500 Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: <333efb450806101012w7e37e172q5c03cdbdde7fe1db@mail.gmail.com> On Tue, Jun 10, 2008 at 12:07 PM, dave selby wrote: > Hi All, > > Up to now I when I need to write some data to a file I have been > purposely using close() > > f = open(conf, 'w') > f.writelines(lines) > f.close() > > Is it as safe to use the following .... > > open(conf, 'w').writelines(lines) > > ie no close() to flush the data, but also not assigned an object name > so am I right in thinking that as the object is 'reclaimed' close() is > automatically called ? My guess is that's probably correct, but it's also bad programming. It's like that old saying of my grandma's: If you open it, close it! -Wayne From alan.gauld at btinternet.com Tue Jun 10 19:21:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 18:21:32 +0100 Subject: [Tutor] IDE References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com> <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> Message-ID: "Sean Novak" wrote >> like about EMACS, however, is the ability to run the current buffer >> interactively to a python command line. Is there a way to set this >> up in VIM? Yes, it's a standard vi (not even vim) feature. The command is something like: :!(motion) python Where (motion) is any vi navigation/selection set (including vims visual mode) Thus for the full buffer: :1,$! python Follow with a u to undo the change!!! Do help ! for lots more options >> with VIM (shocking, I know). But, as is,, I wouldn't consider it >> an IDE. It's more of a really really nice text editor. I hope I >> don't get flamed for that last one. Does anyone know of a >> documented useful workflow using VIM and it's other UNIX >> compatriots that feels more like an IDE? Just standard unix tools like grep, tags, and the filter trick above. HTH, Alan G From alan.gauld at btinternet.com Tue Jun 10 19:26:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 18:26:42 +0100 Subject: [Tutor] do I need f.close() References: Message-ID: "dave selby" wrote > Up to now I when I need to write some data to a file I have been > purposely using close() > > f = open(conf, 'w') > f.writelines(lines) > f.close() > > Is it as safe to use the following .... > > open(conf, 'w').writelines(lines) > In theory yes, but in practice its much harder to deal with if things go wrong. You have no opportunity to catch errors and if you do its hard to know whether it was because the file didn't open properly or didn't write properly or whatever. Any time you are dealing with a lump of metal spinning at high speed, tiny distances from a magnet with the potential to hose your data its good to be careful... Most long term programmers have been bitten often enough that they use f.close() just to be safe.. :-) Alan G. From michael at yavarsity.com Tue Jun 10 19:30:30 2008 From: michael at yavarsity.com (Michael yaV) Date: Tue, 10 Jun 2008 13:30:30 -0400 Subject: [Tutor] IDE In-Reply-To: <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> Message-ID: <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> Thanks. What do you think of IDLE? On Jun 10, 2008, at 11:39 AM, Hansen, Mike wrote: > > >> -----Original Message----- >> From: tutor-bounces at python.org >> [mailto:tutor-bounces at python.org] On Behalf Of Michael yaV >> Sent: Tuesday, June 10, 2008 8:45 AM >> To: Alan Gauld >> Cc: tutor at python.org >> Subject: Re: [Tutor] IDE >> >> How about for the Mac platform? >> > > Textmate(not open source) but most who program on the mac love it. > > TextWrangler(not open source, but free) > > Open source > ----------- > VIM > Emacs(Aquamacs) > Eclipse > > Probably not considered IDEs > ---------------------------- > Smultron > SubEthaEdit > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From balderas at whtvcable.com Tue Jun 10 19:13:14 2008 From: balderas at whtvcable.com (Chris Balderas) Date: Tue, 10 Jun 2008 10:13:14 -0700 Subject: [Tutor] Tutor Digest, Vol 52, Issue 27 In-Reply-To: Message-ID: <200806101013391.SM00768@chaos> I would like to be remove off your mailing list please... -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tutor-request at python.org Sent: Tuesday, June 10, 2008 10:05 AM To: tutor at python.org Subject: Tutor Digest, Vol 52, Issue 27 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: parsing .txt (Kent Johnson) 2. Re: IDE (Kent Johnson) 3. Re: IDE (Alan Gauld) 4. Re: IDE (Demonic Software) 5. Re: IDE (Michael yaV) 6. Re: IDE (Hansen, Mike) 7. Re: IDE (Hansen, Mike) 8. Re: IDE (Sean Novak) 9. Re: IDE (Hansen, Mike) ---------------------------------------------------------------------- Message: 1 Date: Tue, 10 Jun 2008 08:19:27 -0400 From: "Kent Johnson" Subject: Re: [Tutor] parsing .txt To: "bob gailer" Cc: tutor at python.org Message-ID: <1c2a2c590806100519j530098eftcfb0ccae01717472 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jun 10, 2008 at 7:45 AM, bob gailer wrote: > questionary = [] > > for line in textdata.split('\n'): > if line: > tag, content = line.split(' ', 1) tag = tag[1:] # strip leading % > if tag == "question": > questionary.append({tag : content}) > else: > questionary[-1].update({tag : content}) or questionary[-1][tag] = content Kent ------------------------------ Message: 2 Date: Tue, 10 Jun 2008 08:21:44 -0400 From: "Kent Johnson" Subject: Re: [Tutor] IDE To: "Sean Novak" Cc: tutor at python.org Message-ID: <1c2a2c590806100521q3e69eadx6249211220892633 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jun 10, 2008 at 7:07 AM, Sean Novak wrote: > I'm looking for the perfect IDE, preferably open source. 'Perfect' is in the eye of the beholder! Some suggestions here: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Kent ------------------------------ Message: 3 Date: Tue, 10 Jun 2008 13:26:08 +0100 From: "Alan Gauld" Subject: Re: [Tutor] IDE To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "Sean Novak" wrote > I'm looking for the perfect IDE, preferably open source. Aren't we all! :-) We used to have editor wars, now its IDE wars... > someone has tried a few different IDEs and found the one that they > love.. I'd be interested in your insight! I've tried many and liked several but none ae perfect. And some suit different tasks better than others. The best of all is probably the Dolphin Smalltalk IDE, but it has the disadvantage of only doing Smalltalk on a Windows box... I also liked the Borland Delphi IDE around version 3. The later versions are based on Eclipse with which I have a love/hate relationship! But Delphi is commercial and doesn't do Python! I liked ObjectCenter on my Sun workstation, but it costs big bucks and doesn't do Python. For Python work, since I assume that's what you are really interested in, I use Pythonwin for small projects. For bigger jobs I use vim with a command prompt and an interactive session. 3 windows and Unix or Cygwin to provide the other tools. Old fashioned, but it's the most productive route for me. Alan G ------------------------------ Message: 4 Date: Tue, 10 Jun 2008 08:48:02 -0500 From: "Demonic Software" Subject: Re: [Tutor] IDE To: tutor at python.org Message-ID: Content-Type: text/plain; charset="iso-8859-1" I have tried a few and I mainly stick with Eclipse IDE + PyDev for large projects, simply because I develop stuff in other languages and it is X-platform. For small stuff, I might just use Notepad++ (Windows), Kate/(KDE)/ vim, or ipython for rapid python prototyping :) My only dislike about vim is how spacing is interpretted going from editor to editor, so I dont use it very often for python :/ On Tue, Jun 10, 2008 at 7:26 AM, Alan Gauld wrote: > "Sean Novak" wrote > > I'm looking for the perfect IDE, preferably open source. >> > > Aren't we all! :-) > > We used to have editor wars, now its IDE wars... > > someone has tried a few different IDEs and found the one that they love.. >> I'd be interested in your insight! >> > > I've tried many and liked several but none ae perfect. > And some suit different tasks better than others. > > The best of all is probably the Dolphin Smalltalk IDE, but it has > the disadvantage of only doing Smalltalk on a Windows box... > > I also liked the Borland Delphi IDE around version 3. The later > versions are based on Eclipse with which I have a love/hate > relationship! But Delphi is commercial and doesn't do Python! > > I liked ObjectCenter on my Sun workstation, but it costs big > bucks and doesn't do Python. > > For Python work, since I assume that's what you are really > interested in, I use Pythonwin for small projects. For bigger jobs > I use vim with a command prompt and an interactive session. > 3 windows and Unix or Cygwin to provide the other tools. > > Old fashioned, but it's the most productive route for me. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Tue, 10 Jun 2008 10:44:44 -0400 From: Michael yaV Subject: Re: [Tutor] IDE To: Alan Gauld Cc: tutor at python.org Message-ID: <7B3C37F3-6252-4148-8892-76E18ADFACB1 at yavarsity.com> Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes How about for the Mac platform? On Jun 10, 2008, at 8:26 AM, Alan Gauld wrote: > "Sean Novak" wrote > >> I'm looking for the perfect IDE, preferably open source. > > Aren't we all! :-) > > We used to have editor wars, now its IDE wars... > >> someone has tried a few different IDEs and found the one that they >> love.. I'd be interested in your insight! > > I've tried many and liked several but none ae perfect. > And some suit different tasks better than others. > > The best of all is probably the Dolphin Smalltalk IDE, but it has > the disadvantage of only doing Smalltalk on a Windows box... > > I also liked the Borland Delphi IDE around version 3. The later > versions are based on Eclipse with which I have a love/hate > relationship! But Delphi is commercial and doesn't do Python! > > I liked ObjectCenter on my Sun workstation, but it costs big > bucks and doesn't do Python. > > For Python work, since I assume that's what you are really > interested in, I use Pythonwin for small projects. For bigger jobs > I use vim with a command prompt and an interactive session. > 3 windows and Unix or Cygwin to provide the other tools. > > Old fashioned, but it's the most productive route for me. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------ Message: 6 Date: Tue, 10 Jun 2008 09:39:21 -0600 From: "Hansen, Mike" Subject: Re: [Tutor] IDE To: Message-ID: <7941B2693F32294AAF16C26B679A258D0283795D at csomb01.corp.atmel.com> Content-Type: text/plain; charset="us-ascii" > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Michael yaV > Sent: Tuesday, June 10, 2008 8:45 AM > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] IDE > > How about for the Mac platform? > Textmate(not open source) but most who program on the mac love it. TextWrangler(not open source, but free) Open source ----------- VIM Emacs(Aquamacs) Eclipse Probably not considered IDEs ---------------------------- Smultron SubEthaEdit Mike ------------------------------ Message: 7 Date: Tue, 10 Jun 2008 09:49:40 -0600 From: "Hansen, Mike" Subject: Re: [Tutor] IDE To: Message-ID: <7941B2693F32294AAF16C26B679A258D02837987 at csomb01.corp.atmel.com> Content-Type: text/plain; charset="us-ascii" > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Sean Novak > Sent: Tuesday, June 10, 2008 5:08 AM > To: tutor at python.org > Subject: [Tutor] IDE > > I'm looking for the perfect IDE, preferably open source. I've > installed Bluefish, which I find to be a little buggy still. > I'm just > starting to dive into emacs, which I feel is a little daunting. If > someone has tried a few different IDEs and found the one that they > love.. I'd be interested in your insight! > > Thank you! > > Sean Since you mentioned Bluefish, I'm assuming you are on a Linux/Unix system. VIM Emacs SPE(I'm not sure if it's open source, but it's free) Komodo Edit Eclipse w/Pydev Eric4 I use VIM the majority of the time. The company I work for purchased Komodo IDE for me, and I use it off and on. I do my development on a Windows XP machine mostly for web applications that run on a Linux box. Mike ------------------------------ Message: 8 Date: Tue, 10 Jun 2008 12:44:02 -0400 From: Sean Novak Subject: Re: [Tutor] IDE To: tutor at python.org Message-ID: <36A3D5CB-C705-4852-8F1F-457D0E15B0DB at snovak.com> Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes > > Wow.. thanks everyone!! I am on a mac,, currently. But, I often > bounce from one computer to the next.. often Linux. So, I like the > VIM option as it comes pre installed on either OS. One thing that I > like about EMACS, however, is the ability to run the current buffer > interactively to a python command line. Is there a way to set this > up in VIM? Why not just use EMACS? I'm already pretty familiar > with VIM (shocking, I know). But, as is,, I wouldn't consider it an > IDE. It's more of a really really nice text editor. I hope I don't > get flamed for that last one. Does anyone know of a documented > useful workflow using VIM and it's other UNIX compatriots that feels > more like an IDE? Links would be very appreciated!!! Any video > links/tutorials.. I will make you a delicious sandwich. > > Sean > > > On Jun 10, 2008, at 11:39 AM, Hansen, Mike wrote: > >> >> >>> -----Original Message----- >>> From: tutor-bounces at python.org >>> [mailto:tutor-bounces at python.org] On Behalf Of Michael yaV >>> Sent: Tuesday, June 10, 2008 8:45 AM >>> To: Alan Gauld >>> Cc: tutor at python.org >>> Subject: Re: [Tutor] IDE >>> >>> How about for the Mac platform? >>> >> >> Textmate(not open source) but most who program on the mac love it. >> >> TextWrangler(not open source, but free) >> >> Open source >> ----------- >> VIM >> Emacs(Aquamacs) >> Eclipse >> >> Probably not considered IDEs >> ---------------------------- >> Smultron >> SubEthaEdit >> >> Mike >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > ------------------------------ Message: 9 Date: Tue, 10 Jun 2008 11:05:08 -0600 From: "Hansen, Mike" Subject: Re: [Tutor] IDE To: Message-ID: <7941B2693F32294AAF16C26B679A258D02837AB6 at csomb01.corp.atmel.com> Content-Type: text/plain; charset="us-ascii" > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Sean Novak > Sent: Tuesday, June 10, 2008 10:44 AM > To: tutor at python.org > Subject: Re: [Tutor] IDE > > > > > Wow.. thanks everyone!! I am on a mac,, currently. But, I often > > bounce from one computer to the next.. often Linux. So, I > like the > > VIM option as it comes pre installed on either OS. One > thing that I > > like about EMACS, however, is the ability to run the > current buffer > > interactively to a python command line. Is there a way to > set this > > up in VIM? Why not just use EMACS? I'm already pretty familiar > > with VIM (shocking, I know). But, as is,, I wouldn't > consider it an > > IDE. It's more of a really really nice text editor. I > hope I don't > > get flamed for that last one. Does anyone know of a documented > > useful workflow using VIM and it's other UNIX compatriots > that feels > > more like an IDE? Links would be very appreciated!!! Any video > > links/tutorials.. I will make you a delicious sandwich. > > > > Sean Here's a couple of links. I need to explore some of the stuff in Peter's Blog more. http://www.petersblog.org/node/461 http://clipboarded.blogspot.com/2007/10/vim-as-ide.html ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 52, Issue 27 ************************************* From kent37 at tds.net Tue Jun 10 19:42:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jun 2008 13:42:19 -0400 Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: <1c2a2c590806101042i282b48fdn9e0d510daaaaaea9@mail.gmail.com> On Tue, Jun 10, 2008 at 1:07 PM, dave selby wrote: > Hi All, > > Up to now I when I need to write some data to a file I have been > purposely using close() > > f = open(conf, 'w') > f.writelines(lines) > f.close() > > Is it as safe to use the following .... > > open(conf, 'w').writelines(lines) I will do this with file *read* in code that is not intended to be production quality. For writes and production code I always call close explicitly. > > ie no close() to flush the data, but also not assigned an object name > so am I right in thinking that as the object is 'reclaimed' close() is > automatically called ? In the current implementation of CPython I believe that is correct. For Jython, it is not correct, as Jython uses a different (not reference counted) GC. Perhaps that is why I am scrupulous about closing files that I open for write; I'm pretty sure I have been burned by it and I did a lot of Jython coding a few jobs ago... Kent From marc.tompkins at gmail.com Tue Jun 10 19:45:38 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 10 Jun 2008 10:45:38 -0700 Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: <40af687b0806101045s2f6a4cf5p8ea41c1815232bc7@mail.gmail.com> On Tue, Jun 10, 2008 at 10:07 AM, dave selby wrote: > Hi All, > > Up to now I when I need to write some data to a file I have been > purposely using close() > > f = open(conf, 'w') > f.writelines(lines) > f.close() > > Is it as safe to use the following .... > > open(conf, 'w').writelines(lines) > > ie no close() to flush the data, but also not assigned an object name > so am I right in thinking that as the object is 'reclaimed' close() is > automatically called ? > > Cheers > > Dave > > If you're using Python 2.5, you can use the new "with" - > with open("x.txt") as f: > data = f.read() > do something with data > > which takes care of closing and possible exception handling automagically. Fredrik Lundh has a good article about it: http://effbot.org/zone/python-with-statement.htm -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Jun 10 19:54:49 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Jun 2008 13:54:49 -0400 Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: <484EBFE9.1000804@gmail.com> dave selby wrote: > Hi All, > > Up to now I when I need to write some data to a file I have been > purposely using close() > > f = open(conf, 'w') > f.writelines(lines) > f.close() > > Is it as safe to use the following .... > > open(conf, 'w').writelines(lines) > > ie no close() to flush the data, but also not assigned an object name > so am I right in thinking that as the object is 'reclaimed' close() is > automatically called ? > True. And not, imho, "bad programming" -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Tue Jun 10 20:06:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jun 2008 14:06:50 -0400 Subject: [Tutor] Tutor Digest, Vol 52, Issue 27 In-Reply-To: <200806101013391.SM00768@chaos> References: <200806101013391.SM00768@chaos> Message-ID: <1c2a2c590806101106x68562a02nacff90cbb1d4cadb@mail.gmail.com> On Tue, Jun 10, 2008 at 1:13 PM, Chris Balderas wrote: > I would like to be remove off your mailing list please... Just follow the directions here: > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org Kent From kent37 at tds.net Tue Jun 10 20:07:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Jun 2008 14:07:48 -0400 Subject: [Tutor] IDE In-Reply-To: <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> Message-ID: <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> On Tue, Jun 10, 2008 at 1:30 PM, Michael yaV wrote: > Thanks. What do you think of IDLE? It's primitive. Kent From michael at yavarsity.com Tue Jun 10 20:13:26 2008 From: michael at yavarsity.com (Michael yaV) Date: Tue, 10 Jun 2008 14:13:26 -0400 Subject: [Tutor] IDE In-Reply-To: <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> Message-ID: <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Since I'm on a mac, how about using Xcode? On Jun 10, 2008, at 2:07 PM, Kent Johnson wrote: > On Tue, Jun 10, 2008 at 1:30 PM, Michael yaV > wrote: >> Thanks. What do you think of IDLE? > > It's primitive. > > Kent > From snovak at snovak.com Tue Jun 10 20:24:27 2008 From: snovak at snovak.com (Sean Novak) Date: Tue, 10 Jun 2008 14:24:27 -0400 Subject: [Tutor] IDE In-Reply-To: References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com> <36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> Message-ID: Sweet Jesus!! Thank you! Thus far,, I know only the basic VIM functionality ie. navigating the document.. search/replace, etc. Still need to learn regular expressions also. This filter stuff rocks.. thanks! Sean On Jun 10, 2008, at 1:21 PM, Alan Gauld wrote: > "Sean Novak" wrote > >>> like about EMACS, however, is the ability to run the current >>> buffer interactively to a python command line. Is there a way to >>> set this up in VIM? > > Yes, it's a standard vi (not even vim) feature. > The command is something like: > > :!(motion) python > > Where (motion) is any vi navigation/selection set > (including vims visual mode) > > Thus for the full buffer: > > :1,$! python > > Follow with a u to undo the change!!! > > Do help ! for lots more options > >>> with VIM (shocking, I know). But, as is,, I wouldn't consider it >>> an IDE. It's more of a really really nice text editor. I hope I >>> don't get flamed for that last one. Does anyone know of a >>> documented useful workflow using VIM and it's other UNIX >>> compatriots that feels more like an IDE? > > Just standard unix tools like grep, tags, and the filter trick above. > > HTH, > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From wim at dehul.net Tue Jun 10 20:48:32 2008 From: wim at dehul.net (Wim De Hul) Date: Tue, 10 Jun 2008 20:48:32 +0200 Subject: [Tutor] IDE In-Reply-To: <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Message-ID: What about Wingware, I use Wingware professional at ork and the free version at home. Here's the link: http://www.wingware.com Cheers! Wim On 10 Jun 2008, at 20:13, Michael yaV wrote: > Since I'm on a mac, how about using Xcode? > > > On Jun 10, 2008, at 2:07 PM, Kent Johnson wrote: > >> On Tue, Jun 10, 2008 at 1:30 PM, Michael yaV >> wrote: >>> Thanks. What do you think of IDLE? >> >> It's primitive. >> >> Kent >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Mike.Hansen at atmel.com Tue Jun 10 20:56:07 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 10 Jun 2008 12:56:07 -0600 Subject: [Tutor] IDE In-Reply-To: <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Message-ID: <7941B2693F32294AAF16C26B679A258D02837C14@csomb01.corp.atmel.com> > -----Original Message----- > From: Michael yaV [mailto:michael at yavarsity.com] > Sent: Tuesday, June 10, 2008 12:13 PM > To: Kent Johnson > Cc: Hansen, Mike; tutor at python.org > Subject: Re: [Tutor] IDE > > Since I'm on a mac, how about using Xcode? > > > On Jun 10, 2008, at 2:07 PM, Kent Johnson wrote: > > > On Tue, Jun 10, 2008 at 1:30 PM, Michael yaV > > > wrote: > >> Thanks. What do you think of IDLE? > > > > It's primitive. > > > > Kent > > > I agree with Kent. IDLE is bare bones. It's nice to mess around with the interactive interpreter, but I've been using Ipython for that. I've never played with Xcode. Mike From michael at yavarsity.com Tue Jun 10 21:04:04 2008 From: michael at yavarsity.com (Michael yaV) Date: Tue, 10 Jun 2008 15:04:04 -0400 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Message-ID: <09FD2363-0E5A-4E51-A90C-9EAD46D05FE7@yavarsity.com> Thanks, I'll give it look. On Jun 10, 2008, at 2:48 PM, Wim De Hul wrote: > What about Wingware, > > I use Wingware professional at ork and the free version at home. > > Here's the link: http://www.wingware.com > > > Cheers! > > Wim > > On 10 Jun 2008, at 20:13, Michael yaV wrote: > >> Since I'm on a mac, how about using Xcode? >> >> >> On Jun 10, 2008, at 2:07 PM, Kent Johnson wrote: >> >>> On Tue, Jun 10, 2008 at 1:30 PM, Michael yaV >>> wrote: >>>> Thanks. What do you think of IDLE? >>> >>> It's primitive. >>> >>> Kent >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From dyoo at cs.wpi.edu Tue Jun 10 20:31:57 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 10 Jun 2008 14:31:57 -0400 (EDT) Subject: [Tutor] do I need f.close() In-Reply-To: <484EBFE9.1000804@gmail.com> References: <484EBFE9.1000804@gmail.com> Message-ID: >> f = open(conf, 'w') >> f.writelines(lines) >> f.close() >> >> Is it as safe to use the following .... >> >> open(conf, 'w').writelines(lines) >> >> ie no close() to flush the data, but also not assigned an object name >> so am I right in thinking that as the object is 'reclaimed' close() is >> automatically called ? > > True. And not, imho, "bad programming" I have to disagree. The effect of the above line is sensitive to the behavior of the underlying implmentation. As Kent mentioned, CPython says that it'll call close() immediately when the count of the last reference to the file object goes to zero. But Jython and IronPython on the other hand make no such guarantees. This is one of those places where the behavior of the above code is, unfortunately, undefined in the language specification. We have to dig ourselves out of such swamps: we should avoid getting into trouble by explicit close() of the resource. Python 2.5's 'with' form addresses this problem. The documentation on file.close() has an example: http://www.python.org/doc/lib/bltin-file-objects.html#l2h-297 So the code above could become: ############################################## with open(conf, 'w') as f: f.writelines(lines) ############################################## You'll need to add the 'from __future__ import with_statement' at the top, since this is a Python 2.5 specific feature. The code is almost as short as the previous and it guarantees that f will be flushed and closed after the statement's done. From rdm at rcblue.com Tue Jun 10 22:54:25 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Jun 2008 13:54:25 -0700 Subject: [Tutor] How to get a script to open a text file with Python? Message-ID: <20080610205437.7543A1E4002@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Tue Jun 10 23:21:10 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Jun 2008 14:21:10 -0700 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Message-ID: <20080610212121.EE73A1E4003@bag.python.org> At 11:48 AM 6/10/2008, Wim De Hul wrote: >What about Wingware, > >I use Wingware professional at ork and the free version at home. > >Here's the link: http://www.wingware.com What do you like about Wing? Esp. Wing Pro? Dick Moores From washakie at gmail.com Tue Jun 10 23:31:13 2008 From: washakie at gmail.com (washakie) Date: Tue, 10 Jun 2008 14:31:13 -0700 (PDT) Subject: [Tutor] inserting a vector into an array - numpy Q Message-ID: <17765150.post@talk.nabble.com> I know there must be a better way to do this with slices, but I can't seem to figure it out - I keep getting errors about the need to have the same dimensions: Here's what I'm trying: >>> type(time) >>> type(new_data) >>> shape(time) (1334,) >>> shape(new_data) (1334, 54) >>> newArray=concatenate((time,new_data)) Traceback (most recent call last): File "", line 1, in ValueError: arrays must have same number of dimensions >>> I've tried transposing, setting axis=1, etc. but I'mdoing something wrong. Here's my solution: outList=[] for i in range(len(time)): tl=[time[i]] tl.extend(new_data[i,:]) outList.append(tl) Suggestions for improvement - or just how the heck I'm supposed to do this in numpy are appreciated! -- View this message in context: http://www.nabble.com/inserting-a-vector-into-an-array---numpy-Q-tp17765150p17765150.html Sent from the Python - tutor mailing list archive at Nabble.com. From lowelltackett at yahoo.com Tue Jun 10 23:27:58 2008 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Tue, 10 Jun 2008 14:27:58 -0700 (PDT) Subject: [Tutor] IDE In-Reply-To: <333efb450806101009r144380e4w868bd39458df7ccf@mail.gmail.com> Message-ID: <405867.50654.qm@web45909.mail.sp1.yahoo.com> >From the virtual desk of Lowell Tackett  --- On Tue, 6/10/08, W W <srilyk at gmail.com> wrote: From: W W <srilyk at gmail.com> Subject: Re: [Tutor] IDE To: "Sean Novak" <snovak at snovak.com> Cc: tutor at python.org Date: Tuesday, June 10, 2008, 1:09 PM 1) I have two terminal windows open, one with an interactive python prompt, and the other with vim... How do you do that (as you describe above)? -Wayne _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at cs.wpi.edu Tue Jun 10 23:53:48 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 10 Jun 2008 17:53:48 -0400 (EDT) Subject: [Tutor] inserting a vector into an array - numpy Q In-Reply-To: <17765150.post@talk.nabble.com> References: <17765150.post@talk.nabble.com> Message-ID: > I know there must be a better way to do this with slices, but I can't > seem to figure it out - I keep getting errors about the need to have the > same dimensions: Look at the error message more closely. ValueError: arrays must have same number of dimensions What does this mean? The 1-d array that's being passed in has a different dimension than the 2d array. If we trust the error message, we should make the two arrays the same dimension before we pass them to functions that glue these arrays together. We want both of them to be two-dimensional. If we look in: http://www.scipy.org/Numpy_Functions_by_Category we should see several ways to do this. One way is with reshape: http://www.scipy.org/Numpy_Example_List_With_Doc#reshape For example: ######################################## >>> numpy.array([1, 2, 3]).reshape(1, 3) array([[1, 2, 3]]) >>> >>> >>> numpy.append(numpy.array([1, 2, 3]), ... numpy.array([[4, 5, 6], ... [7, 8, 9]]), ... axis=0) Traceback (most recent call last): File "", line 4, in File "/usr/lib/python2.5/site-packages/numpy/lib/function_base.py", line 1492, in append return concatenate((arr, values), axis=axis) ValueError: arrays must have same number of dimensions ##################################################### As we expect, this fails. But let's try to reshape the first array into two dimensions and try again. ##################################################### >>> numpy.append(numpy.array([1, 2, 3]).reshape(1, 3), ... numpy.array([[4, 5, 6], ... [7, 8, 9]]), ... axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ######################################## Another way is to use numpy.atleast_2d(), and for your particular example, it's probably more appropriate than using reshape() on the 1-d array. #################################################### >>> numpy.atleast_2d(numpy.array([3,1,4,1,5])) array([[3, 1, 4, 1, 5]]) >>> numpy.atleast_2d(numpy.array([3,1,4,1,5])).shape (1, 5) #################################################### See: http://www.scipy.org/Numpy_Example_List_With_Doc#atleast_2d From srilyk at gmail.com Wed Jun 11 00:14:12 2008 From: srilyk at gmail.com (W W) Date: Tue, 10 Jun 2008 17:14:12 -0500 Subject: [Tutor] IDE In-Reply-To: <405867.50654.qm@web45909.mail.sp1.yahoo.com> References: <333efb450806101009r144380e4w868bd39458df7ccf@mail.gmail.com> <405867.50654.qm@web45909.mail.sp1.yahoo.com> Message-ID: <333efb450806101514h3c0ea4bh6c0fc7b88c70d473@mail.gmail.com> On Tue, Jun 10, 2008 at 4:27 PM, Lowell Tackett wrote: > > > From the virtual desk of Lowell Tackett > > > --- On Tue, 6/10/08, W W wrote: > > From: W W > Subject: Re: [Tutor] IDE > To: "Sean Novak" > Cc: tutor at python.org > Date: Tuesday, June 10, 2008, 1:09 PM > > 1) I have two terminal windows open, one with an interactive python > prompt, and the other with vim... > > How do you do that (as you describe > above)? On linux, simply open two terminal windows. On mac, the same. If you're using ssh, you'd have to run two copies... although, when I've been on windows, I simply use VIM for windows, and a command prompt with the interactive shell. HTH, Wayne From alan.gauld at btinternet.com Wed Jun 11 00:33:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 23:33:15 +0100 Subject: [Tutor] IDE References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com><7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com><7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com><13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com><1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> Message-ID: "Michael yaV" wrote > Since I'm on a mac, how about using Xcode? XCode with the PyObjC bridge is OK for Cocoa work but as a general purpose IDE is no better than a good editor IMHO. I still tend to work with 3 windows on the Mac - vim, shell and Python interactive. I can cut n paste between them and along with all the Unix tools plus bash command history etc its just as productive as most IDEs in my experience. The only thing I do miss in vim over pythonwin is the tooltips when entering functions, especially if using something like Tkinter with lots of parameters per method. I've also used Netbeans and Eclipse with Python add-ons and both worked in MacOS but on my 600MHz iBook they were just too slow! I keep meaning to try emacs mode. I used to be a heavy emacs user but when I moved to a PC I started using vim and my fingers have lost their emacs habits. Alan G. From alan.gauld at btinternet.com Wed Jun 11 00:36:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 23:36:36 +0100 Subject: [Tutor] IDE References: <66CB169C-E2BB-4F71-98A2-F01B1FEC7F21@snovak.com><36A3D5CB-C705-4852-8F1F-457D0E15B0DB@snovak.com> Message-ID: "Sean Novak" wrote > Thus far,, I know only the basic VIM functionality ie. navigating > the document.. search/replace, etc. Still need to learn regular > expressions also. This filter stuff rocks.. thanks! vim can do all siort of stuff, most of the basic emacs stuff. split windows, rectangular editing blocks, folding etc etc. Alan G From alan.gauld at btinternet.com Wed Jun 11 00:35:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 23:35:18 +0100 Subject: [Tutor] IDE References: <333efb450806101009r144380e4w868bd39458df7ccf@mail.gmail.com> <405867.50654.qm@web45909.mail.sp1.yahoo.com> Message-ID: "Lowell Tackett" wrote > 1) I have two terminal windows open, one with an interactive python > prompt, and the other with vim... > > How do you do that (as you describe above)? Can you elaborate on the question? He says he opens two terminal windows and runs vim in one and python in the other. What is it you want explained? Alan G From alan.gauld at btinternet.com Wed Jun 11 00:44:33 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jun 2008 23:44:33 +0100 Subject: [Tutor] How to get a script to open a text file with Python? References: <20080610205437.7543A1E4002@bag.python.org> Message-ID: "Dick Moores" wrote > The script prints into the Windows command line > window (I don't know the official term), from which > copying is a PITA. Whats the problem copying from a command prompt? Just grab with the mouse and it's selected automatically (assuming you have QuickEdit mode turned on in the preferences obviously!) I copy/paste from a DOS box into my mail messages regularly. > Now, the script writes into temp.txt, so I thought if > I could also have Textpad open temp.txt, I could copy easily. You could. But why do you need to copy it at all? Couldn't you get Python to do what you want with the data directly rather than writing to a file then manually copying it? > But I don't know how to have a script get Textpad > to open a file. Please tell me. If TextPad is your default txt editor just use os.system("foo.txt") or if not use os.system("Path/to/textpad.exe foo.txt") Or if you want to be politically correct use the subprocess module to do the same thing. Alan G From jordan at jordanhalsey.com Tue Jun 10 19:40:17 2008 From: jordan at jordanhalsey.com (jordan halsey) Date: Tue, 10 Jun 2008 10:40:17 -0700 Subject: [Tutor] IDE In-Reply-To: <7941B2693F32294AAF16C26B679A258D02837987@csomb01.corp.atmel.com> Message-ID: <20080610232351.4C1BE1E400A@bag.python.org> Any one here using cutter... http://www.fundza.com Free Java based ide with many built in functions and bindings. This is an especially useful tool if you are doing 3d or any kind of shader writing. Jordan Reece Halsey maya | mental ray | renderman | nuke | houdini | ae www.jordanhalsey.com From rdm at rcblue.com Wed Jun 11 01:59:05 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Jun 2008 16:59:05 -0700 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: References: <20080610205437.7543A1E4002@bag.python.org> Message-ID: <20080610235917.22EF31E4003@bag.python.org> At 03:44 PM 6/10/2008, Alan Gauld wrote: >"Dick Moores" wrote > >>The script prints into the Windows command line >>window (I don't know the official term), from which >>copying is a PITA. > >Whats the problem copying from a command prompt? 1. Click on the little black icon in the upper left corner. 2. Select Edit. 3. Select Mark 4. Select text to copy 5. Hit Enter 5 steps! >Just grab with the mouse and it's selected automatically >(assuming you have QuickEdit mode turned on in the >preferences obviously!) Big assumption! I've been doing the above 5-step dance for years because I didn't know about QuickEdit. Thanks, Alan. How about pasting INTO the command prompt. Ctrl+V doesn't work, even with QuickEdit.. > I copy/paste from a DOS box >into my mail messages regularly. > >>Now, the script writes into temp.txt, so I thought if >>I could also have Textpad open temp.txt, I could copy easily. > >You could. But why do you need to copy it at all? >Couldn't you get Python to do what you want with the >data directly rather than writing to a file then manually >copying it? Looking at the script now, I think I could. >>But I don't know how to have a script get Textpad >>to open a file. Please tell me. > >If TextPad is your default txt editor just use >os.system("foo.txt") or if not use os.system("Path/to/textpad.exe foo.txt") Thanks for this. >Or if you want to be politically correct use the subprocess module >to do the same thing. Nah. Or I don't think I do. Why is it the correct way? Is there a problem with yours? Dick From john at fouhy.net Wed Jun 11 02:17:27 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Jun 2008 12:17:27 +1200 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: <20080610235917.22EF31E4003@bag.python.org> References: <20080610205437.7543A1E4002@bag.python.org> <20080610235917.22EF31E4003@bag.python.org> Message-ID: <5e58f2e40806101717s2863f68ya3c8242545eb668a@mail.gmail.com> On 11/06/2008, Dick Moores wrote: > At 03:44 PM 6/10/2008, Alan Gauld wrote: [on Windows cmd.exe] > > (assuming you have QuickEdit mode turned on in the > > preferences obviously!) > How about pasting INTO the command prompt. Ctrl+V doesn't work, even with > QuickEdit.. Single right-click to paste. User interface consistency would be a wonderful thing :-) -- John. From rdm at rcblue.com Wed Jun 11 02:42:28 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Jun 2008 17:42:28 -0700 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: <5e58f2e40806101717s2863f68ya3c8242545eb668a@mail.gmail.com > References: <20080610205437.7543A1E4002@bag.python.org> <20080610235917.22EF31E4003@bag.python.org> <5e58f2e40806101717s2863f68ya3c8242545eb668a@mail.gmail.com> Message-ID: <20080611004240.A41FA1E4003@bag.python.org> At 05:17 PM 6/10/2008, John Fouhy wrote: >On 11/06/2008, Dick Moores wrote: > > At 03:44 PM 6/10/2008, Alan Gauld wrote: >[on Windows cmd.exe] > > > (assuming you have QuickEdit mode turned on in the > > > preferences obviously!) > > How about pasting INTO the command prompt. Ctrl+V doesn't work, even with > > QuickEdit.. > >Single right-click to paste. That's weird! Thanks! >User interface consistency would be a wonderful thing :-) Yeah. Up to now I thought that other than in dragging, right-clicking (in a Windows OS) NEVER did anything. It only presented choices for things you could do. Dick From snovak at snovak.com Wed Jun 11 03:36:47 2008 From: snovak at snovak.com (Sean Novak) Date: Tue, 10 Jun 2008 21:36:47 -0400 Subject: [Tutor] for loop Message-ID: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> I know I'm going to feel stupid on this one.. I would normally write this in PHP like this: for($i=1; i< count($someArray); $i++) { print $someArray[i] } essentially,, I want to loop through an array skipping "someArray[0]" but in python the for syntax is more like foreach in PHP.. I've tried this to no avail count = 0 for i in range(1,10): if count == 0: continue else: count += 1 print i continue it prints absolutely nothing. From carroll at tjc.com Wed Jun 11 03:53:11 2008 From: carroll at tjc.com (Terry Carroll) Date: Tue, 10 Jun 2008 18:53:11 -0700 (PDT) Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: Message-ID: On Tue, 10 Jun 2008, Alan Gauld wrote: > If TextPad is your default txt editor just use > os.system("foo.txt") or os.startfile("foo.txt"); sounds like the equivalent, but for some reason, I prefer it. From carroll at tjc.com Wed Jun 11 04:07:51 2008 From: carroll at tjc.com (Terry Carroll) Date: Tue, 10 Jun 2008 19:07:51 -0700 (PDT) Subject: [Tutor] for loop In-Reply-To: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> Message-ID: On Tue, 10 Jun 2008, Sean Novak wrote: > I know I'm going to feel stupid on this one.. > > I would normally write this in PHP like this: > > for($i=1; i< count($someArray); $i++) > { > print $someArray[i] > } > > essentially,, I want to loop through an array skipping "someArray[0]" Like this? >>> someArray = ["able", "bakera", "charley", "dog", "fox"] >>> for i in range(1,len(someArray)): ... print somearray[i] ... baker charley dog fox >>> > I've tried this to no avail > > count = 0 > for i in range(1,10): > if count == 0: > continue > else: > count += 1 > print i > continue > > it prints absolutely nothing. Right. > count = 0 count is now equal to 0 > for i in range(1,10): you'll loop through 9 times, from 9 up to but not including 10. > if count == 0: > continue And because you initialized count to 0, it will always take this branch... > else: > count += 1 > print i > continue and never this branch where you increment count. From chester_lab at fltg.net Wed Jun 11 04:10:08 2008 From: chester_lab at fltg.net (FT) Date: Tue, 10 Jun 2008 22:10:08 -0400 Subject: [Tutor] IDE References: <20080610232351.4C1BE1E400A@bag.python.org> Message-ID: <003b01c8cb68$4cff5ba0$0301a8c0@brucetower> From: "jordan halsey" Sent: Tuesday, June 10, 2008 1:40 PM Any one here using cutter... http://www.fundza.com Free Java based ide with many built in functions and bindings. This is an especially useful tool if you are doing 3d or any kind of shader writing. Also, try this editor: http://www.contexteditor.org/ ConTEXT Text Editor Features unlimited open files unlimited editing file size, 4kB line length powerful syntax highlighting for: C/C++ Delphi/Pascal Java Java Script Visual Basic Perl/CGI HTML CSS SQL FoxPro 80x86 assembler Python PHP Tcl/Tk XML Fortran Foxpro InnoSetup scripts powerful custom defined syntax highlighter multilanguage support English German French Croatian Chinese Czech Danish Dutch Estonian Esperanto Spanish Galego Italian Hungarian Portuguese (Brazil) Russian Slovakian Polish Lithuanian Latvian Slovenian Turkish project workspaces support unicode UTF8 support code templates customizable help files for each file type file explorer with favorites list file compare export to HTML/RTF conversion DOS->UNIX->Macintosh file formats editing position remembering across files macro recorder commenting/uncommenting code text sort normal and columnar text selection bookmarks search and replace with regular expressions search and replace text in all open files incremental search with text emphasizing C/Java-style block auto indent/outdent customizable color printing with print preview exporting configuration stored in registry customizable syntax highlighter colors, cursors, margin, gutter, line spacing... user definable execution keys, depending on file type capturing console applications standard output compiler output parser for positioning on error line powerful command line handler Powerful Python Editor Edit, create, and navigate Python code easily. Free Email: info at context.cx From lowelltackett at yahoo.com Wed Jun 11 04:07:20 2008 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Tue, 10 Jun 2008 19:07:20 -0700 (PDT) Subject: [Tutor] IDE In-Reply-To: Message-ID: <683600.91283.qm@web45908.mail.sp1.yahoo.com> "W W" answered the question to my satisfaction.  When I first saw the comment, I thought the auther was able to open two virtual windows in the same terminal (Linux) that he was able to view (and interact with) simultaneously.  That was the advice that I was inquiring after.  When I realized he simply opened two terminals, I kinda thought, 'oh yea...duh!' But, thanks for followng up and inquiring. >From the virtual desk of Lowell Tackett  --- On Tue, 6/10/08, Alan Gauld <alan.gauld at btinternet.com> wrote: From: Alan Gauld <alan.gauld at btinternet.com> Subject: Re: [Tutor] IDE To: tutor at python.org Date: Tuesday, June 10, 2008, 6:35 PM "Lowell Tackett" <lowelltackett at yahoo.com> wrote > 1) I have two terminal windows open, one with an interactive python > prompt, and the other with vim... > > How do you do that (as you describe above)? Can you elaborate on the question? He says he opens two terminal windows and runs vim in one and python in the other. What is it you want explained? Alan G _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jun 11 04:43:02 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Jun 2008 22:43:02 -0400 Subject: [Tutor] for loop In-Reply-To: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> References: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> Message-ID: <484F3BB6.1020304@gmail.com> Sean Novak wrote: > I know I'm going to feel stupid on this one.. > > I would normally write this in PHP like this: > > for($i=1; i< count($someArray); $i++) > { > print $someArray[i] > } > > essentially,, I want to loop through an array skipping "someArray[0]" > > but in python the for syntax is more like foreach in PHP.. for item in somearray[1:]: print i > > I've tried this to no avail > > count = 0 > for i in range(1,10): > if count == 0: > continue > else: > count += 1 > print i > continue > > it prints absolutely nothing. > -- Bob Gailer 919-636-4239 Chapel Hill, NC From tiagosaboga at gmail.com Wed Jun 11 04:01:26 2008 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Tue, 10 Jun 2008 23:01:26 -0300 Subject: [Tutor] for loop In-Reply-To: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> References: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> Message-ID: <20080611020126.GA3763@localdomain> On Tue, Jun 10, 2008 at 09:36:47PM -0400, Sean Novak wrote: > I know I'm going to feel stupid on this one.. > > I would normally write this in PHP like this: > > for($i=1; i< count($someArray); $i++) > { > print $someArray[i] > } > > essentially,, I want to loop through an array skipping "someArray[0]" > > but in python the for syntax is more like foreach in PHP.. > > I've tried this to no avail > > count = 0 > for i in range(1,10): > if count == 0: > continue > else: > count += 1 > print i > continue > > it prints absolutely nothing. The count var is never updated. What about: for i in someArray[1:]: print i Tiago Saboga. From mwalsh at groktech.org Wed Jun 11 05:22:10 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Tue, 10 Jun 2008 22:22:10 -0500 Subject: [Tutor] for loop In-Reply-To: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> References: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> Message-ID: <484F44E2.9060302@groktech.org> Sean Novak wrote: > I know I'm going to feel stupid on this one.. > I would normally write this in PHP like this: > > for($i=1; i< count($someArray); $i++) > { > print $someArray[i] > } > > essentially,, I want to loop through an array skipping "someArray[0]" > but in python the for syntax is more like foreach in PHP.. I can think of a few approaches, in no particular order -- the decision is somewhat data dependent, IMO. 1. Use the enumerate built-in somelist = ['one', 'two', 'three', 'four'] for count, element in enumerate(somelist): if count > 0: print element 2a. Slice the list to omit the first element for element in somelist[1:]: print element 2b. If somelist is a sequence of strings... print '\n'.join(somelist[1:]) > I've tried this to no avail > > count = 0 > for i in range(1,10): > if count == 0: > continue > else: > count += 1 > print i > continue > > it prints absolutely nothing. This never reaches 'print i', because count is not incremented when count == 0, and so it remains for all of the values in range(1, 10). HTH, Marty From alan.gauld at btinternet.com Wed Jun 11 05:26:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jun 2008 04:26:24 +0100 Subject: [Tutor] How to get a script to open a text file with Python? References: Message-ID: "Terry Carroll" wrote >> If TextPad is your default txt editor just use >> os.system("foo.txt") > > or os.startfile("foo.txt"); sounds like the equivalent, but for some > reason, I prefer it. Actually os.startfile was what I meant for the default case! Thanks for pointing it out. system() may work if the preference is already set but startfile is specifically intended for that scnario. Alan G From alan.gauld at btinternet.com Wed Jun 11 05:33:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jun 2008 04:33:31 +0100 Subject: [Tutor] for loop References: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> Message-ID: "Sean Novak" wrote > I would normally write this in PHP like this: > > for($i=1; i< count($someArray); $i++) > { > print $someArray[i] > } > > essentially,, I want to loop through an array skipping > "someArray[0]" for i,n in enumerate(myArray): if i == 0: continue print n is how I'd do it. > but in python the for syntax is more like foreach in PHP.. Indeed it is exactly like a foreach. I wish it were called foreach except that its more typing. But it would save much confusion among newbies! > count = 0 > for i in range(1,10): > if count == 0: count += 1 > continue > else: > print i Should work -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jun 11 05:35:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jun 2008 04:35:39 +0100 Subject: [Tutor] for loop References: <93B75811-C66C-4D6F-B644-89BE25DEAD39@snovak.com> <20080611020126.GA3763@localdomain> Message-ID: "Tiago Saboga" wrote > The count var is never updated. What about: > > for i in someArray[1:]: > print i Yes, that's much better than my enumerate version! :-) Alan G From cspears2002 at yahoo.com Wed Jun 11 06:17:34 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 10 Jun 2008 21:17:34 -0700 (PDT) Subject: [Tutor] static methods and class methods Message-ID: <120286.49155.qm@web51601.mail.re2.yahoo.com> I am reading Wesley Chun's "Core Python Programming" (2nd Edition) and have reached the part on static and class methods. I typed in the following to demonstrate the difference between the two methods: >>> class TestClassMethod: ... def foo(cls): ... print 'calling class method foo()' ... print 'foo() is part of class:',cls.__name__ ... foo = classmethod(foo) ... >>> class TestStaticMethod: ... def foo(): ... print 'calling static method foo()' ... foo = staticmethod(foo) ... >>> tsm = TestStaticMethod() >>> TestStaticMethod.foo() calling static method foo() >>> tcm = TestClassMethod() >>> TestClassMethod.foo() calling class method foo() foo() is part of class: TestClassMethod >>> tcm.foo > >>> According to the author, the result for typing in 'tcm.foo' is calling class method foo() foo() is part of class: TestClassMethod Did I do something wrong or is this an error on the book's part? Intuitively, the answer I received makes more sense to me. I am still unsure of the difference of static and class methods. Can someone enlighten me? Thanks! From marilyn at deliberate.com Wed Jun 11 06:41:54 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 10 Jun 2008 21:41:54 -0700 (PDT) Subject: [Tutor] static methods and class methods In-Reply-To: <120286.49155.qm@web51601.mail.re2.yahoo.com> References: <120286.49155.qm@web51601.mail.re2.yahoo.com> Message-ID: <53854.66.218.47.125.1213159314.squirrel@mail.tigertech.net> On Tue, June 10, 2008 9:17 pm, Christopher Spears wrote: > I am reading Wesley Chun's "Core Python Programming" (2nd Edition) and > have reached the part on static and class methods. I typed in the > following to demonstrate the difference between the two methods: > >>>> class TestClassMethod: > ... def foo(cls): > ... print 'calling class method foo()' > ... print 'foo() is part of class:',cls.__name__ > ... foo = classmethod(foo) > ... > > >>>> class TestStaticMethod: > ... def foo(): > ... print 'calling static method foo()' > ... foo = staticmethod(foo) > ... > >>>> tsm = TestStaticMethod() TestStaticMethod.foo() >>>> > calling static method foo() >>>> tcm = TestClassMethod() TestClassMethod.foo() >>>> > calling class method foo() foo() is part of class: TestClassMethod >>>> tcm.foo > 0xb7da0f2c>> > >>>> > > According to the author, the result for typing in 'tcm.foo' is You forgot to put () after the method name. Wesley has them. Class methods and static methods can be called, even when you don't have an instance of the class. I think that that's all there is to it. With the class method, the interpreter provides the class itself as the first argument. With the static, nothing comes in. What else? Marilyn Davis > > > calling class method foo() foo() is part of class: TestClassMethod > > Did I do something wrong or is this an error on the book's part? > Intuitively, the answer I received makes more sense to me. I am still > unsure of the difference of static and class methods. Can someone > enlighten me? > > Thanks! > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cspears2002 at yahoo.com Wed Jun 11 07:12:17 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 10 Jun 2008 22:12:17 -0700 (PDT) Subject: [Tutor] error message with multiple inheritance Message-ID: <150475.41756.qm@web51603.mail.re2.yahoo.com> I've been working out of Core Python Programming (2nd Edition). Here is an example demonstrating multiple inheritance. >>> class A(object): ... pass ... >>> class B(A): ... pass ... >>> class C(B): ... pass ... >>> class D(A, B): ... pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases B, A What does this error message mean? The example worked in the book. I checked in the docs and could not find anything. Thanks! From trey at opmstech.org Wed Jun 11 07:11:49 2008 From: trey at opmstech.org (Trey Keown) Date: Wed, 11 Jun 2008 00:11:49 -0500 (CDT) Subject: [Tutor] Python-windows command prompt interaction? Message-ID: <63598.75.137.243.71.1213161109.squirrel@webmail.opmstech.org> Hey all, I'm creating a program that will copy a user's internet history from Internet Explorer, and I'm having a bit of trouble. I need to get python to either initiate a command via the command prompt, or open a file with its default program (in this case, a .bat file with cmd.exe). I've been googling a bit, but I can't seem to find any answers. Thanks for any help. From juzzydee at gmail.com Wed Jun 11 08:10:16 2008 From: juzzydee at gmail.com (Juzzy Dee) Date: Wed, 11 Jun 2008 16:10:16 +1000 Subject: [Tutor] Python-windows command prompt interaction? In-Reply-To: <63598.75.137.243.71.1213161109.squirrel@webmail.opmstech.org> References: <63598.75.137.243.71.1213161109.squirrel@webmail.opmstech.org> Message-ID: <1a8bfa70806102310h9873d72pa46119d01745e689@mail.gmail.com> On Wed, Jun 11, 2008 at 3:11 PM, Trey Keown wrote: > Hey all, > I'm creating a program that will copy a user's internet history from > Internet Explorer, and I'm having a bit of trouble. > > I need to get python to either initiate a command via the command prompt, > or open a file with its default program (in this case, a .bat file with > cmd.exe). > > I've been googling a bit, but I can't seem to find any answers. > > Thanks for any help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------- I think os.system should do the trick in running something from the command line. e.g os.sytem('dir') Will run the dir command. I'm not sure if that's what you're looking for but it sounds about right. -------------- next part -------------- An HTML attachment was scrubbed... URL: From simozack at yahoo.it Wed Jun 11 08:25:32 2008 From: simozack at yahoo.it (simone) Date: Wed, 11 Jun 2008 08:25:32 +0200 Subject: [Tutor] error message with multiple inheritance In-Reply-To: <150475.41756.qm@web51603.mail.re2.yahoo.com> References: <150475.41756.qm@web51603.mail.re2.yahoo.com> Message-ID: <484F6FDC.5040403@yahoo.it> Christopher Spears ha scritto: > I've been working out of Core Python Programming (2nd Edition). Here is an example demonstrating multiple inheritance. > >>>> class A(object): > ... pass > ... >>>> class B(A): > ... pass > ... >>>> class C(B): > ... pass > ... >>>> class D(A, B): > ... pass > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases B, A > > What does this error message mean? The example worked in the book. I checked in the docs and could not find anything. http://www.python.org/download/releases/2.3/mro/ Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From pine508 at hotmail.com Wed Jun 11 08:23:13 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 11 Jun 2008 02:23:13 -0400 Subject: [Tutor] when is object relational mapping for Python warranted? Message-ID: (tried to write a descriptive subject line) I'm curious whether I should consider learning either SQLObject or SQLAlchemy, and whether my needs would be worth it. I am learning to use SQlite databases for fairly simple storage and later search, and have only recently learned about object relational mapping (ORM). "Fairly simple" = 4-6 tables with no more than 2-10 fields each, 100-5,000 records, with queries doing basic LIKE and other matches, nothing fancy. I'd like to hear opinions on when it is worth it to use these ORM tools for a Python database application, that is, in terms of the complexity of the database or queries or the application, or when basic Python and SQL is sufficient. It's a personal preference, I'm sure, but I just wanted to get some opinions. Also, if there is an opinion about either of these two ORMs in terms of learning curve, quality, etc. Thanks, Che _________________________________________________________________ It?s easy to add contacts from Facebook and other social sites through Windows Live? Messenger. Learn how. https://www.invite2messenger.net/im/?source=TXT_EML_WLH_LearnHow -------------- next part -------------- An HTML attachment was scrubbed... URL: From timovwb at gmail.com Wed Jun 11 10:10:11 2008 From: timovwb at gmail.com (Timo) Date: Wed, 11 Jun 2008 10:10:11 +0200 Subject: [Tutor] Copy file as root Message-ID: <484f8853.05a4100a.506c.ffff96ca@mx.google.com> Hello, I'm writing a program in Python/pyGTK and I need to be root 2 times. The first time is to open a file, let's say menu.lst. I use os.system('gksudo gedit /boot/grub/menu.lst'), so that works. But what if I have a copy of the file on my desktop? I use shutil.copyfile() to copy the file from /boot/grub/ to /home/user/Desktop, but ofcourse need to be root to copy it back. So, how can I use shutil.copyfile() with gksudo to ask the password? Or is the another good way to do this in Python? Greets, Timo From wescpy at gmail.com Wed Jun 11 10:19:36 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Jun 2008 01:19:36 -0700 Subject: [Tutor] doc string format ? In-Reply-To: References: Message-ID: <78b3a9580806110119p340dac4exbbaf26cadf6f1b4f@mail.gmail.com> > I am trying to improve my code quality and have started using doc > strings. What format do you guys use for your doc strings ? > I have 'made up' the following general format ... > > def gen_vhost(kmotion_dir): > """ > Generate the kmotion vhost file from vhost_template expanding %directory% > strings to their full paths as defined in kmotion.rc > > arguments : > kmotion_dir ... the 'root' directory of kmotion > > exceptions: > exit ... if kmotion.rc cannot be read > > returns: > """ dave, excellent question and good to see that "you care" enough to ask. docstrings are one of Python's strengths, esp. given some of the external tools that are at your disposal. a) my 1st suggestion is to add some code to any of your docstrings where it makes sense; and even better would be some output. for example: def foo(x): """foo(x): display argument 'x' >>> foo(123) 123 """ print x this is helpful because if you're writing code for others (including yourself), it's easy to see what the proper syntax/usage is. b) given the above, wouldn't it be neat if there was a tool that could actually *execute* that code in your docstring as a regression test to (help) ensure code correctness? well, there is, and it's called the doctest module. if you add in the snippet below, you've just added testing for your code (and docstring)! def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test() when you run your program, it should give no output if things ran swimmingly. if you do get output, that means that something went wrong. to see that it really works, just run your code with a "-v" flag: $ foo.py -v Trying: foo(123) Expecting: 123 ok 3 items had no tests: __main__ __main__.User __main__._test 1 items passed all tests: 1 tests in __main__.foo 1 tests in 4 items. 1 passed and 0 failed. Test passed. ----- the output tells you that of the 4 places that docstrings could go, only 1 had a test in a docstring (the other 3 didn't). c) on top of this, i would also 2nd kent's suggestion of using Epydoc, which is also compatible with doctest docstrings: http://epydoc.sourceforge.net/manual-epytext.html adding a bit more, you get this: def foo(x): """foo(x): display argument 'x' >>> foo(123) 123 @param x: this is the main arg for foo() @type x: 'x' can be any object, i.e., int, str, etc. @return: None since there is no explicit return """ print x now you can use Epydoc to generate HTML or PDF documentation of your entire code base! hope this helps! -- 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 wescpy at gmail.com Wed Jun 11 10:21:17 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Jun 2008 01:21:17 -0700 Subject: [Tutor] doc string format ? In-Reply-To: References: Message-ID: <78b3a9580806110121i53fe3765o2719595d667b418f@mail.gmail.com> > I am trying to improve my code quality and have started using doc > strings. What format do you guys use for your doc strings ? > I have 'made up' the following general format ... > > def gen_vhost(kmotion_dir): > """ > Generate the kmotion vhost file from vhost_template expanding %directory% > strings to their full paths as defined in kmotion.rc > > arguments : > kmotion_dir ... the 'root' directory of kmotion > > exceptions: > exit ... if kmotion.rc cannot be read > > returns: > """ dave, excellent question and good to see that "you care" enough to ask. docstrings are one of Python's strengths, esp. given some of the external tools that are at your disposal. a) my 1st suggestion is to add some code to any of your docstrings where it makes sense; and even better would be some output. for example: def foo(x): """foo(x): display argument 'x' >>> foo(123) 123 """ print x this is helpful because if you're writing code for others (including yourself), it's easy to see what the proper syntax/usage is. b) given the above, wouldn't it be neat if there was a tool that could actually *execute* that code in your docstring as a regression test to (help) ensure code correctness? well, there is, and it's called the doctest module. if you add in the snippet below, you've just added testing for your code (and docstring)! def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test() when you run your program, it should give no output if things ran swimmingly. if you do get output, that means that something went wrong. to see that it really works, just run your code with a "-v" flag: $ foo.py -v Trying: foo(123) Expecting: 123 ok 3 items had no tests: __main__ __main__.User __main__._test 1 items passed all tests: 1 tests in __main__.foo 1 tests in 4 items. 1 passed and 0 failed. Test passed. ----- the output tells you that of the 4 places that docstrings could go, only 1 had a test in a docstring (the other 3 didn't). c) on top of this, i would also 2nd kent's suggestion of using Epydoc, which is also compatible with doctest docstrings: http://epydoc.sourceforge.net/manual-epytext.html adding a bit more, you get this: def foo(x): """foo(x): display argument 'x' >>> foo(123) 123 @param x: this is the main arg for foo() @type x: 'x' can be any object, i.e., int, str, etc. @return: None since there is no explicit return """ print x now you can use Epydoc to generate HTML or PDF documentation of your entire code base! hope this helps! -- 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 mail at timgolden.me.uk Wed Jun 11 10:22:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 11 Jun 2008 09:22:34 +0100 Subject: [Tutor] Python-windows command prompt interaction? In-Reply-To: <63598.75.137.243.71.1213161109.squirrel@webmail.opmstech.org> References: <63598.75.137.243.71.1213161109.squirrel@webmail.opmstech.org> Message-ID: <484F8B4A.1070205@timgolden.me.uk> Trey Keown wrote: > Hey all, > I'm creating a program that will copy a user's internet history from > Internet Explorer, and I'm having a bit of trouble. > > I need to get python to either initiate a command via the command prompt, > or open a file with its default program (in this case, a .bat file with > cmd.exe). > > I've been googling a bit, but I can't seem to find any answers. Depending on *exactly* what you're trying to achieve here, you're going to want one of two things: 1) The subprocess module (and probably the call function) http://docs.python.org/lib/node529.html 2) The os module's startfile function http://docs.python.org/lib/os-process.html There are other possiblities open to you, including automating IE and using comtypes to access the IURLHistory interfaces, but if you're just starting out then maybe you're better off sticking with the builtin stuff. TJG From wescpy at gmail.com Wed Jun 11 10:28:00 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Jun 2008 01:28:00 -0700 Subject: [Tutor] static methods and class methods In-Reply-To: <120286.49155.qm@web51601.mail.re2.yahoo.com> References: <120286.49155.qm@web51601.mail.re2.yahoo.com> Message-ID: <78b3a9580806110128q1e0c7e36u9a73452f4f0c2ca6@mail.gmail.com> >>>> tcm.foo > > > > Did I do something wrong or is this an error on the book's part? Intuitively, the answer I received makes more sense to me. I am still unsure of the difference of static and class methods. Can someone enlighten me? hi there, thanks for picking up the book. there are definitely some typos in the book, but this isn't one of them. marilyn is correct, instead of *calling* the method, you asked the interpreter to show you what object it represents [repr() for those if you who know]. tcm.foo <--- that is a function/method object that is callable tcm.foo() <-- actually call the function and return its output all you did wrong was to ask for the object instead of calling it. hope this helps! -- wesley ps. be sure to check out the Errata page at the book's website to get all the corrections... i'll be updating it within a few days with the latest changes. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "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 mail at timgolden.me.uk Wed Jun 11 10:36:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 11 Jun 2008 09:36:26 +0100 Subject: [Tutor] when is object relational mapping for Python warranted? In-Reply-To: References: Message-ID: <484F8E8A.1090309@timgolden.me.uk> Che M wrote: > I'm curious whether I should consider learning either SQLObject > or SQLAlchemy, and whether my needs would be worth it. I am > learning to use SQlite databases for fairly simple storage and later > search, and have only recently learned about object relational > mapping (ORM). "Fairly simple" = 4-6 tables with no more than > 2-10 fields each, 100-5,000 records, with queries doing basic LIKE > and other matches, nothing fancy. > > I'd like to hear opinions on when it is worth it to use these ORM tools > for a Python database application, that is, in terms of the complexity > of the database or queries or the application, or when basic Python > and SQL is sufficient. It's a personal preference, I'm sure, but I just > wanted to get some opinions. Also, if there is an opinion about either > of these two ORMs in terms of learning curve, quality, etc. Good question, I think. My answer would be: pick an ORM to learn anyway. You can't go far wrong knowing what's there and the learning curves are not steep. You've mentioned sqlalchemy and SQLObject. There are also Storm, MotherDb and Elixir (which is an easier layer over sqlalchemy). SQLObject is more mature but sqlalchemy is quite popular and has a lot of community support. The others are relatively new and I don't know too much about them. But the other side of the coin is: when do you need an ORM at all? I'm a professional SQL programmer so I tend to find extra tools getting in the way. If I'm dealing with relational data, I think in SQL and, no matter how good the ORM's syntax, I find it a distraction. But where I *do* find an ORM useful is in dealing with very simple interactions with one or two joins which are handled automatically and which save me writing fairly tedious boilerplate. In short, I use ORMs for small projects, but not for big ones. So far. TJG From dave6502 at googlemail.com Wed Jun 11 11:10:54 2008 From: dave6502 at googlemail.com (dave selby) Date: Wed, 11 Jun 2008 10:10:54 +0100 Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: Thanks for all your help guys, I am getting a strong consensus that f.close() should be used everywhere, reading files as well as writing files and not to rely on the PVM to do clean-up for you. The whole topic came up because I just finished reading 'learning python' 3rd edition OReilly as a refresher where there are multiple instances of suggesting that you do the exact opposite eg ... [line.rstrip() for line in open('myfile')] ... p361 for line in open('script1.py') ... p261& p276 where it is described as 'best practice' for reading files line by line etc ... Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From qsqgeekyogdty at tiscali.co.uk Wed Jun 11 11:35:30 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Wed, 11 Jun 2008 10:35:30 +0100 (GMT+01:00) Subject: [Tutor] RegEx to search for the '$' symbol Message-ID: <26410943.1213176930690.JavaMail.root@ps35.mc.tiscali.sys> Hi, Silly question but how do you use python's re module to find dictionary items that contain the '$' symbol. Thanks David From mfana-boy at thusa.co.za Wed Jun 11 09:49:28 2008 From: mfana-boy at thusa.co.za (Mfana-boy Msibi) Date: Wed, 11 Jun 2008 09:49:28 +0200 Subject: [Tutor] Help python coding not working Message-ID: How to add a delete button in your web page in Python -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jun 11 12:47:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 06:47:44 -0400 Subject: [Tutor] error message with multiple inheritance In-Reply-To: <484F6FDC.5040403@yahoo.it> References: <150475.41756.qm@web51603.mail.re2.yahoo.com> <484F6FDC.5040403@yahoo.it> Message-ID: <1c2a2c590806110347n5f6edb21qbd2b7d379ac8a414@mail.gmail.com> On Wed, Jun 11, 2008 at 2:25 AM, simone wrote: > Christopher Spears ha scritto: >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: Error when calling the metaclass bases >> Cannot create a consistent method resolution >> order (MRO) for bases B, A >> >> What does this error message mean? The example worked in the book. I >> checked in the docs and could not find anything. > > http://www.python.org/download/releases/2.3/mro/ In layman's terms: For class C, the method resolution order is C, B, A, object. Note that B is before A. For class D, A would come before B because of the order of declaration of base classes. This conflict causes the TypeError. One way to fix it is to define D as class D(B, A): pass Kent From onyxtic at gmail.com Wed Jun 11 12:53:09 2008 From: onyxtic at gmail.com (Evans Anyokwu) Date: Wed, 11 Jun 2008 11:53:09 +0100 Subject: [Tutor] Help python coding not working In-Reply-To: References: Message-ID: Just like you'd add any other button on your web page -- Evans On Wed, Jun 11, 2008 at 8:49 AM, Mfana-boy Msibi wrote: > How to add a delete button in your web page in Python > > > > > __________ Information from ESET NOD32 Antivirus, version of virus > signature database 3175 (20080611) __________ > > The message was checked by ESET NOD32 Antivirus. > > http://www.eset.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From muchanek at gmail.com Wed Jun 11 13:29:31 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Wed, 11 Jun 2008 14:29:31 +0300 Subject: [Tutor] RegEx to search for the '$' symbol In-Reply-To: References: Message-ID: <1213183771.9578.17.camel@www.kinuthia.com> > ------------------------------ > > Message: 4 > Date: Wed, 11 Jun 2008 10:35:30 +0100 (GMT+01:00) > From: "qsqgeekyogdty at tiscali.co.uk" > Subject: [Tutor] RegEx to search for the '$' symbol > To: tutor at python.org > Message-ID: <26410943.1213176930690.JavaMail.root at ps35.mc.tiscali.sys> > Content-Type: text/plain;charset="UTF-8" > > Hi, > Silly question but how do you use python's re module to find > dictionary items that contain the '$' symbol. Hi, I no expert but here is my dime's worth... > >>> import re > >>> d = {'k':'$',1:'2','p':'$','j':'$dollar','l': 'dol$lar'} > >>> for i in d.values(): > ... re.findall(r'.*\$.*',i) > ... > > [] > ['$'] > ['$dollar'] > ['dol$lar'] > [] > > NB: > Empty matches are included in the result unless they touch the beginning of another match. > > > Kinuthia... > Thanks > David > > > > From kent37 at tds.net Wed Jun 11 13:30:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 07:30:52 -0400 Subject: [Tutor] static methods and class methods In-Reply-To: <120286.49155.qm@web51601.mail.re2.yahoo.com> References: <120286.49155.qm@web51601.mail.re2.yahoo.com> Message-ID: <1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> On Wed, Jun 11, 2008 at 12:17 AM, Christopher Spears wrote: >>>> tcm.foo > > >>>> > > According to the author, the result for typing in 'tcm.foo' is > > calling class method foo() > foo() is part of class: TestClassMethod Try tcm.foo() tcm.foo without parentheses is the classmethod itself. You need parentheses to actually call it. > Did I do something wrong or is this an error on the book's part? Intuitively, the answer I received makes more sense to me. I am still unsure of the difference of static and class methods. Can someone enlighten me? A class method receives the class it was called on as the first argument. This can be useful with subclasses. A staticmethod doesn't get a a class or instance argument. It is just a way to put a plain function into the scope of a class. Both of these are rarely used; I don't think I have ever written a class method in live code. I have used staticmethods as a convenient way to put a function into a class namespace. Kent From kent37 at tds.net Wed Jun 11 13:45:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 07:45:48 -0400 Subject: [Tutor] RegEx to search for the '$' symbol In-Reply-To: <26410943.1213176930690.JavaMail.root@ps35.mc.tiscali.sys> References: <26410943.1213176930690.JavaMail.root@ps35.mc.tiscali.sys> Message-ID: <1c2a2c590806110445i24f42a1dl7ad6c3eca240c4f8@mail.gmail.com> On Wed, Jun 11, 2008 at 5:35 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hi, > Silly question but how do you use python's re module to find > dictionary items that contain the '$' symbol. There is no need to use re for this. [ v for v in d.values() if '$' in v ] will give you a list of all values containing '$'. Kent From qsqgeekyogdty at tiscali.co.uk Wed Jun 11 14:25:31 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Wed, 11 Jun 2008 13:25:31 +0100 (GMT+01:00) Subject: [Tutor] RegEx to search for the '$' symbol Message-ID: <21230455.1213187131222.JavaMail.root@ps35.mc.tiscali.sys> thank you all. ______________________________________________________ New Online ID Theft Protection - http://www.tiscali.co.uk/spyguard From gabriela.soares.fcup at gmail.com Wed Jun 11 15:03:45 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 14:03:45 +0100 Subject: [Tutor] python gui Message-ID: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Greetings, I want to make a dynamic dashboard, something like: http://examples.adobe.com/flex3/labs/dashboard/main.html# but using python. Is it possible ? Thanks in advance. Best regards, Gabriela Soares. -- Gabriela Soares "I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." Nelson Mandela -------------- next part -------------- An HTML attachment was scrubbed... URL: From oldmantaggie at gmail.com Wed Jun 11 15:50:29 2008 From: oldmantaggie at gmail.com (John Chandler) Date: Wed, 11 Jun 2008 09:50:29 -0400 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: References: Message-ID: <8e087c6d0806110650o13c9a34ob96337608bd80655@mail.gmail.com> Why not have python copy the text to the clipboard for you? You will need the win32 packages, which is hardly a turnoff since they are so useful. import win32clipboard win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text) win32clipboard.CloseClipboard() Python puts it on the clipboard for use for you! I trump the above '5 steps' and even '1 step' with 0 steps! I hope this helps. (Remember to close the clipboard, I forgot when I was first trying to come up with this and it does not work if the clipboard remains open. Thanks goes to Bob Gailer and his 2003 post for the syntax reminder) On Tue, Jun 10, 2008 at 11:26 PM, Alan Gauld wrote: > > "Terry Carroll" wrote > > If TextPad is your default txt editor just use >>> os.system("foo.txt") >>> >> >> or os.startfile("foo.txt"); sounds like the equivalent, but for some >> reason, I prefer it. >> > > Actually os.startfile was what I meant for the default case! > Thanks for pointing it out. system() may work if the preference is > already set but startfile is specifically intended for that scnario. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -John Chandler -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at drinktomi.com Tue Jun 10 20:49:05 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Tue, 10 Jun 2008 11:49:05 -0700 Subject: [Tutor] IDE In-Reply-To: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> Message-ID: <448C05BE-131B-432F-9A47-C9FB601479A0@drinktomi.com> On Jun 10, 2008, at 4:07 AM, Sean Novak wrote: > > I'm looking for the perfect IDE, preferably open source. I've > installed Bluefish, which I find to be a little buggy still. I'm > just starting to dive into emacs, which I feel is a little > daunting. If someone has tried a few different IDEs and found the > one that they love.. I'd be interested in your insight! Pydev and Eclipse are an industrial strength solution. You get a full integrated IDE: - An editor with spell checking, syntax highlighting, code completion, templates, etc. - An integrated visual debugger. - Outline navigators - Remote debugging. - Refactoring support - Navigation tools like 'go to definition' - Revision control integration with just about every revision control system on the planet. - Unit test runner - Interactive python execution - Job management via Mylar plugin - SQL editing via SQLExplorer plugin - HTML/XML/Javascript development plugins - Run external tools from within the IDE - To do lists - Multi-language development - etc. - Jeff Younker - jeff at drinktomi.com - From tavspamnofwd at googlemail.com Wed Jun 11 16:37:11 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Wed, 11 Jun 2008 15:37:11 +0100 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: References: Message-ID: Or this can open most things: import webbrowser webbrowser.open_new('file///' + filename) On 11/06/2008, Alan Gauld wrote: > > "Terry Carroll" wrote > > > > > > > If TextPad is your default txt editor just use > > > os.system("foo.txt") > > > > > > > or os.startfile("foo.txt"); sounds like the equivalent, but for some > > reason, I prefer it. > > From michael at yavarsity.com Wed Jun 11 16:48:28 2008 From: michael at yavarsity.com (Michael yaV) Date: Wed, 11 Jun 2008 10:48:28 -0400 Subject: [Tutor] wanting to learn Message-ID: A little background on myself. I am a web designer so I am a Mac person. I have taught myself HTML and flash by reading manuals and a lot of trial and error over the last 11 years. I have always wanted to learn a language like php, asp, .net but I never took the time to learn them. I have recently found Python and believe this is the language that I will "hang-my-hat-on" and learn. I don't have any formal training in any coding language but I do have the "will" to learn. Since my background is web, I want to learn Python and how it relates to the web. I have been told that I need to learn and understand the basics in "standard/general" Python before I move onto something like "django" but really, how much Python do I need to know before I can head down the web path? Is Python a language a total beginner/tutorial reader like myself can learn or do I need to take classes at a local college? Is their is just too much to learn to do this on my own. I am starting to get a bit over whelmed with all of the information I'm finding. So, can anybody head me in the right direction with my endeavor? Since I am on an intel/Mac which IDE should I be using? Which one will be robust enough to take me through my journey? I have started with IDLE but I have been told that it is a bare bones IDE. So, if I need to learn how to use a IDE, I want to learn one that I will not have to discard as I become more familiar with the Python language. Thanks for any help. From srilyk at gmail.com Wed Jun 11 17:16:17 2008 From: srilyk at gmail.com (W W) Date: Wed, 11 Jun 2008 10:16:17 -0500 Subject: [Tutor] wanting to learn In-Reply-To: References: Message-ID: <333efb450806110816l2ada2c46me594661445200341@mail.gmail.com> On Wed, Jun 11, 2008 at 9:48 AM, Michael yaV wrote: > A little background on myself. I am a web designer so I am a Mac person. I > have taught myself HTML and flash by reading manuals and a lot of trial and > error over the last 11 years. I have always wanted to learn a language like > php, asp, .net but I never took the time to learn them. I have recently > found Python and believe this is the language that I will "hang-my-hat-on" > and learn. I'm sure several of us come from similar backgrounds, if not so focused on HTML/flash > I don't have any formal training in any coding language but I do have the > "will" to learn. That's probably the most important part. You may find that *some* of the principles you've learned in html/flash will carry over. If you've had any experience with javascript, that will also be rather helpful. > Since my background is web, I want to learn Python and how it relates to the > web. I have been told that I need to learn and understand the basics in > "standard/general" Python before I move onto something like "django" but > really, how much Python do I need to know before I can head down the web > path? I'm sure there are several on the list who are better qualified to answer this, seeing as how I haven't even touched django ;) > Is Python a language a total beginner/tutorial reader like myself can learn > or do I need to take classes at a local college? Is their is just too much > to learn to do this on my own. I am starting to get a bit over whelmed with > all of the information I'm finding. If you took any programming classes, that would be helpful. As a great beginning resource, I'd recommend Think Python, available here: http://www.greenteapress.com/thinkpython/ It's one of the sources I used in my migration to python. I'm currently still in school, and c++ is the main language they teach here so I bounce back and forth (specifically, i do c++ pertaining to school work, and sometimes for kicks I write my ~30 min c++ program in ~5 in python) > So, can anybody head me in the right direction with my endeavor? > Since I am on an intel/Mac which IDE should I be using? Which one will be > robust enough to take me through my journey? I have started with IDLE but I > have been told that it is a bare bones IDE. So, if I need to learn how to > use a IDE, I want to learn one that I will not have to discard as I become > more familiar with the Python language. I'm sure asking a question like that will get you more various answers than asking "which is your favourite food?" However, my personal preference is using vi/vim (which you should have built in on your mac, along with python). If you open a mac terminal window and type "vimtutor" at the prompt, it should start the vim tutor program. There are many programmers across various different programming languages and platforms that use vi/vim as their ide. That's my personal recommendation, and at the very least you should give a few different editors/IDEs a try to see which one fits your style/comfort zone best. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From srilyk at gmail.com Wed Jun 11 17:18:15 2008 From: srilyk at gmail.com (W W) Date: Wed, 11 Jun 2008 10:18:15 -0500 Subject: [Tutor] python gui In-Reply-To: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Message-ID: <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares wrote: > Greetings, > > I want to make a dynamic dashboard, something like: > > http://examples.adobe.com/flex3/labs/dashboard/main.html# > > but using python. Is it possible ? Yes. -Wayne From norman at khine.net Wed Jun 11 17:21:20 2008 From: norman at khine.net (Norman Khine) Date: Wed, 11 Jun 2008 17:21:20 +0200 Subject: [Tutor] python gui In-Reply-To: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Message-ID: <484FED70.8020308@khine.net> I am nto an expert but this might help: http://gaeswf.appspot.com/examples/initial/flex/ Norman Gabriela Soares wrote: > Greetings, > > I want to make a dynamic dashboard, something like: > > http://examples.adobe.com/flex3/labs/dashboard/main.html# > > but using python. Is it possible ? > > > Thanks in advance. > > Best regards, > > Gabriela Soares. > > > > -- > Gabriela Soares > > "I learned that courage was not the absence of fear, but the triumph > over it. The brave man is not he who does not feel afraid, but he who > conquers that fear." > Nelson Mandela > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tavspamnofwd at googlemail.com Wed Jun 11 18:05:18 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Wed, 11 Jun 2008 17:05:18 +0100 Subject: [Tutor] IDE In-Reply-To: <448C05BE-131B-432F-9A47-C9FB601479A0@drinktomi.com> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <448C05BE-131B-432F-9A47-C9FB601479A0@drinktomi.com> Message-ID: I use PythonWin and find the Interactive Python Window invaluable. Does anyone know which of the IDE's mentioned above have a similar feature. (I'm on Vista,sorry!) Thanks. From sanelson at gmail.com Wed Jun 11 19:10:11 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 11 Jun 2008 18:10:11 +0100 Subject: [Tutor] Web Stats Message-ID: Hi, I've been asked to produce a report showing all possible resources in a website, together with statistics on how frequently they've been visited. Nothing fancy - just number and perhaps date of last visit. This has to include resources which have not been visited, as the point is to clean out old stuff. I have several years of apache weblogs. Is there something out there that already does this? If not, or if it's interesting and not beyond the ken of a reasonable programmer, could anyone provide some pointers on where to start? Thanks, S. From wim at dehul.net Wed Jun 11 19:33:07 2008 From: wim at dehul.net (Wim De Hul) Date: Wed, 11 Jun 2008 19:33:07 +0200 Subject: [Tutor] IDE In-Reply-To: <20080610212121.EE73A1E4003@bag.python.org> References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com> <7B3C37F3-6252-4148-8892-76E18ADFACB1@yavarsity.com> <7941B2693F32294AAF16C26B679A258D0283795D@csomb01.corp.atmel.com> <13D5C511-DFEB-4602-8649-071C3DB80087@yavarsity.com> <1c2a2c590806101107y7ee7c41bh277fe1e11be56f5c@mail.gmail.com> <368D1A9F-B215-4D5A-9D71-29BE94C51A7B@yavarsity.com> <20080610212121.EE73A1E4003@bag.python.org> Message-ID: <57835622-2CE6-4E08-90F0-C3D609F35F57@dehul.net> To name a few: . you can specify the keyboard behaviour (Vi, Emacs,...) . Syntax help . debugging: step, break, etc, debug I/O window . python shell I used Vi before to write all my code. Infact I still do, but for python, I use Wingware :-) Cheers! Wim On 10 Jun 2008, at 23:21, Dick Moores wrote: > At 11:48 AM 6/10/2008, Wim De Hul wrote: >> What about Wingware, >> >> I use Wingware professional at ork and the free version at home. >> >> Here's the link: http://www.wingware.com > > What do you like about Wing? Esp. Wing Pro? > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dos.fool at gmail.com Wed Jun 11 18:58:40 2008 From: dos.fool at gmail.com (max baseman) Date: Wed, 11 Jun 2008 10:58:40 -0600 Subject: [Tutor] powerball Message-ID: as a fun little project i scripted a powerball program. it seems to have a bug in it that i cant find. from random import randrange wins=0 win=[] count =0 while count !=5: number=randrange(55)+1 win.append(number) count=count+1 powerball=randrange(42)+1 count=0 win.sort() while count !=146107962: numbers=[] count2=0 while count2 !=5: number=randrange(55)+1 if number in win: numbers.append(number) else: print "lose" break numbers.sort() ball=randrange(42)+1 if ball==powerball: print "win" print print print win, powerball From kent37 at tds.net Wed Jun 11 20:32:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 14:32:49 -0400 Subject: [Tutor] Web Stats In-Reply-To: References: Message-ID: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> On Wed, Jun 11, 2008 at 1:10 PM, Stephen Nelson-Smith wrote: > Hi, > > I've been asked to produce a report showing all possible resources in > a website, together with statistics on how frequently they've been > visited. Nothing fancy - just number and perhaps date of last visit. > This has to include resources which have not been visited, as the > point is to clean out old stuff. Take a look at AWStats (not Python). For do it yourself, loghetti might be a good starting point http://code.google.com/p/loghetti/ Kent From kent37 at tds.net Wed Jun 11 20:33:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 14:33:27 -0400 Subject: [Tutor] powerball In-Reply-To: References: Message-ID: <1c2a2c590806111133h6938759biab5018ca3f1093f1@mail.gmail.com> On Wed, Jun 11, 2008 at 12:58 PM, max baseman wrote: > as a fun little project i scripted a powerball program. it seems to have a > bug in it that i cant find. What does it do? What do you expect it to do? Kent From marilyn at deliberate.com Wed Jun 11 20:36:11 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed, 11 Jun 2008 11:36:11 -0700 (PDT) Subject: [Tutor] powerball In-Reply-To: References: Message-ID: <59950.66.218.47.125.1213209371.squirrel@mail.tigertech.net> On Wed, June 11, 2008 9:58 am, max baseman wrote: Hi Max, Here's your code with the indents preserved. I'll make my comments with >'s. from random import randrange wins=0 win=[] count =0 while count !=5: > To loop 5 times it is better to use: > for count in range(5): > stuff you want to do > Then all the loop controlling happens in one place and it is hard to > mess up. number=randrange(55)+1 win.append(number) count=count+1 powerball=randrange(42)+1 count=0 win.sort() while count !=146107962: numbers=[] count2=0 while count2 !=5: number=randrange(55)+1 > Yep, indeed, here you made the easy mistake of forgetting to + 1 to > count2. So, it probably spun forever right there. > I also don't see that "count" is every changed, so that would be another > spin. All these would go away by using 'for' 'in' and 'range'. > It looks like a fun program and a good start. > Marilyn Davis if number in win: numbers.append(number) else: print "lose" break numbers.sort() ball=randrange(42)+1 if ball==powerball: print "win" print print print win, powerball > as a fun little project i scripted a powerball program. it seems to have a > bug in it that i cant find. > > from random import randrange wins=0 win=[] count =0 while count !=5: > number=randrange(55)+1 win.append(number) count=count+1 > powerball=randrange(42)+1 count=0 win.sort() while count !=146107962: > numbers=[] count2=0 while count2 !=5: number=randrange(55)+1 if number in > win: > numbers.append(number) else: > print "lose" break numbers.sort() ball=randrange(42)+1 if ball==powerball: > print "win" print print print win, powerball > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Wed Jun 11 20:46:57 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 11 Jun 2008 14:46:57 -0400 Subject: [Tutor] powerball In-Reply-To: References: Message-ID: <48501DA1.5050209@gmail.com> max baseman wrote: > as a fun little project i scripted a powerball program. it seems to > have a bug in it that i cant find. To echo Kent: tell us the expected outcome and why you think there is a bug. Also please add a comment explaining the "magic" number 146107962. Also add a comment about "powerball". I had to Google it to find out what it is! That aside, the program will run forever (until interrupted). It is common practice to walk thru the program yourself to test it. I suggest you do this. Write down the values of variables and note when they change. Perhaps there are some that should change and are not changing. > > from random import randrange > wins=0 > win=[] > count =0 > while count !=5: > number=randrange(55)+1 > win.append(number) > count=count+1 > powerball=randrange(42)+1 > count=0 > win.sort() > while count !=146107962: > numbers=[] > count2=0 > while count2 !=5: > number=randrange(55)+1 > if number in win: > numbers.append(number) > else: > print "lose" > break > numbers.sort() > ball=randrange(42)+1 > if ball==powerball: > print "win" > print > print > print win, powerball > -- Bob Gailer 919-636-4239 Chapel Hill, NC From sanelson at gmail.com Wed Jun 11 21:58:56 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 11 Jun 2008 20:58:56 +0100 Subject: [Tutor] Web Stats In-Reply-To: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> References: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> Message-ID: Hello, >> This has to include resources which have not been visited, as the >> point is to clean out old stuff. > > Take a look at AWStats (not Python). Doesn't this 'only' parse weblogs? I'd still need some kind of spider to tell me all the possible resources available wouldn't I? It's a big website, with 1000s of pages. > For do it yourself, loghetti > might be a good starting point > http://code.google.com/p/loghetti/ Looks interesting, but again don't I fall foul of the "how can I know about what, by definition, doesn't feature in a log?" problem? S. > Kent > From clazzt at arnet.com.ar Wed Jun 11 22:05:05 2008 From: clazzt at arnet.com.ar (claxo) Date: Wed, 11 Jun 2008 17:05:05 -0300 (Hora est. de Sudamérica E.) Subject: [Tutor] it is ok that object.__init__ gets called multiple times? Message-ID: <20080611200934.A036A1E4005@bag.python.org> In the following code the __init__ for C would end calling two times object.__init__ . Is this ok or I calling for trouble ? To make explicit some context: object is the std python object super is not suposed to be used in any subclass class A(object): def __init__(self,**kwargs): object.__init__(self,**kwargs) self.m_a = kwargs['ka'] class B(object): def __init__(self,**kwargs): object.__init__(self,**kwargs) self.m_b = kwargs['kb'] class C(A,B): def __init__(self,**kwargs): A.__init__(self,**kwargs) B.__init__(self,**kwargs) From kent37 at tds.net Wed Jun 11 23:28:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 17:28:31 -0400 Subject: [Tutor] it is ok that object.__init__ gets called multiple times? In-Reply-To: <20080611200934.A036A1E4005@bag.python.org> References: <20080611200934.A036A1E4005@bag.python.org> Message-ID: <1c2a2c590806111428m55e2d649j6b4fc3390c666b3@mail.gmail.com> On Wed, Jun 11, 2008 at 4:05 PM, claxo wrote: > In the following code the __init__ for C would end calling two times object.__init__ . > Is this ok or I calling for trouble ? > To make explicit some context: > object is the std python object > super is not suposed to be used in any subclass Why not? This seems to me the problem super is designed to solve. OTOH why are you calling object.__init__() ? I don't think that is needed... Kent From washakie at gmail.com Wed Jun 11 23:31:32 2008 From: washakie at gmail.com (washakie) Date: Wed, 11 Jun 2008 14:31:32 -0700 (PDT) Subject: [Tutor] Upgrade Python distribution 2.4 to 2.5 Message-ID: <17787717.post@talk.nabble.com> Hello, I searched the web and python.org but I haven't found a good resource that explains how to upgrade python from 2.4 to 2.5 What I'm wondering is whether I'll have to start from scratch on the installation of all my external modules such as Numpy, Matplotlib, PyXML, etc... Could someone please comment on the best approach to upgrading? -- View this message in context: http://www.nabble.com/Upgrade-Python-distribution-2.4-to-2.5-tp17787717p17787717.html Sent from the Python - tutor mailing list archive at Nabble.com. From pythonnutter at gmail.com Thu Jun 12 00:19:26 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 12 Jun 2008 08:19:26 +1000 Subject: [Tutor] wanting to learn In-Reply-To: References: Message-ID: repost as didn't reply to list first time: 2008/6/12 Michael yaV : > A little background on myself. I am a web designer so I am a Mac person. I > have taught myself HTML and flash by reading manuals and a lot of trial and > error over the last 11 years. I have always wanted to learn a language like > php, asp, .net but I never took the time to learn them. I have recently > found Python and believe this is the language that I will "hang-my-hat-on" > and learn. I was web designer a while back, moved into security, then found python, other than that almost the same path as yourself. > I don't have any formal training in any coding language but I do have the > "will" to learn. > Since my background is web, I want to learn Python and how it relates to the > web. I have been told that I need to learn and understand the basics in > "standard/general" Python before I move onto something like "django" but > really, how much Python do I need to know before I can head down the web > path? Yes you will need to learn some python but not to the level of taking courses at college/uni straight off the get go. As you learn you will determine what you need as you go on as far as how deep/level the books and tutorials need to be. Don't be like most and put off the super timple tutorials. I had a lot of fun (after reading the Core python books out there) with the kids tutorial because it was just fun to play around and learn some python / work with some python in the process. Honestly I didn't learn anything because the core books taught me everything but if your brain is on information overload then start here: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ Once you tire of it you can move on to others (still freely available on the web and just a google search away): Non-Programmers Tutorial for Python Official Python Documentation: Text Processing in Python: Python Reference Manual: Python Imaging Library Handbook: How to Think Like a Computer Scientist - Learning with Python: Graphical Programming With Python - QT Edition: Dive Into Python: I had a lot of my first learning from the last, Dive Into Python, and can recommend it, then for books at the bookstore, I bought them all =) but if you only get one, its a tough choice, but wesley chuns core python programming (whatever the latest edition) is a very good book that will dig deep into every corner of python and expose it to you. While you are finish up on these last tutorials and books you'll be already at the level to start playing with django, the online djangobook is free and will help you out a lot. > Since I am on an intel/Mac which IDE should I be using? Which one will be > robust enough to take me through my journey? I have started with IDLE. IDEs are personal preference and likely to start great debates of opinion back and forth and around again and again ad nauseum. I've run vimtutor like the other poster suggested. However I just didn't use it and got rusty and now will need to run it again. It did not fit my brain well so I just never kept on using it. I know the basics of how to open, edit, save. But all the formatting shortcut keys which I will need are gone. Instead for the command line, you can absolutely not beat iPython shell. Its absolute amazing and you can find tons of free videos on the web showing it off by googling on iPython Tutorial etc. For GUI/IDEs I've tried them all from free to commercial. You can get free versions (cut down in features) of commercial ones like Wing-IDE (good but you need to run it in X11 on Mac) and Komodo IDE (my personal fav), and lots of free ones that may fit your needs / mind (SPE, Eric4, Eclipse with Pyton add-ins, Ulipad, etc. etc.) By far my personal favourites to date will be iPython for terminal, Komodo IDE for GUI IDE with Wing-IDE as a runner up. The final decision you will have is stick with the Apple complied/supplied Python which will lock you out of a few tiny features and lock you into a version without updates for a very long time (in other words until you buy a new version of OS X in most cases). Or you can go to python.org and install the standard framework python (this is my option perference and choice for all my Macs). Other option would be to use Easy Install from PEAK developer tools (google) to help install new modules from the web in egg format. Its a personal choice, its not hard to install modules the standard way (python setup.py install) in python and as a hint if you import the sys module you can use it to tell you all the paths python searches and in there it will show you where the directory is in your Mac for site packages to install all your downloaded modules to. Best of luck, Take it slow and have fun (selecting python gave you the last one, you have to do the first one). PN From kent37 at tds.net Thu Jun 12 00:34:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 18:34:21 -0400 Subject: [Tutor] Upgrade Python distribution 2.4 to 2.5 In-Reply-To: <17787717.post@talk.nabble.com> References: <17787717.post@talk.nabble.com> Message-ID: <1c2a2c590806111534s4589e7acwd8cddd3ae889e97c@mail.gmail.com> On Wed, Jun 11, 2008 at 5:31 PM, washakie wrote: > > Hello, I searched the web and python.org but I haven't found a good resource > that explains how to upgrade python from 2.4 to 2.5 > > What I'm wondering is whether I'll have to start from scratch on the > installation of all my external modules such as Numpy, Matplotlib, PyXML, Unfortunately external modules that include compiled extensions are not compatible between .x releases of Python. So you will have to install them from scratch. You might want to check that all critical modules are available; 2.5 has been out for long enough that you shouldn't have much problem there. Pure-Python modules are easier, they can usually be copied over directly, for example a python module in your site-packages can be copied to the new site-packages. You might want to use easy_install to get the most recent versions of modules with easy_install support... Kent From kent37 at tds.net Thu Jun 12 00:38:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 18:38:55 -0400 Subject: [Tutor] Web Stats In-Reply-To: References: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> Message-ID: <1c2a2c590806111538o43370375ldfff984327bd5387@mail.gmail.com> On Wed, Jun 11, 2008 at 3:58 PM, Stephen Nelson-Smith wrote: > Hello, > >>> This has to include resources which have not been visited, as the >>> point is to clean out old stuff. Ah, I missed that part. >> Take a look at AWStats (not Python). > > Doesn't this 'only' parse weblogs? It parses them and displays the stats. But it is focused on presentation, probably not what you need. > I'd still need some kind of spider > to tell me all the possible resources available wouldn't I? It's a > big website, with 1000s of pages. I guess, unless you can figure it out from the backend somehow. For example if it's all static files you can walk the file system instead of the site. Kent From clazzt at arnet.com.ar Thu Jun 12 01:20:42 2008 From: clazzt at arnet.com.ar (claxo) Date: Wed, 11 Jun 2008 20:20:42 -0300 (Hora est. de Sudamérica E.) Subject: [Tutor] Subject: Re: it is ok that object.__init__ gets called multiple times? Message-ID: <20080611231812.CBB701E4005@bag.python.org> >> In the following code the __init__ for C would end calling two times object.__init__ . >> Is this ok or I calling for trouble ? >> To make explicit some context: >> object is the std python object >> super is not suposed to be used in any subclass >Why not? This seems to me the problem super is designed to solve. Googling super + new classes I found http://fuhm.net/super-harmful/ There it seems that super is not so simple to use, so I wanted to stay away. >OTOH why are you calling object.__init__() ? I don't think that is needed... >Kent I dont know what object may do in his __init__ method, so at least calling object.__init__(self) seems sensible. Also, the same page advises against not calling object.__init__. On the other side, today I have seen in another thread ( New Style Classes ) that wesley chun not pointed as erroneous some new class code that doenst call object.__init__. Im confused. From jeff at drinktomi.com Thu Jun 12 01:26:56 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 11 Jun 2008 16:26:56 -0700 Subject: [Tutor] when is object relational mapping for Python warranted? In-Reply-To: References: Message-ID: Yes, it's worth it. It makes it trivial to write simple database applications. The smaller the program, the more useful they are. Both SQLObject and SQLAlchemy have their strengths and weaknesses. SQLObject will get you and going up really fast. Its really simple to create a schema and to start working on a project. The most recent version is also acquiring a revision system. SQLAlchemy has a little more overhead, but it ultimately allows you to perform much more sophisticated operations. It also serves as a simpler DBI. My personal take is that SQLAchemy gives you much more growing room, and that this is well worth the initial investment. The documentation for SQLAlchemy tends to be better too. (That said I work primarily with SQLObject, and the addition of a revision system will keep me from switching our product to SQLAlchemy for a while longer.) - Jeff Younker - jeff at drinktomi.com - From john at fouhy.net Thu Jun 12 01:32:52 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 12 Jun 2008 11:32:52 +1200 Subject: [Tutor] Copy file as root In-Reply-To: <484f8853.05a4100a.506c.ffff96ca@mx.google.com> References: <484f8853.05a4100a.506c.ffff96ca@mx.google.com> Message-ID: <5e58f2e40806111632i70941ba8n44d5807fbdd1faaa@mail.gmail.com> On 11/06/2008, Timo wrote: > Hello, I'm writing a program in Python/pyGTK and I need to be root 2 > times. The first time is to open a file, let's say menu.lst. I use > os.system('gksudo gedit /boot/grub/menu.lst'), so that works. But what > if I have a copy of the file on my desktop? I use shutil.copyfile() to > copy the file from /boot/grub/ to /home/user/Desktop, but ofcourse need > to be root to copy it back. > So, how can I use shutil.copyfile() with gksudo to ask the password? Or > is the another good way to do this in Python? Presumably you could do os.system('gksudo cp /home/user/Desktop/menu.lst /boot/grub') ? -- John. From eike.welk at gmx.net Thu Jun 12 01:44:35 2008 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 12 Jun 2008 01:44:35 +0200 Subject: [Tutor] Controlling applications In-Reply-To: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> References: <333efb450806090851y3beae517i2034901e80499c5c@mail.gmail.com> Message-ID: <200806120144.35409.eike.welk@gmx.net> On Monday 09 June 2008 17:51, W W wrote: > Hi, > > I've done some cursory searches, and it doesn't appear that what I > want to do is popular, if it's even possible. > > I'm trying to control other applications via python (specifically > my web browser). > > My hope is there is some way to emulate a series of keypresses. My > goal is to have a script that will automatically retrieve my > banking information. Originally I was planning to use urllib to > post/retrieve the data, but as far as I can tell, the bank uses > several variables and some javascript to authenticate everything, > and it seems overly complicated to try and manually figure it all > out. > > Is there a way to utilize python to perform keypresses? And does > anyone know of a tutorial for such a thing? I'm running the most > recently updated Ubuntu 8.04. > > TIA, Wayne This discussion might be interesting for you: http://holovaty.com/blog/archive/2008/05/02/0136 HTH, Eike. From kent37 at tds.net Thu Jun 12 02:47:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Jun 2008 20:47:48 -0400 Subject: [Tutor] Subject: Re: it is ok that object.__init__ gets called multiple times? In-Reply-To: <20080611231812.CBB701E4005@bag.python.org> References: <20080611231812.CBB701E4005@bag.python.org> Message-ID: <1c2a2c590806111747l440f148ai430717b3437e72c5@mail.gmail.com> On Wed, Jun 11, 2008 at 7:20 PM, claxo wrote: >>OTOH why are you calling object.__init__() ? I don't think that is > needed... >Kent > > I dont know what object may do in his __init__ method, so at least calling > object.__init__(self) seems sensible. Also, the same page advises against > not calling object.__init__. What page is that? This thread has both points of view: http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-12/4599.html I think if you are using super() then your classes that inherit from object still need to call super().__init__(). If you are not using super I don't think it matters. Kent From bhaaluu at gmail.com Thu Jun 12 03:24:20 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 11 Jun 2008 21:24:20 -0400 Subject: [Tutor] wanting to learn In-Reply-To: <333efb450806110816l2ada2c46me594661445200341@mail.gmail.com> References: <333efb450806110816l2ada2c46me594661445200341@mail.gmail.com> Message-ID: On Wed, Jun 11, 2008 at 11:16 AM, W W wrote: > > However, my personal preference is using vi/vim (which you should have > built in on your mac, along with python). > > If you open a mac terminal window and type "vimtutor" at the prompt, > it should start the vim tutor program. There are many programmers > across various different programming languages and platforms that use > vi/vim as their ide. > > That's my personal recommendation, and at the very least you should > give a few different editors/IDEs a try to see which one fits your > style/comfort zone best. > > HTH, > Wayne I also use vim as an IDE for Python. vim == vi improved. Here is the (dot)vimrc (.vimrc) I use: " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set et set sw=4 set smarttab " set line number (added by bhaaluu) set nu " Bind key to running the python interpreter on the currently active " file. (courtesy of Steve Howell from email dated 1 Feb 2006). map :w\|!python % That turns on syntax highlighting, autoindenting, line numbers, and allows you to press the F2 function key to run your code from vim, then returns you to the editor afterwards. Use 'print' and 'raw_input()' to watch variables and establish breakpoints. vim is touch-typist friendly, so you can really go to town if you know it. 'vimtutor' is a good starting point if you're not familiar with it. You can do a lot with it, with just a handful of commands. Then add to those as you need them. Edit multiple files in multiple windows... whatever you want to do, and more! There are two modes in vim: normal and insert. will always get you into normal mode. 8^D Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From pine508 at hotmail.com Thu Jun 12 03:25:13 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 11 Jun 2008 21:25:13 -0400 Subject: [Tutor] wanting to learn In-Reply-To: References: Message-ID: Hi Michael, > Since my background is web, I want to learn Python and how it relates > to the web. I have been told that I need to learn and understand the > basics in "standard/general" Python before I move onto something like > "django" but really, how much Python do I need to know before I can > head down the web path? That's hard to quantify, and I myself don't have that experience yet, but from what I've been told, web programming in Python is not at all an easy thing to get started with and so you wouldn't want lack of basic Python knowledge to hinder you, especially when you'll be dealing with the ins and outs of the web framework, like Django. And so I'd guess you'd need to understand more than just the very basics of Python, but not a great deal beyond that. Trying to quantify it, there is probably a "top 50" (100?) ideas in programming that you should be familiar with, and so you'd want to learn how Python handles that top 50. In many ways Python is a great language to start with as it is very readable, sensible, and compact compared to others, from what I hear. For me, the most "aha!" thing to learn in programming was that you could name an action and that would then be a storage for the results of that action. For example (from wxPython): mytext = textControl.GetValue() now mytext will refer to the text which was got from the GetValue() action that the textControl does. I've mainly only encountered that kind of thinking in programming. Of course, there's also classes and attributes and all sorts of stuff, but one thing at a time. > Is Python a language a total beginner/tutorial reader like myself can > learn or do I need to take classes at a local college? Is their is > just too much to learn to do this on my own. I started learning Python on my own and although I am far from anything like a Programmer, have been able to make some applications and have fun with it. I've been goofing around with it for just under two years in my off time. It's been 100% without classes. Some books, but mainly websites, trial and error, reading this and other lists, etc. Without Google this would have not happened, I'm sure. It is amazing how Google can turn up old forum posts which completely answer my confusion of the moment. Or if not, I've gotten great help on this and other lists. > I am starting to get a bit over whelmed with all of the information I'm finding. That's not surprising, either. The key is to tune most of it out at first, and just pick a few good sources. There are some very good online tutorials, like... Alan Gauld's Learn to Program (great for conceptual basics, and he is a master tutor on this list) http://www.freenetpages.co.uk/hp/alan.gauld/ Frederik "eff-bot" Lundh's guide to the Standard Python Library (great for knowing what the Python standard library can do, which is so much of the power of the language) http://effbot.org/librarybook/ ShowMeDo has many excellent instructional webcasts and is very Python-centric. www.ShowMeDo.com I find the official Python tutorial to be usually not very good for beginners to programming, though (it's more for those coming from another language I feel). Back search this list's archives, too. Lots of good info already stamped into the internet. > So, can anybody head me in the right direction with my endeavor? > Since I am on an intel/Mac which IDE should I be using? Which one will > be robust enough to take me through my journey? I have started with > IDLE but I have been told that it is a bare bones IDE. So, if I need > to learn how to use a IDE, I want to learn one that I will not have to > discard as I become more familiar with the Python language. I wouldn't worry about discarding IDLE just yet; sometimes it is better to start simple, and I still fire up IDLE now and then for testing. I like using Boa Constructor as an IDE but that's also because I do GUI programming. I believe it works for Mac as well. There are tons of IDEs and people will all have their favorites. Best of luck, and take it little by little, Che _________________________________________________________________ Now you can invite friends from Facebook and other groups to join you on Windows Live? Messenger. Add now. https://www.invite2messenger.net/im/?source=TXT_EML_WLH_AddNow_Now -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at drinktomi.com Thu Jun 12 03:29:17 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 11 Jun 2008 18:29:17 -0700 Subject: [Tutor] Web Stats In-Reply-To: References: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> Message-ID: <7B9E3C8D-0BB2-41DA-97D0-AB2687A41D41@drinktomi.com> On Jun 11, 2008, at 12:58 PM, Stephen Nelson-Smith wrote: >> Take a look at AWStats (not Python). > > Doesn't this 'only' parse weblogs? I'd still need some kind of spider > to tell me all the possible resources available wouldn't I? It's a > big website, with 1000s of pages. If you have pages which are no longer referenced from any root pages then a spider won't find them. These dangling pages are precisely the sort of thing you're trying to remove. Consider other options such as looking through the filesystem. - Jeff Younker - jeff at drinktomi.com - From bhaaluu at gmail.com Thu Jun 12 03:33:49 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 11 Jun 2008 21:33:49 -0400 Subject: [Tutor] wanting to learn In-Reply-To: References: Message-ID: On Wed, Jun 11, 2008 at 10:48 AM, Michael yaV wrote: > So, can anybody head me in the right direction with my endeavor? I've read 'Programming Python Third Edition' by Mark Lutz. O'Reilly & Assoc., 2006. ISBN 0596009259. It has a lot of stuff about doing things with the Net in it. See if you can find a copy of it at a used-book store, or someplace like http://used.addall.com Just the chapters on using Tkinter (300+ pages) are worth it! The best Python Tutorial I've found (for me) is: Python Programming for the Absolute Beginner, Second Edition. Michael Dawson. ISBN: 1598631128 It is games oriented, but covers all the basics, quite thoroughly. If you can work through that one, you'll be able to tackle just about anything Python. Plus, it's a lot of fun to read and do. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From clazzt at arnet.com.ar Thu Jun 12 04:11:30 2008 From: clazzt at arnet.com.ar (claxo) Date: Wed, 11 Jun 2008 23:11:30 -0300 Subject: [Tutor] Subject: Re: it is ok that object.__init__ gets called multiple times? In-Reply-To: <1c2a2c590806111747l440f148ai430717b3437e72c5@mail.gmail.com> References: <20080611231812.CBB701E4005@bag.python.org> <1c2a2c590806111747l440f148ai430717b3437e72c5@mail.gmail.com> Message-ID: <20080612020843.8D2AB1E4010@bag.python.org> On Wed, 11 Jun 2008 20:47:48 -0400 Kent Johnson wrote: > This thread has both points of view: > http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-12/4599.html > > I think if you are using super() then your classes that inherit from > object still need to call super().__init__(). If you are not using > super I don't think it matters. > > Kent Yes, you are right. Thanks for the pointer Kent, the discussion there tells me the whys. From cspears2002 at yahoo.com Thu Jun 12 06:16:43 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 11 Jun 2008 21:16:43 -0700 (PDT) Subject: [Tutor] text editor for Windows? Message-ID: <15418.52012.qm@web51601.mail.re2.yahoo.com> I just got Python installed on my Dell laptop running Windows Vista Business. Can someone recommend a good text editor to use for Python programming? Some people seem to like PythonWin. In the past I have use ConText. Thanks! From marilyn at deliberate.com Thu Jun 12 07:14:19 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed, 11 Jun 2008 22:14:19 -0700 (PDT) Subject: [Tutor] [Fwd: Re: powerball] Message-ID: <50796.66.218.47.125.1213247659.squirrel@mail.tigertech.net> Hi Max and everyone, Max, your reply-to only went to me. You have to work harder to get it to go to the whole list. Anyway, my advice is to post your new program and see what people say. Marilyn ---------------------------- Original Message ---------------------------- Subject: Re: [Tutor] powerball From: "max baseman" Date: Wed, June 11, 2008 7:22 pm To: "Marilyn Davis" -------------------------------------------------------------------------- thank you for your help i beleave i have fixed this bug and made the script slightly shorter yet i seem to have run into another bug i cant find - the program now just eats my ram and doesn't seem to run correctly now it displays no output and nearly freezes my computer i'm still looking for the reason but if you have the time i would appreciate you advise - thanks On Jun 11, 2008, at 12:36 PM, Marilyn Davis wrote: > On Wed, June 11, 2008 9:58 am, max baseman wrote: > > Hi Max, > > Here's your code with the indents preserved. I'll make my comments > with >'s. > > from random import randrange > wins=0 > win=[] > count =0 > while count !=5: > >> To loop 5 times it is better to use: > >> for count in range(5): >> stuff you want to do > >> Then all the loop controlling happens in one place and it is hard to >> mess up. > > number=randrange(55)+1 > win.append(number) > count=count+1 > powerball=randrange(42)+1 > count=0 > win.sort() > while count !=146107962: > numbers=[] > count2=0 > while count2 !=5: > number=randrange(55)+1 > >> Yep, indeed, here you made the easy mistake of forgetting to + 1 to >> count2. So, it probably spun forever right there. > >> I also don't see that "count" is every changed, so that would be >> another >> spin. All these would go away by using 'for' 'in' and 'range'. > >> It looks like a fun program and a good start. > >> Marilyn Davis > > if number in win: > numbers.append(number) > else: > print "lose" > break > numbers.sort() > ball=randrange(42)+1 > if ball==powerball: > print "win" > print > print > print win, powerball > >> as a fun little project i scripted a powerball program. it seems >> to have a >> bug in it that i cant find. >> >> from random import randrange wins=0 win=[] count =0 while count !=5: >> number=randrange(55)+1 win.append(number) count=count+1 >> powerball=randrange(42)+1 count=0 win.sort() while count !=146107962: >> numbers=[] count2=0 while count2 !=5: number=randrange(55)+1 if >> number in >> win: >> numbers.append(number) else: >> print "lose" break numbers.sort() ball=randrange(42)+1 if >> ball==powerball: >> print "win" print print print win, powerball >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- A non-text attachment was scrubbed... Name: powerball.py Type: text/x-python-script Size: 555 bytes Desc: not available URL: From wescpy at gmail.com Thu Jun 12 08:33:10 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Jun 2008 23:33:10 -0700 Subject: [Tutor] Uniform 'for' behavior for strings and files In-Reply-To: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> References: <376fbdcf0806091426i1e3dda86gf4a8c8a4bd327600@mail.gmail.com> Message-ID: <78b3a9580806112333m469a7957i39a7ca51c5658c31@mail.gmail.com> > for item in block: > > where block is a file, then item becomes each line of the file in turn > But if block in a large string (let's say the actual text that was in > the file), item becomes each character at a time. Is there a way to > have a uniform iteration irrespective of whether block is a file or > string (ideally one \n-delimited line at a time)? i would definitely take Kent's and Alan's suggestions of using the str.splitlines() method whenever possible... (i think alan misspelled it as "split" but we know what he meant! ;-) their idea is to use isinstance() to tell the different between a file and a string, and if it's a file, it iterate over each line as usual, but for a large string, to break it up into a group of lines using str.splitlines(). another approach is to "turn that string into a file"-like object by using the StringIO.StringIO class. what that does is that it creates a file-like interface to a large string. once you have that object, then you can iterate over it like a normal file, even tho it's a string: import StringIO large = '''Line 1 Line 2 Line 3''' stringFile = StringIO.StringIO(large) for eachLine in stringFile: # process each line here. ie. print eachLine, # trailing ',' suppresses print's \n stringFile.close() # free the object there is also a faster version of this class written in C: cStringIO.StringIO. here are the module docs: http://docs.python.org/lib/module-StringIO.html http://docs.python.org/lib/module-cStringIO.html the advantage of doing it this way is that your code that iterates over a file can stay unchanged... you just create the StringIO object inside the if isinstance() clause. hope this helps! -- 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 ksterling at mindspring.com Thu Jun 12 09:12:16 2008 From: ksterling at mindspring.com (Ken Oliver) Date: Thu, 12 Jun 2008 03:12:16 -0400 (GMT-04:00) Subject: [Tutor] wanting to learn Message-ID: <12836596.1213254736570.JavaMail.root@mswamui-bichon.atl.sa.earthlink.net> >Don't be like most and put off the super timple tutorials. I had a lot >of fun (after reading the Core python books out there) with the kids >tutorial because it was just fun to play around and learn some python >/ work with some python in the process. Honestly I didn't learn >anything because the core books taught me everything but if your brain >is on information overload then start here: > >http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ This sounds interesting to me, but I have not been successful at downloading the text at the link above. The dreaded 404. Does anyone have the Windows version of the book or a suggestion as to where to download it? From rdm at rcblue.com Thu Jun 12 10:37:28 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 12 Jun 2008 01:37:28 -0700 Subject: [Tutor] Turtle Triangles Problem Message-ID: <20080612090610.D0CF91E4006@bag.python.org> An HTML attachment was scrubbed... URL: From timovwb at gmail.com Thu Jun 12 11:38:53 2008 From: timovwb at gmail.com (Timo) Date: Thu, 12 Jun 2008 11:38:53 +0200 Subject: [Tutor] Copy file as root In-Reply-To: <5e58f2e40806111632i70941ba8n44d5807fbdd1faaa@mail.gmail.com> References: <484f8853.05a4100a.506c.ffff96ca@mx.google.com> <5e58f2e40806111632i70941ba8n44d5807fbdd1faaa@mail.gmail.com> Message-ID: <4850ee99.1d624e0a.3635.49cf@mx.google.com> John Fouhy schreef: > On 11/06/2008, Timo wrote: > >> Hello, I'm writing a program in Python/pyGTK and I need to be root 2 >> times. The first time is to open a file, let's say menu.lst. I use >> os.system('gksudo gedit /boot/grub/menu.lst'), so that works. But what >> if I have a copy of the file on my desktop? I use shutil.copyfile() to >> copy the file from /boot/grub/ to /home/user/Desktop, but ofcourse need >> to be root to copy it back. >> So, how can I use shutil.copyfile() with gksudo to ask the password? Or >> is the another good way to do this in Python? >> > > Presumably you could do os.system('gksudo cp > /home/user/Desktop/menu.lst /boot/grub') ? > > Yep correct, but this isn't the "Python" way I think. Ah well, I'll use this as a solution for now and see if I find something else. From dos.fool at gmail.com Thu Jun 12 06:42:44 2008 From: dos.fool at gmail.com (max baseman) Date: Wed, 11 Jun 2008 22:42:44 -0600 Subject: [Tutor] powerball Message-ID: <4A9342B4-5A21-409E-82B0-4FA8FC5C903F@gmail.com> hello and thank you everyone for your help. I apologize for my ignorance when it came to knowledge of what the powerball is it is not as wide spread as i had thought it was the powerball is a form of lottery their are 5 numbers between 1 and 55, and then their is the powerball between 1 and 42 players win different amounts of money depending on how many numbers they had right the program i wrote uses the number 146107962 as the amount of tickets in play i found this number on the powerball stat as the probability of getting jackpot 1 / 146107962 included is the finished and working script if anyone would like to use or play with it. -------------- next part -------------- A non-text attachment was scrubbed... Name: powerball.py Type: text/x-python-script Size: 922 bytes Desc: not available URL: -------------- next part -------------- seeing as i have left the python mailing list in the past any comments or ideas would be appreciated if sent to this email - thank you From kent37 at tds.net Thu Jun 12 11:50:43 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Jun 2008 05:50:43 -0400 Subject: [Tutor] text editor for Windows? In-Reply-To: <15418.52012.qm@web51601.mail.re2.yahoo.com> References: <15418.52012.qm@web51601.mail.re2.yahoo.com> Message-ID: <1c2a2c590806120250x2f54f5ech271e84b9c6d0b07d@mail.gmail.com> On Thu, Jun 12, 2008 at 12:16 AM, Christopher Spears wrote: > I just got Python installed on my Dell laptop running Windows Vista Business. Can someone recommend a good text editor to use for Python programming? Some people seem to like PythonWin. In the past I have use ConText. This is a highly personal choice and there are many good options: http://wiki.python.org/moin/PythonEditors Personally I use TextPad. Kent From rdm at rcblue.com Thu Jun 12 12:38:44 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 12 Jun 2008 03:38:44 -0700 Subject: [Tutor] Turtle Triangles Problem In-Reply-To: <6faf39c90806120304w22490a5o9703838727ffc694@mail.gmail.com > References: <20080612090610.D0CF91E4006@bag.python.org> <6faf39c90806120304w22490a5o9703838727ffc694@mail.gmail.com> Message-ID: <20080612103856.67CA91E401A@bag.python.org> At 03:04 AM 6/12/2008, Andre Engels wrote: >Content-Transfer-Encoding: 7bit >Content-Disposition: inline > >2008/6/12 Dick Moores : > > The code is at > > < http://py77.python.pastebin.com/f3b6a6f3> > > > > The problem is shown at < > > http://www.rcblue.com/images/Turtle_Triangle_Problem.jpg>. > > > > I'd very much like to get rid of that last line, in this example the > > purple(?) one that heads northwest from the same-colored triangle. It's at > > this point that the script pauses for 3 seconds to show off what it's > > created. I'd like it to show only triangles. > > > > On cursory inspection you might think that the solution is simple: remove > > lines 86-87. But in fact, without these 2 lines a cycle ends with 2 extra > > lines (2 sides of an unfinished triangle). > > > > Anyone see a solution? > >I have been playing around a bit, and if you remove line 86, but leave >line 87 in, it seems to work as you intend. YES! Thanks very much! Dick From rdm at rcblue.com Thu Jun 12 12:41:30 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 12 Jun 2008 03:41:30 -0700 Subject: [Tutor] How to get a script to open a text file with Python? In-Reply-To: <8e087c6d0806110650o13c9a34ob96337608bd80655@mail.gmail.com > References: <8e087c6d0806110650o13c9a34ob96337608bd80655@mail.gmail.com> Message-ID: <20080612104142.72BAD1E4006@bag.python.org> An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Thu Jun 12 13:47:30 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 12 Jun 2008 07:47:30 -0400 Subject: [Tutor] wanting to learn In-Reply-To: <12836596.1213254736570.JavaMail.root@mswamui-bichon.atl.sa.earthlink.net> References: <12836596.1213254736570.JavaMail.root@mswamui-bichon.atl.sa.earthlink.net> Message-ID: On Thu, Jun 12, 2008 at 3:12 AM, Ken Oliver wrote: > >>http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ > > This sounds interesting to me, but I have not been successful at downloading the text at the link above. The dreaded 404. Does anyone have the Windows version of the book or a suggestion as to where to download it? > _______________________________________________ Try this link: http://www.briggs.net.nz/log/wp-content/uploads/2007/09/swfk.zip Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From qsqgeekyogdty at tiscali.co.uk Thu Jun 12 13:56:41 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 12 Jun 2008 12:56:41 +0100 (GMT+01:00) Subject: [Tutor] Dictionary within a dictionary Message-ID: <6508272.1213271801192.JavaMail.root@ps25> Hi, I would like to understand how to generate dictionaries based on other dictionaries. For example, I have a 3 tables in ym SQL database - Groups, Categories and Sub-categories with a one-to-many relations between each. I am presuming that each of these tables is one of my dictionaries?!?! What I don't understand is how to write this SQL statement in python code: SELECT id, category from Categories WHERE group_id = "1"; Can some one help me understand how to pass the group_id in a simple example, so that I can return all the categories from Category table. I am using the SQL example to figure it out in my head - perhaps this is a wrong way to look at this? Thanks David ______________________________________________________ New Online ID Theft Protection - http://www.tiscali.co.uk/spyguard From nicole4real4eva at yahoo.com Thu Jun 12 17:32:41 2008 From: nicole4real4eva at yahoo.com (Nkem Onyemachi) Date: Thu, 12 Jun 2008 08:32:41 -0700 (PDT) Subject: [Tutor] New to Python Message-ID: <720381.69418.qm@web51010.mail.re2.yahoo.com> Hi all im new to programming so i decided 2 learn Python since it is easy to learn on ones own what really is the advantage can i know it is not "heavy" like java etc but really can it do apart 4rom being as a scripting language _____________________________ Sent from my phone using flurry - Get free mobile email and news at: http://www.flurry.com From nicole4real4eva at yahoo.com Thu Jun 12 17:32:41 2008 From: nicole4real4eva at yahoo.com (Nkem Onyemachi) Date: Thu, 12 Jun 2008 08:32:41 -0700 (PDT) Subject: [Tutor] New to Python Message-ID: <720381.69418.qm@web51010.mail.re2.yahoo.com> Hi all im new to programming so i decided 2 learn Python since it is easy to learn on ones own what really is the advantage can i know it is not "heavy" like java etc but really can it do apart 4rom being as a scripting language _____________________________ Sent from my phone using flurry - Get free mobile email and news at: http://www.flurry.com From bgailer at gmail.com Thu Jun 12 18:43:25 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 12 Jun 2008 12:43:25 -0400 Subject: [Tutor] New to Python In-Reply-To: <720381.69418.qm@web51010.mail.re2.yahoo.com> References: <720381.69418.qm@web51010.mail.re2.yahoo.com> Message-ID: <4851522D.6050206@gmail.com> Nkem Onyemachi wrote: > Hi all im new to programming so i decided 2 learn Python since it is easy to learn on ones own what really is the advantage can i know it is not "heavy" like java etc but really can it do apart 4rom being as a scripting language > Hi and welcome. As an aside I'd find your requests easier to read with a little punctuation and capitalization. For one I can parse your comment several different ways, and they reveal different questions. (1) Python is a "general purpose" programming language. This puts it in a very large set of languages. (2) Python is an interpreted language. These are a subset of programming languages. (Jave, VB, Basic, APL, ....) The others are compiled languages (C, FORTRAN, COBOL, ....) Interpreted languages execute somewhat slower than compiled languages. But development turnaround time is usually a LOT shorter. (3) Python is "lighter" than Java (and C, C++, VB, most other languages) (4) Python comes with a large library of modules that support almost anything you'd want to accomplish. HTH -- Bob Gailer 919-636-4239 Chapel Hill, NC From marilyn at deliberate.com Thu Jun 12 19:12:20 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu, 12 Jun 2008 10:12:20 -0700 (PDT) Subject: [Tutor] powerball In-Reply-To: <4A9342B4-5A21-409E-82B0-4FA8FC5C903F@gmail.com> References: <4A9342B4-5A21-409E-82B0-4FA8FC5C903F@gmail.com> Message-ID: <60396.66.218.47.125.1213290740.squirrel@mail.tigertech.net> On Wed, June 11, 2008 9:42 pm, max baseman wrote: > hello and thank you everyone for your help. I apologize for my ignorance > when it came to knowledge of what the powerball is it is not as wide > spread as i had thought it was > > the powerball is a form of lottery their are 5 numbers between 1 and 55, > and then their is the powerball between 1 and 42 players win different > amounts of money depending on how many numbers they had right the program > i wrote uses the number 146107962 as the amount of tickets in play i > found this number on the powerball stat as the probability of getting > jackpot 1 / 146107962 included is the finished and working script if > anyone would like to use or play with it. > Hi Max, The program looks great. You're getting real pythonic. Since you posted it, I'll add some comments to help you spiff it up and make it faster. Again, I'll use the > for comments: from random import randrange # for creating random numbers wins=0 # to see how many people would win win=[] # the winning numbers go here count=0 > You don't need count=0. Python sets the whole thing up for you > with just that "for": for count in range(5): # powerball uses 5 numbers win.append(randrange(55)+1) powerball=randrange(42)+1 count=0 while count != 146107962: # point of information useing for count in range(146107962) will overlaoad with this large a number > Then you might like xrange(big_number). It generates the numbers, > one at a time. numbers=[] # guesses count2=0 for count2 in range(5): number=randrange(55)+1 > With randrange, you can get duplicates. You can get > [23, 2, 14, 23, 2] which I'm guessing can't > happen in a real powerball game. (I don't know powerball either.) > You might like the sample() function in the random library. if number in win: # if the number is in the winning numbers continue numbers.append(number) else: print "lose" # else quite while ahead break > There you went to the next player. It's a good place > for a comment. numbers.sort() > You don't seem to need those numbers sorted. win.sort() > Since win is not changing, you might want to sort it only once, > back when you made that list. ball=randrange(42)+1 #picks the powerball if ball == powerball: print "win" wins=wins+1 > else? it's quiet. count=count+1 print print wins,"winners with", win, powerball > What happens wrong? I didn't run it? Does it just fall quiet for a > while? You might try putting in some extra print statements to see > what is exactly happening. > Are you a student? What grade? > > > seeing as i have left the python mailing list in the past any comments or > ideas would be appreciated if sent to this email - thank you > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Jun 12 21:17:26 2008 From: carroll at tjc.com (Terry Carroll) Date: Thu, 12 Jun 2008 12:17:26 -0700 (PDT) Subject: [Tutor] do I need f.close() In-Reply-To: Message-ID: On Wed, 11 Jun 2008, dave selby wrote: > The whole topic came up because I just finished reading 'learning > python' 3rd edition OReilly as a refresher where there are multiple > instances of suggesting that you do the exact opposite eg ... > > [line.rstrip() for line in open('myfile')] ... p361 > for line in open('script1.py') ... p261& p276 where it is described as > 'best practice' for reading files line by line > etc ... But that's for use of an input file. The question was about writing. I wouldn't worry too much about closing file that was used as input, as I am about one for output, where you want to be careful that the file contents are left in a particular desired state. From gslindstrom at gmail.com Thu Jun 12 22:44:57 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 12 Jun 2008 15:44:57 -0500 Subject: [Tutor] Pinging a service Message-ID: Hello, I would like to write a routine to monitor services running on a remote box. My initial thought is to "ping" the remote box to monitor latency and then execute a query on the remote machine to monitor the database. What I would like is to gather data points and graph the delay to see if there are any patterns; A) Is this a sound strategy? B) Are there libraries for the "ping"ing aspect? If not, I can execute the ping using "command"...how can I capture the screen output to get the times? Thanks, --greg From alan.gauld at btinternet.com Fri Jun 13 01:27:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 00:27:12 +0100 Subject: [Tutor] IDE References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com><448C05BE-131B-432F-9A47-C9FB601479A0@drinktomi.com> Message-ID: "Tom" wrote > Does anyone know which of the IDE's mentioned above have a similar > feature. (I'm on Vista,sorry!) Most will do it one way or another. We mentioned filtering the buiffer in vim, emacs has a shell bvuffer facility in which you can start python, other use the IDLE/Pythonwin approach of a dedicated buffer. Eclipse/PyDev is one that I have not found a way of getting a >>> prompt in the IDE itself. But I suspect thats my inexperience of Eclipse because I find it surprising that such a wiely used IDE doesn't have OS access as standard. Alan G From alan.gauld at btinternet.com Fri Jun 13 01:32:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 00:32:16 +0100 Subject: [Tutor] do I need f.close() References: Message-ID: "dave selby" wrote > The whole topic came up because I just finished reading 'learning > python' 3rd edition OReilly as a refresher where there are multiple > instances of suggesting that you do the exact opposite eg ... LP is a tutorial book so does not always teach industry strength programming practice (in common with most tutorials!) > [line.rstrip() for line in open('myfile')] ... p361 > for line in open('script1.py') ... p261& p276 where it is described > as > 'best practice' for reading files line by line Its the common idiom and for reading files not too bad. I certainly use this sometimes but if its critical I will move the open outside the loop: f = open(...) for line in f:.... or [line.rstrip() for line in f] But thats just so that I can detect and correct missing files if necessary etc. Its not becauise of closure issues. I'm fairly happy about letting the os close read only files, its really for writing that you want to be explicit. Alan G. From marilyn at deliberate.com Fri Jun 13 01:39:04 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu, 12 Jun 2008 16:39:04 -0700 (PDT) Subject: [Tutor] do I need f.close() In-Reply-To: References: Message-ID: <1550.66.218.47.142.1213313944.squirrel@mail.tigertech.net> On Thu, June 12, 2008 4:32 pm, Alan Gauld wrote: > "dave selby" wrote > > >> The whole topic came up because I just finished reading 'learning >> python' 3rd edition OReilly as a refresher where there are multiple >> instances of suggesting that you do the exact opposite eg ... > > LP is a tutorial book so does not always teach industry strength > programming practice (in common with most tutorials!) > >> [line.rstrip() for line in open('myfile')] ... p361 >> for line in open('script1.py') ... p261& p276 where it is described as >> 'best practice' for reading files line by line >> > > Its the common idiom and for reading files not too bad. > I certainly use this sometimes but if its critical I will move > the open outside the loop: > > f = open(...) for line in f:.... > > or > > [line.rstrip() for line in f] > > > But thats just so that I can detect and correct missing > files if necessary etc. Its not becauise of closure issues. I'm fairly > happy about letting the os close read only files, its really for writing > that you want to be explicit. Alan, will the file close, even if it was opened for writing, when the program ends? I know it stays open if you're interactive, but otherwise too? Marilyn Davis > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Jun 13 01:48:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 00:48:54 +0100 Subject: [Tutor] static methods and class methods References: <120286.49155.qm@web51601.mail.re2.yahoo.com> <1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> Message-ID: "Kent Johnson" wrote> > I am still unsure of the difference of static and class methods. You are not alone, it is confusing! > A class method receives the class it was called on as the first > argument. This can be useful with subclasses. A staticmethod doesn't > get a a class or instance argument. It is just a way to put a plain > function into the scope of a class. And that's the definition of the difference in Python. In the wider world of OOP they are two names for the same concept. Smalltalk and Lisp etc used the term "class method" to mean a method that applied to the class as a whole. C++ introduced the term "static method" to reflect the fact that it was loaded in the static area of memory(*) and thus could be called wiothout instantiating an object. This meant it could effectively be used as a class method. [(*) In C it is possible to prefix a normal function definition with the word static to get the compiler to load the fiunction into static memory - this often gives a performance improvement.] Python started off implementing "static methods" then later developed the sligtly more powerfull and flexible "class methods" and rather than lose backward compatibility called them classmethod. So in Python we have two ways of doing more or less the same (conceptual) thing. > Both of these are rarely used; I don't think I have ever written a > class method in live code. I have used staticmethods as a convenient > way to put a function into a class namespace. In contrast most of my major projects have used class methods in some way or other. Often in conjunction with factory classes or as factory methods, but also as a persistence mechanism, a streaming mechanism or as a database access technique. (In Python there are so many good ORMs that the latter use is rarely necessary, but in other languages it can be an easy way of instantiating objects stored in a database.) They are also very powerful tools for writing OOP based MIS systems where you tend to be collecting information at the class level as well as the object level. But I think they are a bit like metaclasses, if you are not used to having them you tend to find other ways of doing the job. They are rarely essential, just sometimes a convenient shortcut. And class methods are often used in conjunction with meta-classes -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jun 13 02:02:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 01:02:11 +0100 Subject: [Tutor] wanting to learn References: Message-ID: "Michael yaV" wrote > person. I have taught myself HTML and flash by reading manuals and a > lot of trial and error over the last 11 years. I have always wanted > to learn a language like php, asp, .net but I never took the time > to learn them. I have recently found Python and believe this is > the language that I will "hang-my-hat-on" and learn. Thats a good choice. Python is one of the easiest languages to learn. > "django" but really, how much Python do I need to know before I can > head down the web path? You need to know about: data types and structures (numbers, strings, lists, dictionaries etc) sequences loops branches functions and for Django, one more advanced topic: OOP, although at a fairly basic level. This can all be picked up in a week doing 2 hours or so per day. > Is Python a language a total beginner/tutorial reader like myself > can learn or do I need to take classes at a local college? Python is easy to learn and there are lots of tutorials for absolute beginners listed on the non programmers section of the python site. I try not to push my own tutor too often but it is well suited to you since it also teaches basic JavaScript which you definitely should learn for web apps too. (Python can't do browser side scripting) > just too much to learn to do this on my own. I am starting to get a > bit over whelmed with all of the information I'm finding. There is a lot of concepts and jargon. In my tutor I try quite hard to explain all terms as I first use them and highlight jargon terms on first use. I also have a couple of concept topics before getting onto the hands-on stuff, and I recommend that you do take the half hour to read them if you decide to do my tutor. (And of course I am online to answer questions :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jun 13 02:13:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 01:13:44 +0100 Subject: [Tutor] New to Python References: <720381.69418.qm@web51010.mail.re2.yahoo.com> Message-ID: "Nkem Onyemachi" wrote > Hi all im new to programming so i decided 2 learn Python > since it is easy to learn on ones own True. > what really is the advantage > can i know it is not "heavy" like java etc If by heavy you mean fully featured then one could argue that Python was at least as "heavy" as Java. It can certainly do many things that Java cannot:- non OOP programming, multiple inheritance, functional programming etc. > but really can it do apart 4rom being as a scripting language Again that rather depends on your definition of a "scripting language". If you mean a language used to glue together other programs, then Python can do much more than that. It is a full programming language in its own right and many applications can be found that are written entirely in Python. Other appliations use Python as a configuration or scripting language internally. There are some application areas - like writing device drivers and operating systems - where Python is not well suited. But most areas can be handled in Python. For more info try searching sourceforge for projects using python and look at the advocacy section of the python web site! HTH, Alan G. From alan.gauld at btinternet.com Fri Jun 13 02:16:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 01:16:40 +0100 Subject: [Tutor] Pinging a service References: Message-ID: "Greg Lindstrom" wrote > A) Is this a sound strategy? Yes provided you keep the poll period sensible - say once per minute at the most Otherwise your pings become a significant overhead in themselves! > B) Are there libraries for the "ping"ing aspect? If not, I can > execute the ping using "command"...how can I capture the screen > output > to get the times? You can use sockets to send raw ICMP messages but using standard ping via the os is ok for this. Use the subprocess module and Popen object to get the outpurt from the command. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Jun 13 02:24:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Jun 2008 20:24:38 -0400 Subject: [Tutor] static methods and class methods In-Reply-To: References: <120286.49155.qm@web51601.mail.re2.yahoo.com> <1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> Message-ID: <1c2a2c590806121724q611456f1yefb8ebe54399b165@mail.gmail.com> On Thu, Jun 12, 2008 at 7:48 PM, Alan Gauld wrote: > "Kent Johnson" wrote> > >> I am still unsure of the difference of static and class methods. No, that wasn't me, it was Christopher Spears. > > You are not alone, it is confusing! > >> A class method receives the class it was called on as the first >> argument. This can be useful with subclasses. A staticmethod doesn't >> get a a class or instance argument. It is just a way to put a plain >> function into the scope of a class. > > And that's the definition of the difference in Python. Yes, that is what I said :-) > Python started off implementing "static methods" then later > developed the sligtly more powerfull and flexible "class methods" and > rather than lose backward compatibility called them classmethod. Are you sure? They were both introduced in Python 2.2 with new-style classes: http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html PEP 252 has an entire section on Static methods and class methods: http://www.python.org/dev/peps/pep-0252/ > So in Python we have two ways of doing more or less the same > (conceptual) thing. ?? But they are not the same thing. > In contrast most of my major projects have used class methods > in some way or other. Often in conjunction with factory classes or > as factory methods, but also as a persistence mechanism, a > streaming mechanism or as a database access technique. I would be interested in an example if you care to share. I have used, or can imagine using, static methods that way but not class methods. Kent From alan.gauld at btinternet.com Fri Jun 13 02:32:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 01:32:11 +0100 Subject: [Tutor] Dictionary within a dictionary References: <6508272.1213271801192.JavaMail.root@ps25> Message-ID: wrote > I am presuming that each of these tables is one of my > dictionaries?!?! > What I don't understand is how to write this SQL statement in python > code: > > SELECT id, category from Categories WHERE group_id = "1"; SQL is designed(and optimised) for doing complex data queries. If you are doingcomplex queries the best and fastest solution will almost certainly be to use SQL from Python rather than trying to build your own database using nested dictionaries and queries. Pythons dbapi can interface to most available database packages. If you don't already have one Python 2.5 comes with SqlLite in the standard library, which is basic but effective for small projects! > Can some one help me understand how to pass the group_id in a simple > example, so that I can return all the categories from Category > table. This is possibly but messy. # items = {group: [(name,category)....]} items = {1 : [('foo', 'hero'), ('bar','villian')], 2: [(darth', 'villian'), ('luke', 'hero'),('han','hero')]} result = [(item[1],item[0]) for item in items[1]] is equivalent to saying SELECT category,name from items where group = 1 But you need to design your data structure carefully to keep the query as simple as that. > I am using the SQL example to figure it out in my head - perhaps > this > is a wrong way to look at this? On the contrary, SQL is almost certainly the best way, not only to think about it, but to implement it! Use the right tool for the job. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jun 13 02:37:33 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 01:37:33 +0100 Subject: [Tutor] do I need f.close() References: <1550.66.218.47.142.1213313944.squirrel@mail.tigertech.net> Message-ID: "Marilyn Davis" wrote >> happy about letting the os close read only files, its really for >> writing >> that you want to be explicit. > > Alan, will the file close, even if it was opened for writing, when > the > program ends? I know it stays open if you're interactive, but > otherwise > too? It will if python closes cleanly. If the os, shell or python session suffer any mishap then the file might not be closed and data may be lost. There are other dangers too with not closing writeable files. If we have a long program we may inadvertantly reuse the name and open a new file without having closed the old one. That can result in unpredictable errors. In the worst case it could lose/overwrite the entire original file. This can, in theory, affect readable files too but it much less likely. The best thing nowadays is to use the new with construct since it guarantees file closure. Or in older versions always wrap file handling code in a try/fuinally block with the closes in the finally block. Alan G. From alan.gauld at btinternet.com Fri Jun 13 03:03:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jun 2008 02:03:40 +0100 Subject: [Tutor] static methods and class methods References: <120286.49155.qm@web51601.mail.re2.yahoo.com><1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> <1c2a2c590806121724q611456f1yefb8ebe54399b165@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590806121724q611456f1yefb8ebe54399b165 at mail.gmail.com... > On Thu, Jun 12, 2008 at 7:48 PM, Alan Gauld > wrote: >> "Kent Johnson" wrote> >> >>> I am still unsure of the difference of static and class methods. > > No, that wasn't me, it was Christopher Spears. Sorry Kent, I got my header editing a bit mixed up. >> Python started off implementing "static methods" then later >> developed the sligtly more powerfull and flexible "class methods" >> and >> rather than lose backward compatibility called them classmethod. > > Are you sure? They were both introduced in Python 2.2 with new-style > classes: > http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html Yes, but I'm fairkly sure I read an article by guido in a magazine or maybe the O'Reilly blogsite that they came up with the classmethod idea after they had already done the staticmethod stuff so they kept both. But I may be hallucinating again! :-) >> So in Python we have two ways of doing more or less the same >> (conceptual) thing. > > ?? But they are not the same thing. Conceptually they are both ways of defining a method that applies at the class level and could be used to implement class wide behavior. Thats what I mean. If you want to build a method to determine how many instances are active at any time then you could use either a staticmethod or a classmethod to do it. Most languages only give you one way. Python, despite its mantra, actually gives 2 ways to do it in this case. >> In contrast most of my major projects have used class methods > I would be interested in an example if you care to share. I have > used, > or can imagine using, static methods that way but not class methods. Notice the space. I mean "class methods" in the OOP sense not specifically classmethods in the Python sense. I have never found anything in Python that I needed a classmethod rather than a staticmethod, although if I were writing dynamic AI type stuff I suspect I could find examples. But in almost any major project I will have a use for class based methods One specific example of how I've used classmethods in a networked client/server app was where we had a GUI client talking to a server. Both GUI and server used the same class interaces but the GUI implementation of the interface was just a pass through to the server. When the GUI messages reached the server a listener picked the message from a socket, decoded the target class and invoked a getInstance() class method. The class method extracted the instance ID from the message. If the object was in memory (an object pool) it called the requested method on the instance and returned the response to the GUI. If the instance was not in memory but an instanceID was provided it fetched the instance from the database and returned the called method response. If no ID was given it created a new instance, saved it to the database and then called the method on the new instance. If the message was a query then it was performed by another class method which just ran a SELECT on the underlying database tables. Its pretty obvious that the class methods here were non trivial. We also had garbage collection and pool management class methods too. We had about 100 data classes like this with the core functionality in a super DBClass' class methods which were in turn called by each subclass' class methods along with their individual attribute wrappers. To add to the interest the data was stored in multiple databases on different boxes around the globe, so the class methods also had to figure out which database instance to talk to when fetching or writing objects... Needless to say this was before the days or Object databases and ORMs! But the final system managed millions of objects with thousands of users in around a dozen countries, and did so for many years. (And all in C++ :-) Hope that makes sense! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From emmanuel.ruellan at laposte.net Fri Jun 13 03:46:19 2008 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Fri, 13 Jun 2008 03:46:19 +0200 Subject: [Tutor] Unicode and fonts in Idle and Tkinter Message-ID: <7296745c0806121846j3e8cc5bdub4ae75efcc03910@mail.gmail.com> Hi all, I'd like to display symbols from the international phonetic alphabet (IPA) in a Tkinter window, but I do not manage to have them displayed correctly, neither in a Tkinter window nor in Idle. For example, I'd like to print the following string and get the result below: *string* my_text = u"""schwa: \N{latin small letter schwa} open e: \N{LATIN SMALL LETTER OPEN E} greek epsilon: \N{greek small letter epsilon} retroflex d: \N{LATIN SMALL LETTER D WITH TAIL} rhotacized schwa: \N{LATIN SMALL LETTER SCHWA WITH HOOK} voiced lateral fricative: \N{LATIN SMALL LETTER LEZH} low central unrounded vowel: \N{LATIN SMALL LETTER TURNED A}""" *expected result* schwa: ? open e: ? greek epsilon: ? retroflex d: ? rhotacized scwha: ? voiced lateral fricative: ? low central unrounded vowel: ? I'm getting the expected result when I execute a script from the shell, but in Idle (with font Times) and in a Tkinter window, I'm getting this instead: schwa: ? open e: \u025b greek epsilon: ? retroflex d: \u0256 rhotacized scwha: \u025a voiced lateral fricative: \u026e low central unrounded vowel: ? Some symbols get replaced by "\u02XX". Note that the IPA open e and the Greek epsilon actually have the same shape (glyph?) but the latter gets displayed correctly in Idle why the former doesn't. It may be just a font problem: when I try and change the font in Idle, the result is different. That is, things are getting worse, not better than with Times... Can you advise on a font that works well for Unicode (more specifically, IPA symbols) with Tkinter? preferably on both Windows and Linux. BTW, how come I do not have the same set of fonts available for Idle and for the shell? I'm using Ubuntu (Hardy). My locale is utf-8. For the shell, I'm using the Gnome terminal. Emmanuel Ruellan From wescpy at gmail.com Fri Jun 13 08:10:30 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 12 Jun 2008 23:10:30 -0700 Subject: [Tutor] static methods and class methods In-Reply-To: <1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> References: <120286.49155.qm@web51601.mail.re2.yahoo.com> <1c2a2c590806110430o7a0f9fe4i21d5bf76d8ff1bd9@mail.gmail.com> Message-ID: <78b3a9580806122310p156bd04egb25293d6a4cbbb81@mail.gmail.com> [static methods, class methods] > Both of these are rarely used; I don't think I have ever written a > class method in live code. I have used staticmethods as a convenient > way to put a function into a class namespace. this is someone out of the flow of the current thread now, but i forgot to mention in my previous post that, like kent, i too, have not used either of these much in practice on the past 11yrs of full-time Python development. class methods: the only time i've ever done a class method is when subclassing an immutable type, i.e., __new__() is a cls method, but that was for the book. i've never done one in practice. static methods: may have done 1 or 2 since they came out in 2.2, but in reality, if general code, they stay as global functions. if i really "want a function defined in a class definition, i may make one. but in practice, i often find that the functions that are most suitable as static methods end up being just *inner* functions defined inside a (regular) method. just my $0.02, -- 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 wayn0.ml at gmail.com Fri Jun 13 08:40:02 2008 From: wayn0.ml at gmail.com (Wayne Oliver) Date: Fri, 13 Jun 2008 08:40:02 +0200 Subject: [Tutor] IDE In-Reply-To: References: <55A9806A-0361-449E-88CE-3D4FE7E4A006@snovak.com><448C05BE-131B-432F-9A47-C9FB601479A0@drinktomi.com> Message-ID: <48521642.4030203@gmail.com> Alan Gauld wrote: > > "Tom" wrote >> Does anyone know which of the IDE's mentioned above have a similar >> feature. (I'm on Vista,sorry!) > > Most will do it one way or another. > > We mentioned filtering the buiffer in vim, emacs has a shell bvuffer > facility in which you can start python, other use the IDLE/Pythonwin > approach of a dedicated buffer. > > Eclipse/PyDev is one that I have not found a way of getting a >>> > prompt in the IDE itself. But I suspect thats my inexperience of > Eclipse because I find it surprising that such a wiely used IDE > doesn't have OS access as standard. > > Alan G Eric4 should work on windows, it does everything I need. YMMV -- Wayn0 From mail at timgolden.me.uk Fri Jun 13 10:18:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Jun 2008 09:18:52 +0100 Subject: [Tutor] Pinging a service In-Reply-To: References: Message-ID: <48522D6C.9000303@timgolden.me.uk> Greg Lindstrom wrote: > Hello, > > I would like to write a routine to monitor services running on a > remote box. My initial thought is to "ping" the remote box to monitor > latency and then execute a query on the remote machine to monitor the > database. What I would like is to gather data points and graph the > delay to see if there are any patterns; > > A) Is this a sound strategy? > > B) Are there libraries for the "ping"ing aspect? If not, I can > execute the ping using "command"...how can I capture the screen output > to get the times? Pinging is actually a more complex beast than you might imagine. If you know what ports the services are running on, or at least if you know one service a box *should* be running, you could do worse than to attempt a socket connection to that port number. For example, seeing if a (not desperately secured) Windows box is up is a question of attempting a connection on port 445. Likewise, seeing if a web server (box) is running, you can try port 80. etc. TJG From kent37 at tds.net Fri Jun 13 13:03:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Jun 2008 07:03:17 -0400 Subject: [Tutor] Dictionary within a dictionary In-Reply-To: <6508272.1213271801192.JavaMail.root@ps25> References: <6508272.1213271801192.JavaMail.root@ps25> Message-ID: <1c2a2c590806130403i7a983b57n626492000917048@mail.gmail.com> On Thu, Jun 12, 2008 at 7:56 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hi, > I would like to understand how to generate dictionaries based on other > dictionaries. For example, I have a 3 tables in ym SQL database - > Groups, Categories and Sub-categories with a one-to-many relations > between each. Can you say more about what you are trying to do, and what the tables contain? Kent From qsqgeekyogdty at tiscali.co.uk Fri Jun 13 16:23:06 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Fri, 13 Jun 2008 15:23:06 +0100 (GMT+01:00) Subject: [Tutor] Dictionary within a dictionary Message-ID: <20076062.1213366986098.JavaMail.root@ps36.mc.tiscali.sys> Hi, Following Alan's post, what I was trying to do is to understand how I can return the sub-item within the same space, if it makes sense ;) For example, in my 3 one-to-many lists, I want to generate this list: [{'id': , 'category': [{'id': , 'sub-category': [ {'id': , 'title': , 'is_selected': } ...] 'title': , 'is_selected': } ...] 'title': , 'is_selected': , } ...] Reason for this is that I want to create a navigational menu for a web template so that when you click on group_id the value is sent and this pulls the 'categories' and when you click on the category then the sub- categories are listed. Thanks David __________________________________________________________ Find out what Tiscali can do for you - http://www.tiscali.co.uk/services From malexiuk at gmail.com Fri Jun 13 16:28:15 2008 From: malexiuk at gmail.com (Mark Alexiuk) Date: Fri, 13 Jun 2008 09:28:15 -0500 Subject: [Tutor] ooffice UNO to generate automatic powerpoint presentations Message-ID: Hi, I want to be able to generate Windows powerpoint presentations by throwing text and images into a directory and running a Python script. I've seen some win32 modules online that manipulate powerpoint using COM but are not quite what I am looking for. Examples I've found http://mail.python.org/pipermail/python-win32/2006-March/004380.html http://www.activeinterface.com/b2003_4_12.html http://www.robertgsmith.com/2006/03/tech-tools-just-for-realtors-powerpoint-creation-script-for-cmabuyer-tour-etc.aspx Ideally, a file containing name=value pairs or XML would add title, text, and images. Has anyone done this with openoffice UNO? Thanks for your comments, Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlangford.cs03 at gtalumni.org Fri Jun 13 17:23:27 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 13 Jun 2008 11:23:27 -0400 Subject: [Tutor] ooffice UNO to generate automatic powerpoint presentations In-Reply-To: References: Message-ID: <82b4f5810806130823q6a7fe298tc0ca3001d04f3905@mail.gmail.com> Quicktime's Com API does something similar to this..... But nothing with PPT files, no. --Michael On Fri, Jun 13, 2008 at 10:28 AM, Mark Alexiuk wrote: > Hi, > I want to be able to generate Windows powerpoint presentations by > throwing > text and images into a directory and running a Python script. I've seen > some win32 modules online that manipulate powerpoint using COM but are > not > quite what I am looking for. > Examples I've found > http://mail.python.org/pipermail/python-win32/2006-March/004380.html > http://www.activeinterface.com/b2003_4_12.html > > http://www.robertgsmith.com/2006/03/tech-tools-just-for-realtors-powerpoint-creation-script-for-cmabuyer-tour-etc.aspx > Ideally, a file containing name=value pairs or XML would add title, text, > and images. > Has anyone done this with openoffice UNO? > Thanks for your comments, > Mark > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From marilyn at deliberate.com Sat Jun 14 00:32:47 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 13 Jun 2008 15:32:47 -0700 (PDT) Subject: [Tutor] Dictionary within a dictionary Message-ID: <3982.66.218.47.142.1213396367.squirrel@mail.tigertech.net> On Fri, June 13, 2008 7:23 am, qsqgeekyogdty at tiscali.co.uk wrote: > Hi, > Following Alan's post, what I was trying to do is to understand how I > can return the sub-item within the same space, if it makes sense ;) > > For example, in my 3 one-to-many lists, I want to generate this list: When see nested builtin data structures, I always think it's time to think of making a few classes instead. Python tutors, is this a good suggestion? Marilyn Davis > > > [{'id': , > 'category': [{'id': , > 'sub-category': [ {'id': , > 'title': , > 'is_selected': > } > ...] > 'title': , > 'is_selected': > } > ...] > 'title': , > 'is_selected': , > } > ...] > > > Reason for this is that I want to create a navigational menu for a web > template so that when you click on group_id the value is sent and this > pulls the 'categories' and when you click on the category then the sub- > categories are listed. > > Thanks > David > > > > > __________________________________________________________ > > > Find out what Tiscali can do for you - http://www.tiscali.co.uk/services > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Jun 14 01:09:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Jun 2008 00:09:20 +0100 Subject: [Tutor] Dictionary within a dictionary References: <3982.66.218.47.142.1213396367.squirrel@mail.tigertech.net> Message-ID: "Marilyn Davis" wrote > When see nested builtin data structures, I always think it's time to > think > of making a few classes instead. It could be, especially if you are about to write a bunch of functions to access those structures. But equally if the structures accurately reflect the problem and acess does not require any complex processing then I'm happy to use the structures. In a case like this I'd still tend to move to a database rather than an OOP solution, although I might use classes to hold the returned data. I'm still not clear why the OP wants to hold the data in memory. Alan G > > Python tutors, is this a good suggestion? > > Marilyn Davis > >> >> >> [{'id': , >> 'category': [{'id': , >> 'sub-category': [ {'id': , >> 'title': , >> 'is_selected': >> } >> ...] >> 'title': , >> 'is_selected': >> } >> ...] >> 'title': , >> 'is_selected': , >> } >> ...] >> >> >> Reason for this is that I want to create a navigational menu for a >> web >> template so that when you click on group_id the value is sent and >> this >> pulls the 'categories' and when you click on the category then the >> sub- >> categories are listed. >> >> Thanks >> David >> >> >> >> >> __________________________________________________________ >> >> >> Find out what Tiscali can do for you - >> http://www.tiscali.co.uk/services >> >> >> _______________________________________________ >> 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 hgfernan at lsi.usp.br Sat Jun 14 01:07:35 2008 From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes) Date: Fri, 13 Jun 2008 20:07:35 -0300 Subject: [Tutor] python gui In-Reply-To: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Message-ID: <200806132007.37502.hgfernan@lsi.usp.br> Hi, Gabriela! that interesting dashboard can be done. At least you can divide your main window into several subwindows and do what you what you want. Each subwindows would have a dropdownlist to redefine another sub-subwindow inside of it. Tabs are also available in several windowing toolkits for Python. In wxPython you can have a panel and put your subwindows inside of it: http://wxpython.org Another alternative is pyGTK. All the best, hilton Em Quarta 11 Junho 2008 10:03, Gabriela Soares escreveu: > Greetings, > I want to make a dynamic dashboard, something like: > http://examples.adobe.com/flex3/labs/dashboard/main.html# > but using python. Is it possible ? > > Thanks in advance. > > Best regards, > Gabriela Soares. > > -- > Gabriela Soares > > "I learned that courage was not the absence of fear, but the triumph over > it. The brave man is not he who does not feel afraid, but he who > conquers that fear." > Nelson Mandela _____________________ -- Hilton Garcia Fernandes Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab Escola Politecnica (Poli) -- Engineering School Univ S Paulo (USP) Tel: (5511)3091-5676 (work) ? ? ?(5511)8131-5213 (mobile) Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900 S. Paulo -- SP -- Brazil Pagina inicial: http://www.lsi.usp.br/~hgfernan From marilyn at deliberate.com Sat Jun 14 02:05:41 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 13 Jun 2008 17:05:41 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Dictionary within a dictionary] Message-ID: <56339.66.218.47.125.1213401941.squirrel@mail.tigertech.net> On Fri, June 13, 2008 4:09 pm, Alan Gauld wrote: > "Marilyn Davis" wrote > > >> When see nested builtin data structures, I always think it's time to >> think of making a few classes instead. > > It could be, especially if you are about to write a bunch of > functions to access those structures. But equally if the structures > accurately reflect the problem and acess does not require any complex > processing then I'm happy to use the structures. > > In a case like this I'd still tend to move to a database rather > than an OOP solution, although I might use classes to hold the returned > data. That sounds like the best plan. > > I'm still not clear why the OP wants to hold the data in > memory. I don't know either. Maybe s/he wants to use shelve or something; maybe s/he has not yet learned classes and databases. So thank you for the reality check. Marilyn Davis > > Alan G > >> >> Python tutors, is this a good suggestion? >> >> >> Marilyn Davis >> >> >>> >>> >>> [{'id': , >>> 'category': [{'id': , >>> 'sub-category': [ {'id': , >>> 'title': , >>> 'is_selected': >>> } >>> ...] >>> 'title': , >>> 'is_selected': >>> } >>> ...] >>> 'title': , >>> 'is_selected': , >>> } >>> ...] >>> >>> >>> >>> Reason for this is that I want to create a navigational menu for a >>> web template so that when you click on group_id the value is sent and >>> this pulls the 'categories' and when you click on the category then >>> the sub- categories are listed. >>> >>> Thanks >>> David >>> >>> >>> >>> >>> >>> __________________________________________________________ >>> >>> >>> >>> Find out what Tiscali can do for you - >>> http://www.tiscali.co.uk/services >>> >>> >>> >>> _______________________________________________ >>> 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 qsqgeekyogdty at tiscali.co.uk Sat Jun 14 11:16:56 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Sat, 14 Jun 2008 10:16:56 +0100 (GMT+01:00) Subject: [Tutor] Dictionary within a dictionary Message-ID: <14885019.1213435016414.JavaMail.root@ps26> Hello, Thank you for the replies. I wanted to hold the data in memory, because the number of records do not warrant the need to have to maintain an additional relational database. Plus I wanted to understand how to build this using classes as this will perhaps give me the bridge I require to move from seeing it as a relational model and more OO - I guess ;) David __________________________________________________________ Find out what Tiscali can do for you - http://www.tiscali.co.uk/services From kent37 at tds.net Sat Jun 14 13:34:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Jun 2008 07:34:58 -0400 Subject: [Tutor] Dictionary within a dictionary In-Reply-To: <20076062.1213366986098.JavaMail.root@ps36.mc.tiscali.sys> References: <20076062.1213366986098.JavaMail.root@ps36.mc.tiscali.sys> Message-ID: <1c2a2c590806140434t255a7631v7f7a4e40ecd6119a@mail.gmail.com> On Fri, Jun 13, 2008 at 10:23 AM, qsqgeekyogdty at tiscali.co.uk wrote: > Hi, > Following Alan's post, what I was trying to do is to understand how I > can return the sub-item within the same space, if it makes sense ;) Um, no, not to me. Is your question about creating a structure or accessing it? > For example, in my 3 one-to-many lists, I want to generate this list: > > [{'id': , > 'category': [{'id': , > 'sub-category': [ {'id': , > 'title': , > 'is_selected': > } > ...] > 'title': , > 'is_selected': > } > ...] > 'title': , > 'is_selected': , > } > ...] And this data is coming from a database? If it is fixed you can just create it as you did above; if you filled in actual values that would be valid Python code. Do you have any code you have tried? It helps to get specific. I still don't really understand what you are having trouble with. Is it - deciding on the best structure to represent the data - reading from a database and creating a nested structure - accessing a nested structure ? Kent From noufal at nibrahim.net.in Fri Jun 13 21:01:59 2008 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sat, 14 Jun 2008 00:31:59 +0530 Subject: [Tutor] Web Stats In-Reply-To: <1c2a2c590806111538o43370375ldfff984327bd5387@mail.gmail.com> References: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> <1c2a2c590806111538o43370375ldfff984327bd5387@mail.gmail.com> Message-ID: <4852C427.4070400@nibrahim.net.in> Kent Johnson wrote: > On Wed, Jun 11, 2008 at 3:58 PM, Stephen Nelson-Smith > wrote: >> Hello, >> >>>> This has to include resources which have not been visited, as the >>>> point is to clean out old stuff. wouldn't a 'find' for files with a an ancient access time be a better way of finding out? Also, http://ch.tudelft.nl/~arthur/webcheck/ is useful if you have the site up and running. It will give you some statistics about broken pages and old ones. -- ~noufal http://nibrahim.net.in/ From chester_lab at fltg.net Sun Jun 15 15:47:01 2008 From: chester_lab at fltg.net (FT) Date: Sun, 15 Jun 2008 09:47:01 -0400 Subject: [Tutor] If You Wish Microsoft Voices For Your Programming References: <1c2a2c590806111132l38721b0cyecda64f17ea66094@mail.gmail.com> <1c2a2c590806111538o43370375ldfff984327bd5387@mail.gmail.com> <4852C427.4070400@nibrahim.net.in> Message-ID: <000301c8ceee$4f2f3010$0301a8c0@brucetower> Hi! Below is the settings to use the built in SAPI 5 voices. It will also read any other voices loaded into the SAPI 5 and stores the list of all of them. You can change the names of the methods if you so desire. I am giving you an example of how to set up your voices. NOTE: The pitch of the voices has to be an XML command and it is built into the speech or Speak method. You will need to understand the XML commands if you wish to use the added XML features. Pitch is just one and there is one for spell, bookmarks, and so on... Bruce #DRIVERS FOR SAPI 5 AND VOICES! #NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES. from comtypes.client import CreateObject import _winreg class constants4tts: Wait = -1 Sync = 0 Async = 1 Purge = 2 Is_filename = 4 XML = 8 Not_XML = 16 Persist = 32 Punc = 64 class SynthDriver(): name="sapi5" description="Microsoft Speech API version 5 (sapi.SPVoice)" _pitch = 0 _voices = [] _wait = -1 #WAIT INDEFINITELY _sync = 0 #WAIT UNTIL SPEECH IS DONE. _async = 1 #DO NOT WAIT FOR SPEECH _purge = 2 #CLEAR SPEAKING BUFFER _is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE _xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER. _not_xml = 16 #NO XML COMMANDS _persist_xml = 32 #Changes made in one speak command persist to other calls to Speak. _punc = 64 #PRONOUNCE ALL PUNCTUATION! def check(self): try: r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice") r.Close() return True except: return False #INITIALIZE ENGINE! def init(self): try: self.tts = CreateObject( 'sapi.SPVoice') self._voice=1 self._voiceCount = len(self.tts.GetVoices()) for v in range(self._voiceCount): self._voices.append( self.tts.GetVoices()[v]) return True except: return False #TERMINATE INSTANCE OF ENGINE! def terminate(self): del self.tts #NUMBER OF VOICES FOR ENGINE! def getVoiceCount(self): return len(self.tts.GetVoices()) #NAME OF A VOICE NUMBER! def getVoiceName(self, num): return self.tts.GetVoices()[num-1].GetDescription() #WHAT IS VOICE RATE? def getRate(self): "MICROSOFT SAPI 5 RATE IS -10 TO 10" return (self.tts.rate) #WHAT IS THE VOICE PITCH? def getPitch(self): "PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!" return self._pitch #GET THE ENGINE VOLUME! def getVolume(self): "MICROSOFT SAPI 5 VOLUME IS 1% TO 100%" return self.tts.volume #GET THE VOICE NUMBER! def getVoiceNum(self): return self._voice #SET A VOICE BY NAME! def setVoiceByName(self, name): "VOICE IS SET BY NAME!" for i in range( self._voiceCount): vp = self.tts.GetVoices()[ i].GetDescription().find( name) if vp>0: self.tts.Voice = self._voices[i] # self.tts.Voice = self.tts.GetVoices()[i] self.tts.Speak( "%s Set!" % name) self._voice=i+1 break if i >= self._voiceCount: self.tts.Speak( "%s Not Found!" % name) #USED FOR BOOKMARKING AND USE LATER! def _get_lastIndex(self): bookmark=self.tts.status.LastBookmark if bookmark!="" and bookmark is not None: return int(bookmark) else: return -1 #NOW SET ENGINE PARMS! #SET THE VOICE RATE! def setRate(self, rate): "MICROSOFT SAPI 5 RATE IS -10 TO 10" if rate > 10: rate = 10 if rate < -10: rate = -10 self.tts.Rate = rate #SET PITCH OF THE VOICE! def setPitch(self, value): "MICROSOFT SAPI 5 pitch is really controled with xml around speECH TEXT AND IS -10 TO 10" if value > 10: value = 10 if value < -10: value = -10 self._pitch=value #SET THE VOICE VOLUME! def setVolume(self, value): "MICROSOFT SAPI 5 VOLUME IS 1% TO 100%" self.tts.Volume = value #CREATE ANOTHER INSTANCE OF A VOICE! def createVoice(self, value=1): if value > self.getVoiceCount: value = self.getVoiceCount if value < 1: value = 1 new_tts = CreateObject( 'sapi.SPVoice') return (new_tts.GetVoices()[ value-1]) #SPEAKING TEXT! #SPEAK TEXT USING BOOKMARKS AND PITCH! def SpeakText(self, text, wait=False, index=None): "SPEAK TEXT AND XML FOR PITCH MUST REPLACE ANY <> SYMBOLS BEFORE USING XML BRACKETED TEXT" flags = constants4tts.XML text = text.replace( "<", "<") pitch = ((self._pitch*2)-100)/10 if isinstance(index, int): bookmarkXML = "" % index #NOTE \" FOR XML FORMAT CONVERSION! else: bookmarkXML = "" flags = constants4tts.XML if wait is False: flags += constants4tts.Async self.tts.Speak( "%s%s" % (pitch, bookmarkXML, text), flags) #CANCEL SPEAK IN PROGRESS! def cancel(self): #if self.tts.Status.RunningState == 2: self.tts.Speak(None, 1|constants4tts.Purge) #SPEAK TEXT! def Speak(self, text, wait=0, sync=0, async=0, purge=0, isfile=0, xml=0, not_xml=0, persist=0, punc=0): "SAPI 5 HAS NO PITCH SO HAS TO BE IN TEXT SPOKEN!" pitch=self._pitch self.tts.Speak( "%s" % (pitch, text), wait |sync |async |purge |isfile |xml |not_xml |persist |punc) #SET THE VOICE BY VALUE! def setVoice(self,value): "SET VOICE AND SAY ITS DESCRIPTION!" if value < 1: value=1 if value > self._voiceCount: value = self._voiceCount self.tts.Voice = self._voices[ value-1] vd = self.tts.GetVoices()[ value-1].GetDescription() self.tts.Speak( vd[ vd.find(" "):]) self._voice=value #READ ALL THE VOICES IN THE ENGINE! def read_Voices(self): self.tts.Speak( "Voices are:") for i in range(1, self._voiceCount+1): #print self.getVoiceName(i) self.tts.Voice = self.tts.GetVoices()[i-1] vd = self.tts.GetVoices()[ i-1].GetDescription() self.tts.Speak( "%d) %s" % (i, vd[ vd.find(" "):])) From jbohren at seas.upenn.edu Sun Jun 15 20:32:01 2008 From: jbohren at seas.upenn.edu (Jonathan Bohren) Date: Sun, 15 Jun 2008 11:32:01 -0700 Subject: [Tutor] curses delwin functionality? Message-ID: > I'm trying to get my hands on some curses experiences in Python. > > The examples I found don't really tell me how to get rid of subwindows and > restore the underlying window again. Is there something that replaces the > curses functionality "delwin"? > Thanks for any help! I had the same question, and I performed some simple experiments. 1) Re-assignment. I ran this and watched python's memory usage. It was completely flat. for i in range(1,50000): stdscr.refresh() win = curses.newwin(10,1,0,2*2*i) win.bkgd(' ',curses.A_REVERSE) win.refresh() curses.napms(1) It seems that python calls the underlying curses API delwin(some_window) when some_window goes out of scope. Thus, there is no need to call something like it explicitly. Hope this helps. -j From arhall1 at comcast.net Sun Jun 15 23:07:58 2008 From: arhall1 at comcast.net (Arden Hall) Date: Sun, 15 Jun 2008 14:07:58 -0700 Subject: [Tutor] Tkinter problem Message-ID: <485584AE.2080901@comcast.net> I'm trying to learn to use Tkinter from "Thinking in Tkinter" and don't seem to be able to get the examples to work the way they are supposed to. I have the latest version of Python on a Macbook. Here's an example of the kind of problem I run into: The source code is: from Tkinter import * root = Tk() myContainer1 = Frame(root) myContainer.pack() button1 = Button(myContainer1) button1["text"} = "Hello, World!" button1[background"] = "green" button1.pack root.mainloop() I can execute this, but the button isn't green (or any other color I try) although it turns blue when I click the mouse on it. . Similarly, I've tried to write a bit of code to create a canvas object and put a rectangle in it, but I can't dimension the canvas, change its color, or get the rectangle to appear. Any advice or suggestion where to look for documentation would be greatly appreciated. Thanks Arden From alan.gauld at btinternet.com Sun Jun 15 23:55:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Jun 2008 22:55:14 +0100 Subject: [Tutor] Tkinter problem References: <485584AE.2080901@comcast.net> Message-ID: "Arden Hall" wrote > The source code is: I don't know if you cut n paste this but there are several errors: > from Tkinter import * > > root = Tk() > > myContainer1 = Frame(root) > myContainer.pack() mycontainer1 > button1 = Button(myContainer1) > button1["text"} = "Hello, World!" ] not } > button1[background"] = "green" > button1.pack pack() > root.mainloop() > I can execute this, but the button isn't green After fixing the errors, it works on my XP and Linux boxes. I haven't tried my Mac but see no reason why it shouldn't. > I've tried to write a bit of code to create a canvas object and > put a rectangle in it, but I can't dimension the canvas, change its > color, or get the rectangle to appear. Any advice or suggestion > where to look for documentation would be greatly appreciated. The online docs for tkinter are quite good. Start with the Tkinter area on the Python web site. Try posting more code here if it doesn't work. Cut n Paste by preference. Describe what you expect and what you get. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jopython at gmail.com Mon Jun 16 03:27:42 2008 From: jopython at gmail.com (Joe) Date: Sun, 15 Jun 2008 21:27:42 -0400 Subject: [Tutor] Tkinter problem In-Reply-To: <485584AE.2080901@comcast.net> References: <485584AE.2080901@comcast.net> Message-ID: <4855C18E.3050907@gmail.com> The following worked for me. from Tkinter import * root = Tk() myContainer = Frame(root) myContainer.pack() button1 = Button(myContainer) button1['text'] = "Hello, World!" button1['background'] = "green" button1.pack() root.mainloop() Arden Hall wrote: > I'm trying to learn to use Tkinter from "Thinking in Tkinter" and > don't seem to be able to get the examples to work the way they are > supposed to. I have the latest version of Python on a Macbook. Here's > an example of the kind of problem I run into: > > The source code is: > > from Tkinter import * > > root = Tk() > > myContainer1 = Frame(root) > myContainer.pack() > > button1 = Button(myContainer1) > button1["text"} = "Hello, World!" > button1[background"] = "green" > button1.pack > > root.mainloop() > > I can execute this, but the button isn't green (or any other color I > try) although it turns blue when I click the mouse on it. . Similarly, > I've tried to write a bit of code to create a canvas object and put a > rectangle in it, but I can't dimension the canvas, change its color, > or get the rectangle to appear. Any advice or suggestion where to look > for documentation would be greatly appreciated. > > Thanks > Arden > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bryan.fodness at gmail.com Mon Jun 16 16:28:55 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 16 Jun 2008 10:28:55 -0400 Subject: [Tutor] Posting to Numpy and Scipy Message-ID: Has anyone had a problem posting to either of these mailing lists. I am a member and have sent a few posts to each of them over the last couple months, but none of them show up in the list. I always receive a 'awaiting moderator approval' email. I have sent an email to the owner about this, but have not received a response. -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. " -Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: From gtxy20 at gmail.com Mon Jun 16 17:41:25 2008 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 16 Jun 2008 11:41:25 -0400 Subject: [Tutor] Replace sequence in list - looking for direction Message-ID: <39cb7e5d0806160841hbe71986m1bff1126e1f4af6d@mail.gmail.com> Hello all, Thanks in advance for any thoughts, direction, and guidance. Let's say I have a list like the following: a = ['a1','a2','a3','a4','a5','a6'] and then I have dictionary like the following: b = {'a1,a2,a3':'super'} I need some direction and thoughts on how I might seach the list for the string (the key in dict b) sequence in list a and replace the occurance with the value from dict b. At the end I would like to have list a represented as: a = ['super', 'a4', 'a5', 'a6'] Thanks. G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon Jun 16 17:44:58 2008 From: srilyk at gmail.com (W W) Date: Mon, 16 Jun 2008 10:44:58 -0500 Subject: [Tutor] Moving a window... on windows? Message-ID: <333efb450806160844w30d840ebqe8da53f42d5f79ba@mail.gmail.com> I'm not even sure if this is possible... and so far a google search of "python move windows xp" has failed to yield any helpful looking results. I'm trying to create a script that will move a program window around on the desktop, and other than that search I'm not sure where to look. What we have is a digital signage program that is ridiculously old, and we're trying to squeeze a bit more life out of it, until we have more money to spend on a better solution. It runs on a system with two video cards, because it requires an 640x480 output (regular coax... the system is ~10 yrs old), but the silly programmers did some things so the window will spawn in the same place on the wrong monitor. Currently I move it manually, but I want to automate the movement. If there's a way to move the program window by a specific X, Y value, I could make it work no problem. Does anyone have any experience with this sort of task? Or can someone point me towards a solution? Thanks in advance, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From mail at timgolden.me.uk Mon Jun 16 18:00:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Jun 2008 17:00:56 +0100 Subject: [Tutor] Moving a window... on windows? In-Reply-To: <333efb450806160844w30d840ebqe8da53f42d5f79ba@mail.gmail.com> References: <333efb450806160844w30d840ebqe8da53f42d5f79ba@mail.gmail.com> Message-ID: <48568E38.2040505@timgolden.me.uk> W W wrote: > I'm not even sure if this is possible... and so far a google search of > "python move windows xp" has failed to yield any helpful looking > results. > > I'm trying to create a script that will move a program window around > on the desktop, and other than that search I'm not sure where to look. > > What we have is a digital signage program that is ridiculously old, > and we're trying to squeeze a bit more life out of it, until we have > more money to spend on a better solution. It runs on a system with two > video cards, because it requires an 640x480 output (regular coax... > the system is ~10 yrs old), but the silly programmers did some things > so the window will spawn in the same place on the wrong monitor. > > Currently I move it manually, but I want to automate the movement. If > there's a way to move the program window by a specific X, Y value, I > could make it work no problem. Does anyone have any experience with > this sort of task? Or can someone point me towards a solution? My guess is that you want the "MoveWindow" API from the pywin32 extensions win32gui module. http://timgolden.me.uk/pywin32-docs/win32gui__MoveWindow_meth.html TJG From srilyk at gmail.com Mon Jun 16 18:23:55 2008 From: srilyk at gmail.com (W W) Date: Mon, 16 Jun 2008 11:23:55 -0500 Subject: [Tutor] Replace sequence in list - looking for direction In-Reply-To: <39cb7e5d0806160841hbe71986m1bff1126e1f4af6d@mail.gmail.com> References: <39cb7e5d0806160841hbe71986m1bff1126e1f4af6d@mail.gmail.com> Message-ID: <333efb450806160923q26b2dfb9p113d9af767408737@mail.gmail.com> On Mon, Jun 16, 2008 at 10:41 AM, GTXY20 wrote: > I need some direction and thoughts on how I might seach the list for the > string (the key in dict b) sequence in list a and replace the occurance with > the value from dict b. At the end I would like to have list a represented > as: > > a = ['super', 'a4', 'a5', 'a6'] That's a really odd problem... If your dict key value will always be separated by a comma, the easiest thing to do would use split on the key. replacement_items = [] for x in b: replacement_items.append(x.split(',')) [['a1', ' a2', ' a3']] will be replacement_items. You can simply iterate over those values and a.remove(each_value). It took me 6 lines to write a function that will do what you're requesting, though if you want 'super' to replace the consecutive(?) string in place (i.e. a[0:2]) it would take a little more coding, but not much. HTH, Wayne From tiagosaboga at gmail.com Mon Jun 16 19:15:24 2008 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Mon, 16 Jun 2008 14:15:24 -0300 Subject: [Tutor] Replace sequence in list - looking for direction In-Reply-To: <39cb7e5d0806160841hbe71986m1bff1126e1f4af6d@mail.gmail.com> References: <39cb7e5d0806160841hbe71986m1bff1126e1f4af6d@mail.gmail.com> Message-ID: <20080616171524.GA3690@localdomain> On Mon, Jun 16, 2008 at 11:41:25AM -0400, GTXY20 wrote: > Hello all, > > Thanks in advance for any thoughts, direction, and guidance. > > Let's say I have a list like the following: > > a = ['a1','a2','a3','a4','a5','a6'] > > and then I have dictionary like the following: > > b = {'a1,a2,a3':'super'} > > I need some direction and thoughts on how I might seach the list for the > string (the key in dict b) sequence in list a and replace the occurance with > the value from dict b. At the end I would like to have list a represented > as: > > a = ['super', 'a4', 'a5', 'a6'] The following works for your example. I assume the values in the a list are unique. for key in b: keylist = key.split(',') if keylist < a: i = a.index(keylist[0]) print a[:i] + [b[key]] + a[i+len(keylist):] Tiago Saboga. From alan.gauld at btinternet.com Mon Jun 16 20:09:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Jun 2008 19:09:13 +0100 Subject: [Tutor] Moving a window... on windows? References: <333efb450806160844w30d840ebqe8da53f42d5f79ba@mail.gmail.com> <48568E38.2040505@timgolden.me.uk> Message-ID: "Tim Golden" wrote >> Currently I move it manually, but I want to automate the movement. >> If >> there's a way to move the program window by a specific X, Y value, >> I >> could make it work no problem. Does anyone have any experience with >> this sort of task? Or can someone point me towards a solution? > > My guess is that you want the "MoveWindow" API from the pywin32 > extensions win32gui module. > > http://timgolden.me.uk/pywin32-docs/win32gui__MoveWindow_meth.html And also see the Microsoft docs at MSDN. Go to: http://msdn.microsoft.com/en-gb/default.aspx Just type MoveWindow into the search box. Alan G From wtfwhoami at gmail.com Mon Jun 16 22:38:21 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 16 Jun 2008 13:38:21 -0700 Subject: [Tutor] newbie Python Modules Message-ID: <8c64f3990806161338k65d14ab6wf9c264466c65218f@mail.gmail.com> *Module Name eli.py* x = 0 y = [1, 2] print 'Running module "eli"' def whitney(): print 'whitney' def printValues(): print x , y *When I imported the Module* from eli import x, y, printValues printValues() y[0] = 'cat' x = 'dog' printValues() Output Running module "eli" 0 [1, 2] 0 ['cat', 2] Can Someone explain this to me? Why x remains 0 ....Is it because x = 'dog' is local variable and y being a list is a mutable object that is changed easily. Also once we reload the module .... every value reverts to its original value .. Am I Right? Thanks, G -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 17 01:47:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Jun 2008 00:47:02 +0100 Subject: [Tutor] newbie Python Modules References: <8c64f3990806161338k65d14ab6wf9c264466c65218f@mail.gmail.com> Message-ID: "Guess?!?" wrote > *Module Name eli.py* > x = 0 > y = [1, 2] > > def whitney(): > print 'whitney' > > def printValues(): > print x , y > *When I imported the Module* > > from eli import x, y, printValues Note that by doing this you are not really importing the module but the names from the module into your name space. > printValues() > y[0] = 'cat' This is changing the value of the y variable which is in the eli module. > x = 'dog' This is creaating a new x value in your local namespace. > printValues() This prints the values from the eli module. > Running module "eli" > > 0 [1, 2] > > 0 ['cat', 2] x is unchanged at zero. y is also unchanged but the content is changed > Is it because x = 'dog' is local variable and y being > a list is a mutable object that is changed Yes, although being picky about the term local its not strictly true since local means inside a function or method In your case you created a new global (ie module scope) variable x which masked the imported one. > Also once we reload the module .... every value reverts to its > original > value .. Am I Right? Yes, but you have not "loaded" the module yet, only the names from within it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Jun 17 02:08:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jun 2008 20:08:56 -0400 Subject: [Tutor] newbie Python Modules In-Reply-To: <8c64f3990806161338k65d14ab6wf9c264466c65218f@mail.gmail.com> References: <8c64f3990806161338k65d14ab6wf9c264466c65218f@mail.gmail.com> Message-ID: <1c2a2c590806161708q13bf074bn1057dd085d96b43f@mail.gmail.com> On Mon, Jun 16, 2008 at 4:38 PM, Guess?!? wrote: > Also once we reload the module .... every value reverts to its original > value .. Am I Right? Yes, but maybe not in the way you think. A new copy of the module will be loaded and bound to the name 'eli'. But the names x, y and printValues, which are bound to values in the old copy of the module, will not change. So if, after all your above manipulations, you import eli reload(eli) you will see that x, y and printValues have the same values as before, but eli.x and eli.y will be restored to the original values. Kent From wtfwhoami at gmail.com Tue Jun 17 02:46:52 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 16 Jun 2008 17:46:52 -0700 Subject: [Tutor] newbie Python Modules In-Reply-To: <1c2a2c590806161708q13bf074bn1057dd085d96b43f@mail.gmail.com> References: <8c64f3990806161338k65d14ab6wf9c264466c65218f@mail.gmail.com> <1c2a2c590806161708q13bf074bn1057dd085d96b43f@mail.gmail.com> Message-ID: <8c64f3990806161746h22dc842dkfba38c55ba317d9e@mail.gmail.com> Thanks Alan and Kent ...Its much clearer now. Any tutorial/reference you recommend to read about python modules? Thanks G On Mon, Jun 16, 2008 at 5:08 PM, Kent Johnson wrote: > On Mon, Jun 16, 2008 at 4:38 PM, Guess?!? wrote: > > > Also once we reload the module .... every value reverts to its original > > value .. Am I Right? > > Yes, but maybe not in the way you think. A new copy of the module will > be loaded and bound to the name 'eli'. But the names x, y and > printValues, which are bound to values in the old copy of the module, > will not change. > > So if, after all your above manipulations, you > import eli > reload(eli) > > you will see that x, y and printValues have the same values as before, > but eli.x and eli.y will be restored to the original values. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryan.fodness at gmail.com Tue Jun 17 04:47:54 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 16 Jun 2008 22:47:54 -0400 Subject: [Tutor] my own error code when no argument is sent Message-ID: when i execute my program without an argument i receive, infile = sys.argv[1] IndexError: list index out of range is there a way that i could suppress this and add my own error code -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at cs.wpi.edu Tue Jun 17 05:05:50 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Mon, 16 Jun 2008 23:05:50 -0400 Subject: [Tutor] my own error code when no argument is sent In-Reply-To: References: Message-ID: when i execute my program without an argument i receive, > > > infile = sys.argv[1] > > IndexError: list index out of range > > is there a way that i could suppress this and add my own error code The direct way to handle this is to check the length of sys.argv first. sys.argv is a list, so you can ask the list for its length. Do you know how to do that? From chester_lab at fltg.net Tue Jun 17 05:40:42 2008 From: chester_lab at fltg.net (FT) Date: Mon, 16 Jun 2008 23:40:42 -0400 Subject: [Tutor] Using SAPI 5 Voices and Methods Message-ID: <004301c8d02b$f02ab140$0301a8c0@brucetower> Hi! I am resending this SAPI examples for speech, I guess in some cases the email message gets messed up so I attached the SAPI 5 test for voices along with an HTML version using Java Script. It also has the methods and a voice by name assignment since the voices are an array list by element. So I use the description to find the name. It also lists the voice names in the console field. I guess you could also use the pyTTS version as well. I did have one problem and that was the isfilename flag seems to get an error. But, also my spell tag did not work on my tower computer, but did work on my Lap Top. Do not know why, but it could be a version issue. Yet the isfilename also does not work on the Lap Top, so who knows. Anyway, have fun and install if for either your games or web pages... Bruce -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Test4Sapi.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Sapi5.py URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtfwhoami at gmail.com Tue Jun 17 06:14:35 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 16 Jun 2008 21:14:35 -0700 Subject: [Tutor] Python Gotcha - List Question Message-ID: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> Exercise 17.6 Write a definition for a class named Kangaroo with the following methods: 1. An init method that initializes an attribute named pouch contents to an empty list. 2. A method named put in pouch that takes an object of any type and adds it to pouch contents. Test your code by creating two Kangaroo objects, assigning them to variables named kanga and roo, and then adding roo to the contents of kanga's pouch. class Kangaroo: def __init__(self, pouch_contents=None): if pouch_contents is None: pouch_contents = [] else: self.pouch_contents = pouch_contents def put_in_pouch(self,obj): self.pouch_contents.append(obj) return self.pouch_contents kanga = Kangaroo([1,2]) roo = Kangaroo([3,4]) print kanga,roo print kanga.put_in_pouch(roo.pouch_contents) ************** <__main__.Kangaroo instance at 0x00A9A878> <__main__.Kangaroo instance at 0x00A9A8A0> [1, 2, [3, 4]] ************** when I modify as class Kangaroo: def __init__(self, pouch_contents=None): if pouch_contents is None: pouch_contents = [] else: self.pouch_contents = pouch_contents def put_in_pouch(self,obj): self.pouch_contents.append(obj) return self.pouch_contents kanga = Kangaroo() roo = Kangaroo() print kanga,roo print kanga.put_in_pouch(roo) I get error which states ... empty list never got formed .... <__main__.Kangaroo instance at 0x00A9A878> <__main__.Kangaroo instance at 0x00A9A8A0> Traceback (most recent call last): File "C:\Documents and Settings\Gagan\workspace\PythonWork\src\Kangaroo.py", line 17, in print kanga.put_in_pouch(roo) File "C:\Documents and Settings\Gagan\workspace\PythonWork\src\Kangaroo.py", line 10, in put_in_pouch self.pouch_contents.append(obj) AttributeError: Kangaroo instance has no attribute 'pouch_contents' Where Am I acting as NewBie :)? From dyoo at cs.wpi.edu Tue Jun 17 06:24:59 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 17 Jun 2008 00:24:59 -0400 Subject: [Tutor] Python Gotcha - List Question In-Reply-To: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> References: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> Message-ID: On Tue, Jun 17, 2008 at 12:14 AM, Guess?!? wrote: > Exercise 17.6 Write a definition for a class named Kangaroo with the > following methods: [cut] Be careful about asking for homework help. We're restricted from giving much help on homework questions. The error message you're seeing is: AttributeError: Kangaroo instance has no attribute 'pouch_contents' I would believe this message. This is saying that, for some reason, your Kangaroos don't have pouches. Where would this 'pouch_contents' attribute be initialized? From arhall1 at comcast.net Tue Jun 17 06:57:55 2008 From: arhall1 at comcast.net (Arden Hall) Date: Mon, 16 Jun 2008 21:57:55 -0700 Subject: [Tutor] Tkinter problem In-Reply-To: References: Message-ID: <48574453.4040407@comcast.net> A followup on the message below. The source code has errors in it because I keyed it in rather than copying and pasting, as pointed out by Alan Gauld. Joe replied with corrected code and said it worked for him. I took his code and ran it on the Mac and had the same problem as before: everything but the background color worked. I then installed Python on a Windows PC and tried the same code: with the PC, the background color works. So the problem seems to be bug in Tkinter for the Mac. Thanks Alan and Joe for your help. > >Message: 3 >Date: Sun, 15 Jun 2008 14:07:58 -0700 >From: Arden Hall >Subject: [Tutor] Tkinter problem >To: tutor at python.org >Message-ID: <485584AE.2080901 at comcast.net> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >I'm trying to learn to use Tkinter from "Thinking in Tkinter" and don't >seem to be able to get the examples to work the way they are supposed >to. I have the latest version of Python on a Macbook. Here's an >example of the kind of problem I run into: > >The source code is: > > from Tkinter import * > > root = Tk() > > myContainer1 = Frame(root) > myContainer.pack() > > button1 = Button(myContainer1) > button1["text"} = "Hello, World!" > button1[background"] = "green" > button1.pack > > root.mainloop() > >I can execute this, but the button isn't green (or any other color I >try) although it turns blue when I click the mouse on it. . Similarly, >I've tried to write a bit of code to create a canvas object and put a >rectangle in it, but I can't dimension the canvas, change its color, or >get the rectangle to appear. Any advice or suggestion where to look for >documentation would be greatly appreciated. > >Thanks >Arden > > > From wtfwhoami at gmail.com Tue Jun 17 07:07:28 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 16 Jun 2008 22:07:28 -0700 Subject: [Tutor] Python Gotcha - List Question In-Reply-To: References: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> Message-ID: <8c64f3990806162207r62f09d0o8b8b7ae3209a2700@mail.gmail.com> Hello Danny, It isnt my homework. I am reading Think Python: An Introduction to Software Design ..... This is Exercise question of Chap 17 Thanks, G On Mon, Jun 16, 2008 at 9:24 PM, Danny Yoo wrote: > On Tue, Jun 17, 2008 at 12:14 AM, Guess?!? wrote: >> Exercise 17.6 Write a definition for a class named Kangaroo with the >> following methods: > > [cut] > > Be careful about asking for homework help. We're restricted from > giving much help on homework questions. > > > The error message you're seeing is: > > AttributeError: Kangaroo instance has no attribute 'pouch_contents' > > I would believe this message. This is saying that, for some reason, > your Kangaroos don't have pouches. > > Where would this 'pouch_contents' attribute be initialized? > From wtfwhoami at gmail.com Tue Jun 17 07:10:12 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 16 Jun 2008 22:10:12 -0700 Subject: [Tutor] Python Gotcha - List Question In-Reply-To: <8c64f3990806162207r62f09d0o8b8b7ae3209a2700@mail.gmail.com> References: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> <8c64f3990806162207r62f09d0o8b8b7ae3209a2700@mail.gmail.com> Message-ID: <8c64f3990806162210j75f1f712t755eb68aeb3cbcd@mail.gmail.com> Hello All, Just made a minor change ..... its fixed now :) class Kangaroo: def __init__(self, pouch_contents=None): if pouch_contents is None: self.pouch_contents = [] else: self.pouch_contents = pouch_contents def put_in_pouch(self,obj): self.pouch_contents.append(obj) return self.pouch_contents kanga = Kangaroo() roo = Kangaroo() print kanga,roo print kanga.put_in_pouch(roo.pouch_contents) ***********************************************************************88 <__main__.Kangaroo instance at 0x00A9A878> <__main__.Kangaroo instance at 0x00A9A8A0> [[]] From cspears2002 at yahoo.com Tue Jun 17 07:46:40 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 16 Jun 2008 22:46:40 -0700 (PDT) Subject: [Tutor] a question about iterators Message-ID: <299517.56967.qm@web51608.mail.re2.yahoo.com> I've been learning about how to implement an iterator in a class from Core Python Programming (2nd Edition). >>> class AnyIter(object): ... def __init__(self, data, safe=False): ... self.safe = safe ... self.iter = iter(data) ... ... def __iter__(self): ... return self ... ... def next(self, howmany=1): ... retval = [] ... for eachItem in range(howmany): ... try: ... retval.append(self.iter.next()) ... except StopIteration: ... if self.safe: ... break ... else: ... raise ... return retval ... >>> >>> a = AnyIter(range(10)) >>> i = iter(a) >>> for j in range(1,5): ... print j, ':', i.next(j) ... 1 : [0] 2 : [1, 2] 3 : [3, 4, 5] 4 : [6, 7, 8, 9] I am confused by this statement: >>> i = iter(a) Why do I need to turn 'a' into an iterator? Didn't I already do this when I constructed the class? As a test, I tried the following: >>> for j in range(1,5): ... print j, ':', a.next(j) ... 1 : Traceback (most recent call last): File "", line 2, in ? File "", line 13, in next StopIteration >>> Why didn't that work? From broek at cc.umanitoba.ca Tue Jun 17 09:01:46 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Tue, 17 Jun 2008 02:01:46 -0500 Subject: [Tutor] my own error code when no argument is sent In-Reply-To: References: Message-ID: <20080617020146.985vojjtwkkokwgw@webware.cc.umanitoba.ca> > when i execute my program without an argument i receive, > > > infile = sys.argv[1] > > IndexError: list index out of range > is there a way that i could suppress this and add my own error code > Hi Bryan, You are probably better off pursuing Danny's suggestion. But, this is what you asked for: IDLE 1.1.4 >>> class CustomError(Exception): pass >>> import sys >>> try: infile = sys.argv[1] except IndexError: raise CustomError, "Some msg (this is optional)" Traceback (most recent call last): File "", line 4, in -toplevel- raise CustomError, "Some msg (this is optional)" CustomError: Some msg (this is optional) Best, Brian vdB From alan.gauld at btinternet.com Tue Jun 17 09:23:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Jun 2008 08:23:02 +0100 Subject: [Tutor] my own error code when no argument is sent References: <20080617020146.985vojjtwkkokwgw@webware.cc.umanitoba.ca> Message-ID: wrote >> infile = sys.argv[1] >> >> IndexError: list index out of range >> is there a way that i could suppress this and add my own error code > Hi Bryan, > You are probably better off pursuing Danny's suggestion. But, this > is what you asked for: > > IDLE 1.1.4 >>>> class CustomError(Exception): > pass Or, combining the suggestions you get: import sys try: infile = sys.argv[1] except IndexError: # handle the error by assigning a default value # just as you would do if checking len() Lots of options :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Jun 17 11:58:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jun 2008 05:58:29 -0400 Subject: [Tutor] Tkinter problem In-Reply-To: <48574453.4040407@comcast.net> References: <48574453.4040407@comcast.net> Message-ID: <1c2a2c590806170258o6f16a6dag630773f091dba7@mail.gmail.com> On Tue, Jun 17, 2008 at 12:57 AM, Arden Hall wrote: > A followup on the message below. The source code has errors in it because I > keyed it in rather than copying and pasting, as pointed out by Alan Gauld. > Joe replied with corrected code and said it worked for him. I took his > code and ran it on the Mac and had the same problem as before: everything > but the background color worked. I then installed Python on a Windows PC > and tried the same code: with the PC, the background color works. So the > problem seems to be bug in Tkinter for the Mac. Thanks Alan and Joe for > your help. It fails on my Mac also. Kent From bhaaluu at gmail.com Tue Jun 17 13:40:52 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 17 Jun 2008 07:40:52 -0400 Subject: [Tutor] Visualizing the Python Project Message-ID: This is very interesting! http://www.vimeo.com/1093745 Visualizing the commit history of the Python scripting language project. http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From kent37 at tds.net Tue Jun 17 14:14:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jun 2008 08:14:35 -0400 Subject: [Tutor] a question about iterators In-Reply-To: <299517.56967.qm@web51608.mail.re2.yahoo.com> References: <299517.56967.qm@web51608.mail.re2.yahoo.com> Message-ID: <1c2a2c590806170514r2406a488m768fe513e801bc01@mail.gmail.com> On Tue, Jun 17, 2008 at 1:46 AM, Christopher Spears wrote: > I am confused by this statement: >>>> i = iter(a) > > Why do I need to turn 'a' into an iterator? Didn't I already do this when I constructed the class? Yes, a is already an iterator. > As a test, I tried the following: > >>>> for j in range(1,5): > ... print j, ':', a.next(j) > ... > 1 : > Traceback (most recent call last): > File "", line 2, in ? > File "", line 13, in next > StopIteration >>>> > > Why didn't that work? Did you make a new a or reuse the same one? The old a has reached the end of its values so it raises StopIteration. Note that passing parameters to next() is not part of the iterator protocol. Kent From srilyk at gmail.com Tue Jun 17 14:26:28 2008 From: srilyk at gmail.com (W W) Date: Tue, 17 Jun 2008 07:26:28 -0500 Subject: [Tutor] Visualizing the Python Project In-Reply-To: References: Message-ID: <333efb450806170526s2059f079wd6a0373fc8eee24b@mail.gmail.com> On Tue, Jun 17, 2008 at 6:40 AM, bhaaluu wrote: > This is very interesting! > > http://www.vimeo.com/1093745 > > Visualizing the commit history of the Python scripting language project. > > http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ That would only be cooler if it was written in python ;) (maybe it was, but it wasn't specified on the page I read :P) From bhaaluu at gmail.com Tue Jun 17 14:33:15 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 17 Jun 2008 08:33:15 -0400 Subject: [Tutor] Visualizing the Python Project In-Reply-To: <333efb450806170526s2059f079wd6a0373fc8eee24b@mail.gmail.com> References: <333efb450806170526s2059f079wd6a0373fc8eee24b@mail.gmail.com> Message-ID: On Tue, Jun 17, 2008 at 8:26 AM, W W wrote: > On Tue, Jun 17, 2008 at 6:40 AM, bhaaluu wrote: >> This is very interesting! >> >> http://www.vimeo.com/1093745 >> >> Visualizing the commit history of the Python scripting language project. >> >> http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ > > That would only be cooler if it was written in python ;) (maybe it > was, but it wasn't specified on the page I read :P) > I know, right? Michael Ogawa, the UC Davis student who made code_swarm says he is seriously considering releasing the source code to his project as open source. We'll see. He says the source code, as it is now, needs to be cleaned-up (which indicates it probably wasn't written in Python - since Python, by its very nature is clean, right?). Nevertheless, the video of the Python Project is really cool! I like it when the project explodes in 2000. It's like a SuperNova. -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From gordon.agress at gmail.com Tue Jun 17 18:58:24 2008 From: gordon.agress at gmail.com (Gordon Agress) Date: Tue, 17 Jun 2008 12:58:24 -0400 Subject: [Tutor] Automating GUI Command Regression Testing Message-ID: Could someone please point me to resources that would help me learn to pipe keyboard input for commands to a Tkinter GUI, and then to automate saving a screen shot of the resulting GUI display? Is this even possible? I'm trying to automate regression testing of a simple Tkinter GUI. I'd like to supplant manual entry of keyboard commands (hotkeys like Alt-F, tabs and arrows to move among fields and buttons, data entry, 'enter', etc) with a file holding all that stuff, and store an image of the outcome for later review or comparison. Simply piping a file to the GUI didn't work, but I don't know if this is because the pipe doesn't work or because I don't know how to properly represent events like Alt-F or Tab in the text file. I've looked in Programming Python and the Python Cookbook, and on the 'net, but haven't found anything that seems helpful. Any help would be appreciated -- I don't want to manually step through a bunch of menu trees every time I make a change! -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Tue Jun 17 21:49:57 2008 From: cbc at unc.edu (Chris Calloway) Date: Tue, 17 Jun 2008 15:49:57 -0400 Subject: [Tutor] BootCampArama Early Bird Registration Reminder Message-ID: <48581565.8040308@unc.edu> Just a reminder, we're at the two week warning on early bird registration for PyCamp: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 7 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1 intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: info at trizpug.org -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From alan.gauld at btinternet.com Tue Jun 17 23:58:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Jun 2008 22:58:43 +0100 Subject: [Tutor] Automating GUI Command Regression Testing References: Message-ID: "Gordon Agress" wrote > help me learn to pipe keyboard input for commands to a Tkinter GUI, > and then > to automate saving a screen shot of the resulting GUI display? Is > this even > possible? Its possible but not trivial. It depends a lot on your OS since X Wndows and MS Windows work very differently. And if you are on Aqua under MacOS your best bet might be to use Applescript to automate things. > to supplant manual entry of keyboard commands (hotkeys like Alt-F, > tabs and > arrows to move among fields and buttons, data entry, 'enter', etc) > with a > file holding all that stuff, and store an image of the outcome for > later > review or comparison. If you are on Windows then you can use the FindWindow and PostMessage API calls to send windows events to the window. You can find the API documentation in the python winall documentaton and the native C documentation on the MS MSDN werb site. See also the recent thread (this last week) about moving a window using the Win32 API for a very short example... If you are on X wuindows then it is much more complex and you might be better lookingh for a 3rd party tool. There are several commercial ones and there might be some freeware ones too, but I don't know the area well enough to recommend anything. If you have money to spend I can get some recommendations from my test team if needed... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jun 18 01:26:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Jun 2008 00:26:43 +0100 Subject: [Tutor] Tkinter problem References: <485584AE.2080901@comcast.net> Message-ID: "Arden Hall" wrote > I'm trying to learn to use Tkinter from "Thinking in Tkinter" I'll make a couple of comments on the code then add a hypothesis about the reason for your "error" > button1 = Button(myContainer1) > button1["text"} = "Hello, World!" > button1[background"] = "green" > button1.pack Its common in Tkinter to set all the attributes in the init method lie so: button1 = Button(myContainer1, text="Hello, World!",background= "green") Or if modifying several attributes at once to use configure(), like this: button1.configure(text="Hello, World!",background= "green") Its shorter and just as easy to read. The dictionary style access tends to be reserved for single attribute changes. > I can execute this, but the button isn't green (or any other color I > try) although it turns blue when I click the mouse on it. . I think this means you are running an Aqua build of Tkinter. It would not surprise me if such a build did not support more than a limited subset of colours since Apple are very keen to ensure that Aqua applications conform to their style guide. And they like buttons to be blue or white and not much else! I suspect that if you can find a build of Tkinter for X under Darwin(probably via Fink) then that would behave as expected. But not having such a build myself I can only confirm that it works OK on my eeePC Linux box running Xandros Linux... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From chester_lab at fltg.net Wed Jun 18 14:36:58 2008 From: chester_lab at fltg.net (FT) Date: Wed, 18 Jun 2008 08:36:58 -0400 Subject: [Tutor] Using SAPI 5 Voices and Methods References: <20080617034230.DCC8C40843@cloak.guaranteedservers.net> Message-ID: <006501c8d140$04ff9530$0301a8c0@brucetower> As a note to this message post: the error I was getting for both the spell and the isfilename was traced down to simple factors. One problem is finding clear explanations and then checking the erroor codes. I found both on the issues mentioned about the SAPI 5 issues. The test I was running and encountered an error with the spell command came from using 2 different type voice packages as one. What I am saying is that I had the 3 Microsoft voices Sam, Mike, and Mary loaded in with 6 eSpeak voices and the error came when I did a test using the eSpeak voice. Once I used the Microsoft voice the error went away. The error I traced to being a unsupported operator type in the ctypes error list: WorkflowConditionOperatorNotSupported -2147201006 "Condition operator not supported for specified type." Error List: http://msdn.microsoft.com/en-us/library/cc151248.aspx The other error came from the open file command, which when using XML commands it is an Internet, Navigator error. When trying to understand the commands and the formats I could not truely understand what was being said, so I thought it could read a text.txt file but it does not. The isfilename comand is for reading a .wav file only. So I got rid of an flags except the isfilename flag, or 4 on the list and it worked. It will also work for sync or async, but you have to understand what each flat means and what it blocks. So this is the error description when using a wrong file type in the sapi XML ISFILENAME flag: List Of Error Codes: http://msdn.microsoft.com/en-us/library/aa768365(VS.85).aspx NavigateError Event Status Codes This page lists the possible values for the StatusCode parameter of the DWebBrowserEvents2::NavigateError -2146697203 INET_E_UNKNOWN_PROTOCOL (0x800C000DL or -2146697203) There a lot of error codes on both lists and you just have to search the code number you wish to find. I am posting this for anyone that may encounter such errors when using SAPI 5 commands. Sent: Monday, June 16, 2008 11:40 PM Subject: [Tutor] Using SAPI 5 Voices and Methods! Hi! I guess in some cases the email message gets messed up so I attached the SAPI 5 test for voices along with an HTML version using Java Script. It also has the methods and a voice by name assignment since the voices are an array list by element. So I use the description to find the name. It also lists the voice names in the console field. I guess you could also use the pyTTS version as well. I did have one problem and that was the isfilename flag seems to get an error. But, also my spell tag did not work on my tower computer, but did work on my Lap Top. Do not know why, but it could be a version issue. Yet the isfilename also does not work on the Lap Top, so who knows. Anyway, have fun and install if for either your games or web pages... Bruce -------------- next part -------------- An HTML attachment was scrubbed... URL: From amit.pureenergy at gmail.com Wed Jun 18 16:13:21 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Wed, 18 Jun 2008 19:43:21 +0530 Subject: [Tutor] (no subject) Message-ID: Hi , Could you please tell me , how i can traverse a two dimensional array , i am sorry , it must be pretty simple but I am new to python am not able to understand. -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Wed Jun 18 18:00:17 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 18 Jun 2008 09:00:17 -0700 Subject: [Tutor] Python Gotcha - List Question In-Reply-To: <8c64f3990806162207r62f09d0o8b8b7ae3209a2700@mail.gmail.com > References: <8c64f3990806162114v2e6986efq58809ae1403e40b0@mail.gmail.com> <8c64f3990806162207r62f09d0o8b8b7ae3209a2700@mail.gmail.com> Message-ID: <20080618160031.296811E4013@bag.python.org> At 10:07 PM 6/16/2008, Guess?!? wrote: > I am reading Think Python: An Introduction to >Software Design This is a recent major revision of a book familiar to many, How to Think Like a Computer Scientist: Learning with Python. Dick Moores From pine508 at hotmail.com Wed Jun 18 21:07:43 2008 From: pine508 at hotmail.com (Che M) Date: Wed, 18 Jun 2008 15:07:43 -0400 Subject: [Tutor] when is object relational mapping for Python warranted? Message-ID: Thank you both to Tim Golden and Jeff Younker for your helpful responses last week [see archive] about ORMs in Python/SQLite. Very helpful, and I'll get around to giving it a try one of these days... Che From: pine508 at hotmail.com To: tutor at python.org Subject: when is object relational mapping for Python warranted? Date: Wed, 11 Jun 2008 02:23:13 -0400 (tried to write a descriptive subject line) I'm curious whether I should consider learning either SQLObject or SQLAlchemy, and whether my needs would be worth it. I am learning to use SQlite databases for fairly simple storage and later search, and have only recently learned about object relational mapping (ORM). "Fairly simple" = 4-6 tables with no more than 2-10 fields each, 100-5,000 records, with queries doing basic LIKE and other matches, nothing fancy. I'd like to hear opinions on when it is worth it to use these ORM tools for a Python database application, that is, in terms of the complexity of the database or queries or the application, or when basic Python and SQL is sufficient. It's a personal preference, I'm sure, but I just wanted to get some opinions. Also, if there is an opinion about either of these two ORMs in terms of learning curve, quality, etc. Thanks, Che It?s easy to add contacts from Facebook and other social sites through Windows Live? Messenger. Learn How. _________________________________________________________________ Need to know now? Get instant answers with Windows Live Messenger. http://www.windowslive.com/messenger/connect_your_way.html?ocid=TXT_TAGLM_WL_Refresh_messenger_062008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jun 18 21:36:29 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 18 Jun 2008 15:36:29 -0400 Subject: [Tutor] traverse a two dimensional array In-Reply-To: References: Message-ID: <485963BD.6050605@gmail.com> amit sethi wrote: > Hi , Could you please tell me , how i can traverse a two dimensional > array , i am sorry , it must be pretty simple but I am new to python > am not able to understand. How did you create the array? How have you tried to traverse it? What do you mean by traverse? -- Bob Gailer 919-636-4239 Chapel Hill, NC From carroll at tjc.com Wed Jun 18 21:36:58 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 18 Jun 2008 12:36:58 -0700 (PDT) Subject: [Tutor] Traversing a two-dimensional "array"(was: (no subject) In-Reply-To: Message-ID: On Wed, 18 Jun 2008, amit sethi wrote: > Hi , Could you please tell me , how i can traverse a two dimensional array , > i am sorry , it must be pretty simple but I am new to python am not able to > understand. What many languages would call a two-dimensional array would be represented in Python as a list of lists; i.e., a list where each item in the list is itself another list. For example, if we have a list like this: >>> list_of_lists = [ ... [1, 2, 3, 4], ... ['A', 'B', 'C', 'D'], ... ["I", "II", "III", "IV"] ... ] >>> list_of_lists [[1, 2, 3, 4], ['A', 'B', 'C', 'D'], ['I', 'II', 'III', 'IV']] You can traverse it like this: >>> for inner_list in list_of_lists: ... print "inner_list is:", inner_list ... for item in inner_list: ... print "item:", item ... inner_list is: [1, 2, 3, 4] item: 1 item: 2 item: 3 item: 4 inner_list is: ['A', 'B', 'C', 'D'] item: A item: B item: C item: D inner_list is: ['I', 'II', 'III', 'IV'] item: I item: II item: III item: IV >>> There's no need for each inner list to be of the same length, by the way; I just made it so for this example. From kuffert_med_hat at hotmail.com Thu Jun 19 01:03:04 2008 From: kuffert_med_hat at hotmail.com (Emil) Date: Thu, 19 Jun 2008 01:03:04 +0200 Subject: [Tutor] traverse a two dimensional array In-Reply-To: References: Message-ID: ________________________________ > Date: Wed, 18 Jun 2008 19:43:21 +0530 > From: amit.pureenergy at gmail.com > To: tutor at python.org > Subject: [Tutor] (no subject) > > Hi , Could you please tell me , how i can traverse a two dimensional array , i am sorry , it must be pretty simple but I am new to python am not able to understand. > > -- > A-M-I-T S|S Are you talking about an object which contains corresponding key value pairs? If so, in python it is called a dictionary and look like this d = { 1 : 'a' , 2 : 'b' , 3 : 'c'}. I am not totally sure what you mean by traverse. But if you are talking about how you access the values stored at a key, you simply do it by calling the key and then it returns the value like this: >>> d = { 1 : 'a', 2 : 'b', 3 : 'c'} >>> d[1] 'a' >>> - Emil _________________________________________________________________ News, entertainment and everything you care about at Live.com. Get it now! http://www.live.com/getstarted.aspx From ktroell at mac.com Thu Jun 19 02:30:05 2008 From: ktroell at mac.com (Keith Troell) Date: Wed, 18 Jun 2008 19:30:05 -0500 Subject: [Tutor] Newbie: Sorting lists of lists Message-ID: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, 3, 2]] If I do a l.sort(), it sorts on the first element of each listed list: >>> l.sort() >>> l [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] How can I sort on the second or third elements of the listed lists? Keith A++ G++ PKR+ !PEG- B++ TB ADB- M+++ CHOW++ http://zbigniew.pyrzqxgl.com/bargegeek.html From john at fouhy.net Thu Jun 19 02:50:47 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Jun 2008 12:50:47 +1200 Subject: [Tutor] Newbie: Sorting lists of lists In-Reply-To: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> References: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> Message-ID: <5e58f2e40806181750r378de3b5v736e1609c3f703ff@mail.gmail.com> On 19/06/2008, Keith Troell wrote: > Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, > 3, 2]] > > If I do a l.sort(), it sorts on the first element of each listed list: > > >>> l.sort() > >>> l > [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] > > > How can I sort on the second or third elements of the listed lists? Use the key= option in sort, together with the operator module: >>> l = [[1,2,3], [2,3,1], [3,2,1], [1,3,2]] >>> import operator >>> l.sort(key=operator.itemgetter(1)) >>> l [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] >>> l.sort(key=operator.itemgetter(2)) >>> l [[3, 2, 1], [2, 3, 1], [1, 3, 2], [1, 2, 3]] >>> operator.itemgetter(i) is basically equivalent to a function defined as follows: def f(lst): return lst[i] If you have an old version of python, this may not work. As an alternative, try googling for "decorate-sort-undecorate". -- John. From kent37 at tds.net Thu Jun 19 02:54:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jun 2008 20:54:04 -0400 Subject: [Tutor] Newbie: Sorting lists of lists In-Reply-To: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> References: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> Message-ID: <1c2a2c590806181754g3f1c5e3em677ab4ee8df3a192@mail.gmail.com> On Wed, Jun 18, 2008 at 8:30 PM, Keith Troell wrote: > Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, > 3, 2]] > > If I do a l.sort(), it sorts on the first element of each listed list: > >>>> l.sort() >>>> l > [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] > > > How can I sort on the second or third elements of the listed lists? Use the key= parameter of sort to specify the sort key. operator.itemgetter is convenient for the actual key: In [3]: from operator import itemgetter In [4]: l.sort(key=itemgetter(1)) In [5]: l Out[5]: [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] A longer explanation is here: http://personalpages.tds.net/~kent37/kk/00007.html Kent From forrest.yu at gmail.com Thu Jun 19 04:48:50 2008 From: forrest.yu at gmail.com (Forrest Y. Yu) Date: Thu, 19 Jun 2008 10:48:50 +0800 Subject: [Tutor] Newbie: Sorting lists of lists Message-ID: > > Message: 8 > Date: Wed, 18 Jun 2008 19:30:05 -0500 > From: Keith Troell > Subject: [Tutor] Newbie: Sorting lists of lists > To: tutor at python.org > Message-ID: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165 at mac.com> > Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed > > Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, > 1], [1, 3, 2]] > > If I do a l.sort(), it sorts on the first element of each listed list: > > >>> l.sort() > >>> l > [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] > > > How can I sort on the second or third elements of the listed lists? I know, it's NOT beautiful code, but it seems work. If you have no better way, try this: """Sort on the second elements.""" def xchg12(l) : for m in l: m[0], m[1] = m[1], m[0] l = [[1, 2, 3], [2, 3, 1], [3, 2,1], [1, 3, 2]] print l xchg12(l) l.sort() xchg12(l) print l Yuan (yet unlovely another newbie) > > Keith > > A++ G++ PKR+ !PEG- B++ TB ADB- M+++ CHOW++ > http://zbigniew.pyrzqxgl.com/bargegeek.html > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 52, Issue 51 > ************************************* > -- Fran Lebowitz - "You're only has good as your last haircut." -------------- next part -------------- An HTML attachment was scrubbed... URL: From snovak at snovak.com Thu Jun 19 05:29:59 2008 From: snovak at snovak.com (Sean Novak) Date: Wed, 18 Jun 2008 23:29:59 -0400 Subject: [Tutor] compiling python Message-ID: <1034CD30-598F-4D79-A206-AE91B19A9232@snovak.com> Hello Python Guru's and Newbies alike. I've been able to write a bit of Python for a web app that works wonderfully on my dev machine. However, I have limited access to the machine that will actually host this app. Will compiling a Python program eliminate library dependency requirements for the host machine? Essentially, are the libraries compiled into the binary? I have little knowledge about compiling for Python, other than a glimmer of a memory that I read about it once. Thanks all, Sean From washakie at gmail.com Thu Jun 19 08:44:03 2008 From: washakie at gmail.com (John [H2O]) Date: Wed, 18 Jun 2008 23:44:03 -0700 (PDT) Subject: [Tutor] re adlines, read, and my own get_contents() Message-ID: <17998300.post@talk.nabble.com> I've defined: def get_contents(infile=file_object): """ return a list of lines from a file """ contents=infile.read() contents = contents.strip().split('\n') return contents then there's also: file_object.read() and file_object.readlines() and file_object.readline() I think I understand the differences, but can someone tell me if there's any difference between what I define and the readlines() method? -john -- View this message in context: http://www.nabble.com/readlines%2C-read%2C-and-my-own-get_contents%28%29-tp17998300p17998300.html Sent from the Python - tutor mailing list archive at Nabble.com. From muchanek at gmail.com Thu Jun 19 09:39:08 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Thu, 19 Jun 2008 10:39:08 +0300 Subject: [Tutor] Two dimesional array In-Reply-To: References: Message-ID: <1213861149.6494.24.camel@www.kinuthia.com> On Thu, 2008-06-19 at 02:30 +0200, tutor-request at python.org wrote: > Message: 2 > Date: Wed, 18 Jun 2008 19:43:21 +0530 > From: "amit sethi" > Subject: [Tutor] (no subject) > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hi , Could you please tell me , how i can traverse a two dimensional >>> from numpy import * # import the necessary module > >>> arry = array((1,2,3,4)) # create a rank-one array > >>> print arry > [1 2 3 4] > >>> print arry.shape > (4,) # this means it is a rank 1 array with a length of 4 (the trailing comma means it is a tuple) > > To get to the first element in the array: > print arry[0] > 1 > > To get to the last element: > >>> print arry[-1] > 4 > >>> > > >>> arry2 = array(([5,6,7,8],[9,10,11,12])) # create a a rank-two array, two-dimensional, if wish > >>> print arry2 > [[ 5 6 7 8] > [ 9 10 11 12]] > >>> print arry2.shape # > (2, 4) # this means that it is a rank 2 (ie 2-dimensional) array, with each axis having a length of 4 > >>> > To get to the first element in the first axis: > >>> print arry2[0,0] > 5 > To get to the last element in the second axis: > >>> print arry2[1,-1] > 12 > > Does this help? > Kinuthia... From kent37 at tds.net Thu Jun 19 11:29:25 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jun 2008 05:29:25 -0400 Subject: [Tutor] Newbie: Sorting lists of lists In-Reply-To: References: Message-ID: <1c2a2c590806190229u5189d58o2a36071ba3b7378e@mail.gmail.com> On Wed, Jun 18, 2008 at 10:48 PM, Forrest Y. Yu wrote: > I know, it's NOT beautiful code, but it seems work. If you have no better > way, try this: > > """Sort on the second elements.""" > def xchg12(l) : > for m in l: > m[0], m[1] = m[1], m[0] > > l = [[1, 2, 3], [2, 3, 1], [3, 2,1], [1, 3, 2]] > print l > xchg12(l) > l.sort() > xchg12(l) > print l This is not too far from the decorate-sort-undecorate idiom which used to be the standard way to do something like this. Instead of modifying the elements of the original list, create a new list whose elements are the key and the item from the old list, and sort that: In [6]: l = [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, 3, 2]] In [7]: m = [ (i[1], i) for i in l ] In [8]: m.sort() In [9]: m Out[9]: [(2, [1, 2, 3]), (2, [3, 2, 1]), (3, [1, 3, 2]), (3, [2, 3, 1])] In [10]: l = [ i[1] for i in m ] In [11]: l Out[11]: [[1, 2, 3], [3, 2, 1], [1, 3, 2], [2, 3, 1]] Kent From kent37 at tds.net Thu Jun 19 11:32:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jun 2008 05:32:53 -0400 Subject: [Tutor] compiling python In-Reply-To: <1034CD30-598F-4D79-A206-AE91B19A9232@snovak.com> References: <1034CD30-598F-4D79-A206-AE91B19A9232@snovak.com> Message-ID: <1c2a2c590806190232h7e25c42cua561ee608a6fdb14@mail.gmail.com> On Wed, Jun 18, 2008 at 11:29 PM, Sean Novak wrote: > Hello Python Guru's and Newbies alike. I've been able to write a bit of > Python for a web app that works wonderfully on my dev machine. However, I > have limited access to the machine that will actually host this app. Will > compiling a Python program eliminate library dependency requirements for the > host machine? Essentially, are the libraries compiled into the binary? You can use py2exe or py2app to create an executable that includes the libraries. This is not compiling, it is more a packaging step. You may also be able to include the libraries in the same directory as your app. What kind of access do you have to the host? What libraries do you need? Kent From kent37 at tds.net Thu Jun 19 11:37:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jun 2008 05:37:20 -0400 Subject: [Tutor] re adlines, read, and my own get_contents() In-Reply-To: <17998300.post@talk.nabble.com> References: <17998300.post@talk.nabble.com> Message-ID: <1c2a2c590806190237i651e1e46l21960a5cd88a881b@mail.gmail.com> On Thu, Jun 19, 2008 at 2:44 AM, John [H2O] wrote: > > I've defined: > > def get_contents(infile=file_object): > """ return a list of lines from a file """ > contents=infile.read() > contents = contents.strip().split('\n') > return contents > I think I understand the differences, but can someone tell me if there's any > difference between what I define and the readlines() method? readline() and readlines() include the trailing newline in the lines they return; your function does not. readline() and readlines() don't strip leading and trailing space. contents = contents.splitlines(True) would duplicate readlines() I think. Kent From kent37 at tds.net Thu Jun 19 13:57:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jun 2008 07:57:44 -0400 Subject: [Tutor] compiling python In-Reply-To: <352DE849-BC55-4E57-808D-887D4C62F084@snovak.com> References: <1034CD30-598F-4D79-A206-AE91B19A9232@snovak.com> <1c2a2c590806190232h7e25c42cua561ee608a6fdb14@mail.gmail.com> <352DE849-BC55-4E57-808D-887D4C62F084@snovak.com> Message-ID: <1c2a2c590806190457i78bbcce8oe56adff8e783c6e8@mail.gmail.com> On Thu, Jun 19, 2008 at 7:11 AM, Sean Novak wrote: > missed answering that last part before I sent the email. > > import urllib > import libxml2dom > import xml.dom.ext urllib is part of the standard lib. Perhaps you could replace the xml libs with something that is in the standard lib, for example xml.etree.ElementTree if you are using Python 2.5. Kent From metolone+gmane at gmail.com Thu Jun 19 17:05:34 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 19 Jun 2008 08:05:34 -0700 Subject: [Tutor] Newbie: Sorting lists of lists References: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165@mac.com> <1c2a2c590806181754g3f1c5e3em677ab4ee8df3a192@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590806181754g3f1c5e3em677ab4ee8df3a192 at mail.gmail.com... > On Wed, Jun 18, 2008 at 8:30 PM, Keith Troell wrote: >> Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], >> [1, >> 3, 2]] >> >> If I do a l.sort(), it sorts on the first element of each listed list: >> >>>>> l.sort() >>>>> l >> [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] >> >> >> How can I sort on the second or third elements of the listed lists? > > Use the key= parameter of sort to specify the sort key. > operator.itemgetter is convenient for the actual key: > > In [3]: from operator import itemgetter > In [4]: l.sort(key=itemgetter(1)) > In [5]: l > Out[5]: [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] > > A longer explanation is here: > http://personalpages.tds.net/~kent37/kk/00007.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You can use a lambda that builds the key you want to sort on from the original element: >>> L=[[1,2,3],[2,3,1],[3,2,1],[1,3,2]] Sort on 2nd value: >>> sorted(L,key=lambda x: x[1]) [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] Sort on 2nd, then by 3rd value >>> sorted(L,key=lambda x: (x[1],x[2])) [[3, 2, 1], [1, 2, 3], [2, 3, 1], [1, 3, 2]] -Mark From eric at ericabrahamsen.net Thu Jun 19 15:50:01 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Thu, 19 Jun 2008 21:50:01 +0800 Subject: [Tutor] inheritance/classmethods/metaclasses Message-ID: I'm probably in over my head here, but I really want to know how this works, and I hope someone will be willing to take a moment to explain it... I'm making a few classes for a very simple ORM, where the classes reflect objects that I'm persisting via pickle. I'd like to add and delete instances via add() and delete() classmethods, so that the classes can keep track of the comings and goings of their instances. My main question is, how can I abstract this classmethod behavior for several classes, either into a metaclass, or a super class? I've done some very scary reading, and some fruitless experimentation, and am over my head. I know the answer is probably "do something else entirely", but I'd really like to know how this is supposed to work. What I'd like is a Model class, which provides an add() classmethod like this: class Model(object): @classmethod def add(cls, *args) inst = cls(args) cls.instances.append(inst) Then, say, a File class: class File(): # inherit from Model, or use Model as a metaclass? instances = [] def __init__(self, *args) self.filename = args[0] self.keyword = args[1] The desired behavior, of course, is this: File.add('somefilename','keywordforthisfile') and to be able to extend this behavior to other classes. Any pointers would be much appreciated... Eric From kent37 at tds.net Thu Jun 19 17:44:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jun 2008 11:44:52 -0400 Subject: [Tutor] inheritance/classmethods/metaclasses In-Reply-To: References: Message-ID: <1c2a2c590806190844h496ac312y7d8769dd9f6ec644@mail.gmail.com> On Thu, Jun 19, 2008 at 9:50 AM, Eric Abrahamsen wrote: > I'm making a few classes for a very simple ORM, where the classes reflect > objects that I'm persisting via pickle. I'd like to add and delete instances > via add() and delete() classmethods, so that the classes can keep track of > the comings and goings of their instances. What you have almost works. Try this: class Model(object): @classmethod def add(cls, *args): inst = cls(*args) cls.instances.append(inst) class File(Model): instances = [] def __init__(self, *args): self.filename = args[0] self.keyword = args[1] File.add('somefilename','keywordforthisfile') print File.instances You have to define instances in each class; a metaclass could do that for you. Anyway I hope this gets you a little farther. Kent From zmanji at gmail.com Thu Jun 19 20:56:50 2008 From: zmanji at gmail.com (Zameer Manji) Date: Thu, 19 Jun 2008 14:56:50 -0400 Subject: [Tutor] Learning Python from books Message-ID: <485AABF2.1030208@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Has anyone here attempted to learn Python from books ? I recently purchased "Learning Python" 3rd Edition (9780596513986) and if anyone here is a good bottom-up learner than it is the perfect book. The author goes over each feature in python, explaining it's syntax, usage and the "pythonic" way of using them in programs. It has really helped me understand some of the more powerful tools in python and I am sure it will make an excellent reference book in the future. With that said, has anyone else attempted to learn python from books and if so which one ? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) iQEcBAEBCgAGBQJIWqvxAAoJEA759sZQuQ1BS+kIAK+6TWqesUQjEQygwsMI3seU ZWUkd4wlextCOXIH6mse4TMHdAU3+NHDo1V4QwSYxNTEjwpWFr1Kg2BE0zyMyxPD gs8Kaov6/DGQgyFFt5DRcKvkQ0M5St7I/PuP+n/eelMUK1culvXx3oycKBqh8D21 R/g0SQ0M9pUDLuBEygbgjFw1WVsf/h8/zCc38qHQ+QOQvrVaEciV3I5JLyp3+u8g JyjzxjHSRHd4Ik4cnaeKa2OyFn5JaPXxPmrmPiE3WEWnJxLWucXAP/CEm7e9aamQ Fv4SYuVmOIGpbAqySgEpQH2yRsd+0qaNKSJq4hqjQ1/z2Bx6hM5LTqJAVjfZMW4= =9xVw -----END PGP SIGNATURE----- From titleistfour at gmail.com Thu Jun 19 23:39:54 2008 From: titleistfour at gmail.com (jay) Date: Thu, 19 Jun 2008 16:39:54 -0500 Subject: [Tutor] Learning Python from books In-Reply-To: <485AABF2.1030208@gmail.com> References: <485AABF2.1030208@gmail.com> Message-ID: <7c25bb490806191439n1d885a8fuaa451dce827a148a@mail.gmail.com> Me personally, both "Learning Python" and "Core Python Programming". I am by no means an expert, but both of these books are excellent and were quite helpful. jay On Thu, Jun 19, 2008 at 1:56 PM, Zameer Manji wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > Has anyone here attempted to learn Python from books ? I recently > purchased "Learning Python" 3rd Edition (9780596513986) and if anyone > here is a good bottom-up learner than it is the perfect book. The author > goes over each feature in python, explaining it's syntax, usage and the > "pythonic" way of using them in programs. It has really helped me > understand some of the more powerful tools in python and I am sure it > will make an excellent reference book in the future. With that said, has > anyone else attempted to learn python from books and if so which one ? > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (MingW32) > > iQEcBAEBCgAGBQJIWqvxAAoJEA759sZQuQ1BS+kIAK+6TWqesUQjEQygwsMI3seU > ZWUkd4wlextCOXIH6mse4TMHdAU3+NHDo1V4QwSYxNTEjwpWFr1Kg2BE0zyMyxPD > gs8Kaov6/DGQgyFFt5DRcKvkQ0M5St7I/PuP+n/eelMUK1culvXx3oycKBqh8D21 > R/g0SQ0M9pUDLuBEygbgjFw1WVsf/h8/zCc38qHQ+QOQvrVaEciV3I5JLyp3+u8g > JyjzxjHSRHd4Ik4cnaeKa2OyFn5JaPXxPmrmPiE3WEWnJxLWucXAP/CEm7e9aamQ > Fv4SYuVmOIGpbAqySgEpQH2yRsd+0qaNKSJq4hqjQ1/z2Bx6hM5LTqJAVjfZMW4= > =9xVw > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jasonbconner at gmail.com Fri Jun 20 01:01:25 2008 From: jasonbconner at gmail.com (Jason Conner) Date: Fri, 20 Jun 2008 11:01:25 +1200 Subject: [Tutor] Learning Python from books In-Reply-To: <7c25bb490806191439n1d885a8fuaa451dce827a148a@mail.gmail.com> References: <485AABF2.1030208@gmail.com> <7c25bb490806191439n1d885a8fuaa451dce827a148a@mail.gmail.com> Message-ID: I use the same books - Learning Python and Core Python Programming, 2nd ed. I found I got about halfway through Learning Python before I switched to CPP and had no problems. I also use "Python Phrasebook" (Brad Dayley, 2007) as a handy reference guide to some common problems as well. Core Python Programming, 2nd ed. (Wesley Chun, 2007) is my most frequent instructional guide, though. On Fri, Jun 20, 2008 at 9:39 AM, jay wrote: > Me personally, both "Learning Python" and "Core Python Programming". I am > by no means an expert, but both of these books are excellent and were quite > helpful. > > jay > > > On Thu, Jun 19, 2008 at 1:56 PM, Zameer Manji wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA512 >> >> Has anyone here attempted to learn Python from books ? I recently >> purchased "Learning Python" 3rd Edition (9780596513986) and if anyone >> here is a good bottom-up learner than it is the perfect book. The author >> goes over each feature in python, explaining it's syntax, usage and the >> "pythonic" way of using them in programs. It has really helped me >> understand some of the more powerful tools in python and I am sure it >> will make an excellent reference book in the future. With that said, has >> anyone else attempted to learn python from books and if so which one ? >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.7 (MingW32) >> >> iQEcBAEBCgAGBQJIWqvxAAoJEA759sZQuQ1BS+kIAK+6TWqesUQjEQygwsMI3seU >> ZWUkd4wlextCOXIH6mse4TMHdAU3+NHDo1V4QwSYxNTEjwpWFr1Kg2BE0zyMyxPD >> gs8Kaov6/DGQgyFFt5DRcKvkQ0M5St7I/PuP+n/eelMUK1culvXx3oycKBqh8D21 >> R/g0SQ0M9pUDLuBEygbgjFw1WVsf/h8/zCc38qHQ+QOQvrVaEciV3I5JLyp3+u8g >> JyjzxjHSRHd4Ik4cnaeKa2OyFn5JaPXxPmrmPiE3WEWnJxLWucXAP/CEm7e9aamQ >> Fv4SYuVmOIGpbAqySgEpQH2yRsd+0qaNKSJq4hqjQ1/z2Bx6hM5LTqJAVjfZMW4= >> =9xVw >> -----END PGP SIGNATURE----- >> _______________________________________________ >> 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 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lowelltackett at yahoo.com Fri Jun 20 06:19:38 2008 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 19 Jun 2008 21:19:38 -0700 (PDT) Subject: [Tutor] Learning Python from books In-Reply-To: <485AABF2.1030208@gmail.com> Message-ID: <775037.10581.qm@web45904.mail.sp1.yahoo.com> "Python Programming [for the absolute beginner]" by Michael Dawson is-in my humble opinion-a programming pedagogical pacesetter. >From the virtual desk of Lowell Tackett --- On Thu, 6/19/08, Zameer Manji wrote: > From: Zameer Manji > Subject: [Tutor] Learning Python from books > To: "Python Tutor mailing list" > Date: Thursday, June 19, 2008, 2:56 PM > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > Has anyone here attempted to learn Python from books ? I > recently > purchased "Learning Python" 3rd Edition > (9780596513986) and if anyone > here is a good bottom-up learner than it is the perfect > book. The author > goes over each feature in python, explaining it's > syntax, usage and the > "pythonic" way of using them in programs. It has > really helped me > understand some of the more powerful tools in python and I > am sure it > will make an excellent reference book in the future. With > that said, has > anyone else attempted to learn python from books and if so > which one ? > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (MingW32) > > iQEcBAEBCgAGBQJIWqvxAAoJEA759sZQuQ1BS+kIAK+6TWqesUQjEQygwsMI3seU > ZWUkd4wlextCOXIH6mse4TMHdAU3+NHDo1V4QwSYxNTEjwpWFr1Kg2BE0zyMyxPD > gs8Kaov6/DGQgyFFt5DRcKvkQ0M5St7I/PuP+n/eelMUK1culvXx3oycKBqh8D21 > R/g0SQ0M9pUDLuBEygbgjFw1WVsf/h8/zCc38qHQ+QOQvrVaEciV3I5JLyp3+u8g > JyjzxjHSRHd4Ik4cnaeKa2OyFn5JaPXxPmrmPiE3WEWnJxLWucXAP/CEm7e9aamQ > Fv4SYuVmOIGpbAqySgEpQH2yRsd+0qaNKSJq4hqjQ1/z2Bx6hM5LTqJAVjfZMW4= > =9xVw > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From eric at ericabrahamsen.net Fri Jun 20 06:32:02 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Fri, 20 Jun 2008 12:32:02 +0800 Subject: [Tutor] inheritance/classmethods/metaclasses In-Reply-To: <1c2a2c590806190844h496ac312y7d8769dd9f6ec644@mail.gmail.com> References: <1c2a2c590806190844h496ac312y7d8769dd9f6ec644@mail.gmail.com> Message-ID: <28DC7859-B4A9-4A9C-8FCC-C1C0B4664C9D@ericabrahamsen.net> > What you have almost works. Try this: No kidding ? that's what I get for wild stabs in the dark, I thought I'd tried that. I'm pleased that it really is that simple (and that, whatever metaclasses are used for, I don't need to worry about them yet). Thanks! Eric (Grrr, bit by the reply-to bug. Not that this is really worth re- posting...) From timovwb at gmail.com Fri Jun 20 09:39:51 2008 From: timovwb at gmail.com (Timo) Date: Fri, 20 Jun 2008 09:39:51 +0200 Subject: [Tutor] Checking the desktop environment Message-ID: <485b5ea5.1636440a.75f1.ffffacc6@mx.google.com> Hello all, in my program I need to know what desktop environment the user is running. I figured this piece of code works, but apparently not on every Linux distro. On Ubuntu it did the trick, but then I heard of someone who runs SLiM that he get's an error with this. if os.environ['DESKTOP_SESSION'].startswith('kde'): print "Running KDE" So, does anyone know a water-proof solution for desktop environment checking? Timo From kent37 at tds.net Fri Jun 20 12:39:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jun 2008 06:39:01 -0400 Subject: [Tutor] Learning Python from books In-Reply-To: <485AABF2.1030208@gmail.com> References: <485AABF2.1030208@gmail.com> Message-ID: <1c2a2c590806200339l34b915faic996c3feb8656a4f@mail.gmail.com> On Thu, Jun 19, 2008 at 2:56 PM, Zameer Manji wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > Has anyone here attempted to learn Python from books ? I learned Python from Learning Python and Python Cookbook initially. Also lots of practice. Reading comp.lang.python is another good way to learn. Kent From trutch at gmail.com Fri Jun 20 16:04:14 2008 From: trutch at gmail.com (Tyler Rutschman) Date: Fri, 20 Jun 2008 09:04:14 -0500 Subject: [Tutor] Using Regex from Configuration File Message-ID: Hello everyone, I'm new to python and have set up a program to parse through reports. The script has started very basic and I've been folding in additional features as it moves along. What it does is takes a specified log file (exported from splunk) and parses through it with a regex specific to the type of log. It is invoked by: ./extract -f filename -c config I've successfully set up ConfigParser to go through the config and apply the proper configuration to the script, but I'm having trouble getting the regex to work. It worked successfully when I declared it within the script. ---------------- code ---------------- def load_config(): configdict = ConfigParser() configdict.read('report.conf') conf=main()[0] opt_name = configdict.get(conf,'name') opt_regex = configdict.get(conf,'regex') return opt_name,opt_regex ... rawstr="r"+"\"\"\""+load_config()[1]+"\"\"\"" ... rxinput = re.compile(rawstr) ---------------- code ---------------- full code here http://codepad.org/pva1dE1i configuration here http://codepad.org/VnXfQhBi Any help would be appreciated. Thanks, Tyler -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 20 16:36:05 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jun 2008 10:36:05 -0400 Subject: [Tutor] Using Regex from Configuration File In-Reply-To: References: Message-ID: <1c2a2c590806200736m3c807c6fm1abf9882fe80012d@mail.gmail.com> On Fri, Jun 20, 2008 at 10:04 AM, Tyler Rutschman wrote: > I've successfully set up ConfigParser to go through the config and apply the > proper configuration to the script, but I'm having trouble getting the regex > to work. It worked successfully when I declared it within the script. > > ---------------- code ---------------- > def load_config(): > configdict = ConfigParser() > configdict.read('report.conf') > conf=main()[0] > opt_name = configdict.get(conf,'name') > opt_regex = configdict.get(conf,'regex') > return opt_name,opt_regex > ... > rawstr="r"+"\"\"\""+load_config()[1]+"\"\"\"" Leave this out, just use the string from load_config() directly. the r""" """ around the string are Python syntax, they should not be part of the actual string. Kent > ... > rxinput = re.compile(rawstr) > ---------------- code ---------------- > > full code here http://codepad.org/pva1dE1i > configuration here http://codepad.org/VnXfQhBi > > Any help would be appreciated. > > Thanks, > Tyler > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From chiennguyen at yahoo.com Fri Jun 20 18:46:13 2008 From: chiennguyen at yahoo.com (Chien Nguyen) Date: Fri, 20 Jun 2008 09:46:13 -0700 (PDT) Subject: [Tutor] Help! Character conversion from a rtf file. Message-ID: <437481.9221.qm@web35606.mail.mud.yahoo.com> Hi All, I am a newbie to Python. I just did some readings on the web and got some basic understanding about the language. I'd like to learn the language by writing some simple programs rather than keep reading books. My first program will convert certain uni-code characters (let's say UTF-8) in an RTF file format based on a certain mapping in another RTF file that is called a "RTF Control file". On each line of the Control file, there are 2 tokens separate by a TAB or a space. The first token contains the character that needs to be converted from, and the second character contains the character that needs to be converted to. The program will write to a new file that contains a new set of mapped characters. If a character form the original file is not found in the Control file, then the program just write the same character to the new file. For an example: The RTF Control file may contain the following lines. ? ? ? ? ? ? The original RTF file may have something like t?c m?m th? and will be converted to a new RTF file as follows. t?c m?m th? Before I start to go into the coding, I would like to get some advice from experienced users/mentors about a quick way to do it. Thanks in advance! -Chien Nguyen -------------- next part -------------- An HTML attachment was scrubbed... URL: From trutch at gmail.com Fri Jun 20 19:11:41 2008 From: trutch at gmail.com (Tyler Rutschman) Date: Fri, 20 Jun 2008 12:11:41 -0500 Subject: [Tutor] How to set up dispatch function Message-ID: Hello again everyone, I'm trying to add another fold into my log reporting script. I would like to set up a dispatch function to find the proper report format for the indicated configuration. The function would need to recognize the configuration and call a function that will parse the data and generate a report. I've only made one type of report thus far but would like to get this part ironed out before adding more. Any suggestions? source code http://codepad.org/VyTAcuji Thanks, Tyler -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 20 19:34:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Jun 2008 18:34:49 +0100 Subject: [Tutor] Checking the desktop environment References: <485b5ea5.1636440a.75f1.ffffacc6@mx.google.com> Message-ID: "Timo" wrote > Hello all, in my program I need to know what desktop environment the > user is running. A few years ago I would have said that meant you had a broken design since it was very bad practice for any program to depend on the users environment. nfortunately recent developments in Linux/X mean that the whole concept is broken that one more environmentally wawre program probably is no big deal! But there are caveats that mean you will probably never get it right in every case. The best you cvan probably do is detect if the environment is one of a fixed set known to work with your code.# But bear in mind that the user can switch envirojnemts while your code is running, or may even be runningmultiple environments simultaneously on virtual windows etc. Thats why the users environment should be left as as something for the user and the programming environment for the programmer. > I figured this piece of code works, but apparently not > on every Linux distro. On Ubuntu it did the trick, but then I heard > of > someone who runs SLiM that he get's an error with this. > > if os.environ['DESKTOP_SESSION'].startswith('kde'): > print "Running KDE" That would only find out if KDE was beiong used and only if the user (or cofig scripts) has not modified the variable. > So, does anyone know a water-proof solution for desktop environment > checking? I don't think such a thing can exist on a Unix/X system. An approximation will be the best you can get. Can you explain why you need to know? In most situations there should be a generic way to do it. Alan G. From alan.gauld at btinternet.com Fri Jun 20 19:37:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Jun 2008 18:37:34 +0100 Subject: [Tutor] How to set up dispatch function References: Message-ID: "Tyler Rutschman" wrote > set up a dispatch function to find the proper report format for the > indicated configuration. Sounds like a job for a dictionary. Just find the key and access the corresponding function. Do you know how to do that? (Use a dictionary to strore functions?) or is it the derivation of the key thats the issue? Alan G From Tse.William at ic.gc.ca Fri Jun 20 19:19:02 2008 From: Tse.William at ic.gc.ca (Tse, William: #CIPO - OPIC) Date: Fri, 20 Jun 2008 13:19:02 -0400 Subject: [Tutor] Python and SOAP Web Services Message-ID: <5A66F7B6A4EF084F9D22810BED690A610A8BBB65@msg-mb1.icent.ic.gc.ca> I am trying to use a SOAP Web Service with Python 2.5 and I'm following the instructions in Chapter 12 of the "Diving into Python" tutorial. It refers to three libraries that I'm having problems accessing or that appear out of date : PyXML, fpconst and SOAPpy. The tutorial also seems to be for Python 2.4 (which I've also tried using unsuccessfully for web services). Is there an updated manual or procedures that I can follow ? Thanks, Will -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 20 20:21:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jun 2008 14:21:32 -0400 Subject: [Tutor] Help! Character conversion from a rtf file. In-Reply-To: <437481.9221.qm@web35606.mail.mud.yahoo.com> References: <437481.9221.qm@web35606.mail.mud.yahoo.com> Message-ID: <1c2a2c590806201121x44d5efeaxb64c2bc7de091cf5@mail.gmail.com> On Fri, Jun 20, 2008 at 12:46 PM, Chien Nguyen wrote: > Hi All, > I am a newbie to Python. I just did some readings on the web > and got some basic understanding about the language. I'd like > to learn the language by writing some simple programs rather than > keep reading books. My first program will convert certain uni-code > characters > (let's say UTF-8) in an RTF file format based on a certain mapping > in another RTF file that is called a "RTF Control file". On each line > of the Control file, there are 2 tokens separate by a TAB or a space. That doesn't sound like an RTF file, more like UTF-8 text. > The first token contains the character that needs to be converted from, > and the second character contains the character that needs to be converted > to. > > The program will write to a new file that contains a new set of mapped > characters. > If a character form the original file is not found in the Control file, then > the program > just write the same character to the new file. Hopefully your reading has shown you the way to read and write files. Look at the codecs module for reading and writing UTF-8 files. Once you have the file data loaded you can use the replace method of the data to change the characters. Something like this (*very rough*) import codecs data = codecs.open('data.rtf', 'r', 'utf-8').read() replacements = codecs.open('replace.rtf', 'r', 'utf-8') for line in replacements: line = line.strip() if line: from, to = line.split() data.replace(from, to) f = codecs.open('newdata.rtf', 'w', 'utf-8') f.write(data) f.close() HTH, Kent From bgailer at gmail.com Fri Jun 20 20:27:34 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Jun 2008 14:27:34 -0400 Subject: [Tutor] Help! Character conversion from a rtf file. In-Reply-To: <437481.9221.qm@web35606.mail.mud.yahoo.com> References: <437481.9221.qm@web35606.mail.mud.yahoo.com> Message-ID: <485BF696.6050305@gmail.com> Chien Nguyen wrote: > Hi All, > I am a newbie to Python. I just did some readings on the web > and got some basic understanding about the language. I'd like > to learn the language by writing some simple programs rather than > keep reading books. My first program will convert certain uni-code > characters > (let's say UTF-8) in an RTF file format based on a certain mapping > in another RTF file that is called a "RTF Control file". On each line > of the Control file, there are 2 tokens separate by a TAB or a space. > The first token contains the character that needs to be converted from, > and the second character contains the character that needs to be > converted to. > > The program will write to a new file that contains a new set of mapped > characters. > If a character form the original file is not found in the Control > file, then the program > just write the same character to the new file. > For an example: The RTF Control file may contain the following lines. > > ? ? > ? ? > ? ? > > The original RTF file may have something like > t?c m?m th? > > and will be converted to a new RTF file as follows. > t?c m?m th? > > Before I start to go into the coding, I would like to get some advice > from > experienced users/mentors about a quick way to do it. Quick - do you mean time to code, or execution time? For each line in the control file add an item to a dictionary, with old value as key and new value as value. For each line in the data file For each character in the line if in dictionary replace with corresponding value write line to output. -- Bob Gailer 919-636-4239 Chapel Hill, NC From washakie at gmail.com Fri Jun 20 20:37:04 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 20 Jun 2008 11:37:04 -0700 (PDT) Subject: [Tutor] os.waitpid non spawned pid Message-ID: <18035187.post@talk.nabble.com> Hello, I would like to write a script that would have a command line option of a pid# (known ahead of time). Then I want my script to wait to execute until the pid is finished. How do I accomplish this? I tried the following: #!/usr/bin/env python import os import sys def run_cmd(cmd): """RUN A BASH CMD""" import subprocess as sub p = sub.Popen( ['/bin/bash' , '-c' , cmd ], stdout = sub.PIPE , stderr = sub.STDOUT ) output = p.stdout.read() return output r=os.waitpid(sys.argv[1],0); cmd = 'echo "Now %s has finished " ' %r run_cmd(cmd) But I get the following: -bash-3.1$ ./waitpid.py 10132 Traceback (most recent call last): File "./waitpid.py", line 14, in ? r=os.waitpid(int(sys.argv[1]),0); OSError: [Errno 10] No child processes -- View this message in context: http://www.nabble.com/os.waitpid-non-spawned-pid-tp18035187p18035187.html Sent from the Python - tutor mailing list archive at Nabble.com. From timovwb at gmail.com Fri Jun 20 20:48:49 2008 From: timovwb at gmail.com (Timo) Date: Fri, 20 Jun 2008 20:48:49 +0200 Subject: [Tutor] Checking the desktop environment In-Reply-To: References: <485b5ea5.1636440a.75f1.ffffacc6@mx.google.com> Message-ID: <485bfb70.1def600a.3adc.20cd@mx.google.com> Thanks for your explanation. Apparently it's not possible to detect it in all cases, but it would be nice to detect it for regular users, so people who have a default install. Well, my program needs a text-editor and a graphical box for root-password. So it checks for the desktop environment so it could set these things to gedit and gksudo for Gnome and kate and kdesu for KDE. Timo Alan Gauld schreef: > "Timo" wrote > >> Hello all, in my program I need to know what desktop environment the >> user is running. > > A few years ago I would have said that meant you had a broken > design since it was very bad practice for any program to depend > on the users environment. nfortunately recent developments in > Linux/X mean that the whole concept is broken that one more > environmentally wawre program probably is no big deal! > > But there are caveats that mean you will probably never get > it right in every case. The best you cvan probably do is detect > if the environment is one of a fixed set known to work with > your code.# > > But bear in mind that the user can switch envirojnemts while > your code is running, or may even be runningmultiple > environments simultaneously on virtual windows etc. > > Thats why the users environment should be left as as > something for the user and the programming environment > for the programmer. > >> I figured this piece of code works, but apparently not >> on every Linux distro. On Ubuntu it did the trick, but then I heard of >> someone who runs SLiM that he get's an error with this. >> >> if os.environ['DESKTOP_SESSION'].startswith('kde'): >> print "Running KDE" > > That would only find out if KDE was beiong used and only > if the user (or cofig scripts) has not modified the variable. > >> So, does anyone know a water-proof solution for desktop environment >> checking? > > I don't think such a thing can exist on a Unix/X system. An > approximation will be the best you can get. > > Can you explain why you need to know? > In most situations there should be a generic way to do it. > > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Fri Jun 20 21:40:56 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 20 Jun 2008 12:40:56 -0700 Subject: [Tutor] Help! Character conversion from a rtf file. In-Reply-To: <437481.9221.qm@web35606.mail.mud.yahoo.com> References: <437481.9221.qm@web35606.mail.mud.yahoo.com> Message-ID: <78b3a9580806201240w183a1f4dk64ad032a541bd2f5@mail.gmail.com> > I'd like to learn the language by writing some simple programs rather than > keep reading books. My first program will convert certain uni-code characters > (let's say UTF-8) in an RTF file format based on a certain mapping > in another RTF file that is called a "RTF Control file". > : > The program will write to a new file that contains a new set of mapped characters. > If a character form the original file is not found in the Control file, then the program > just write the same character to the new file. hi chien, and welcome to Python! the Tutor list is here to help with any learning questions you may have, but keep in mind that we cannot help you with providing solutions to what we feel are education, high school, college, or university course homework assignments, which is what your problem sounds like. the best advice i have for you at this time is to read in the translation mapping into a Python dictionary, and then perform a byte-to-byte traversal and conversion from the source file to the destination file. best of luck on your project! -- 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 srilyk at gmail.com Fri Jun 20 23:39:22 2008 From: srilyk at gmail.com (W W) Date: Fri, 20 Jun 2008 16:39:22 -0500 Subject: [Tutor] Checking the desktop environment In-Reply-To: <485bfb70.1def600a.3adc.20cd@mx.google.com> References: <485b5ea5.1636440a.75f1.ffffacc6@mx.google.com> <485bfb70.1def600a.3adc.20cd@mx.google.com> Message-ID: <333efb450806201439r48fdc305off277ad8979ddc6d@mail.gmail.com> On Fri, Jun 20, 2008 at 1:48 PM, Timo wrote: > Thanks for your explanation. Apparently it's not possible to detect it > in all cases, but it would be nice to detect it for regular users, so > people who have a default install. > > Well, my program needs a text-editor and a graphical box for > root-password. So it checks for the desktop environment so it could set > these things to gedit and gksudo for Gnome and kate and kdesu for KDE. > > Timo I would probably just ask the user which one they're running. It's probably the easiest way. -Wayne From chester_lab at fltg.net Fri Jun 20 23:47:57 2008 From: chester_lab at fltg.net (FT) Date: Fri, 20 Jun 2008 17:47:57 -0400 Subject: [Tutor] File Stream Assignment? Message-ID: <000801c8d321$b744cca0$0301a8c0@brucetower> Hi! I would like to know how a file can be open for a stream event? I ask this question because of the SAPI 5 save a wave file and the only way to do that is with a file stream. The file read is simple and uses the isfilename flag, but the save file I can not find in all my searches, at least for python. Bruce From alan.gauld at btinternet.com Sat Jun 21 02:00:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jun 2008 01:00:36 +0100 Subject: [Tutor] Checking the desktop environment References: <485b5ea5.1636440a.75f1.ffffacc6@mx.google.com> <485bfb70.1def600a.3adc.20cd@mx.google.com> Message-ID: "Timo" wrote > Well, my program needs a text-editor OK, That should be determined by checking the VISUAL environment variable which is the standard Unix value that a user should set to determine their preferred visual (ie full screen) text editor. The EDITOR environrnent variable controls the default editor in text mode., The standard defaults are vi and ed respectively. I used to set xemacs and vi... > graphical box for root-password. This is the sort of thing that I meant about modern Unices messing things up. Why on earth should anyone need a user environment specific su box. That should be a standard dialog controlled by the app and the user environment controlling the GUI aspects. Too many Windows programmers are working on Linux IMHO! ;-) This is exactly why I dislike both Gnome and KDE. The only good things about these is the provision of drag n drop protocols etc. If only they had stuck to that. > these things to gedit and gksudo for Gnome and kate and kdesu for > KDE. But to do so would be to ignore the users preferences if they have set their own choice in the "officially provided" variables. You are thus allowing the environment to dictate to users what tools they use rather than letting the user dictate the environment in the true Unix style. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cspears2002 at yahoo.com Sat Jun 21 02:44:15 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 20 Jun 2008 17:44:15 -0700 (PDT) Subject: [Tutor] dollarize.py Message-ID: <166802.89300.qm@web51605.mail.re2.yahoo.com> I'm working on an exercise from Core Python Programming. I need to create a function that takes a float value and returns the value as string rounded to obtain a financial amount. Basically, the function does this: dollarize(1234567.8901) returns-> $1,234,567,89 The function should allow for dollar signs, negative signs, and commas. This is what I have so far: def dollarize(amount): negative_sign = 0 if amount[0] == '$': amount = amount[1:] elif amount[0] == '-': negative_sign = 1 if amount[1] == '$': amount = amount[2:] else: amount = amount[1:] else: pass amount_list = amount.split(",") final_amount = "" for x in range(len(amount_list)): final_amount = final_amount + amount_list[x] dollar_float = float(final_amount) dollar_rounded = round(dollar_float,2) if negative_sign == 1: dollar_string = "-$%.2f" % dollar_rounded else: dollar_string = "$%.2f" % dollar_rounded return dollar_string amount = raw_input("Enter an amount: ") dollar_amount = dollarize(amount) print dollar_amount I strip off the symbols, break the string apart, convert it to a float, and then round it. I'm not sure how to add the commas back after the string has been converted to a rounded float value. Any hints? From tiagosaboga at gmail.com Sat Jun 21 03:34:43 2008 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Fri, 20 Jun 2008 22:34:43 -0300 Subject: [Tutor] Checking the desktop environment In-Reply-To: References: <485bfb70.1def600a.3adc.20cd@mx.google.com> Message-ID: <20080621013443.GB3901@localdomain> On Sat, Jun 21, 2008 at 01:00:36AM +0100, Alan Gauld wrote: > "Timo" wrote > >> graphical box for root-password. > > This is the sort of thing that I meant about modern Unices messing > things up. Why on earth should anyone need a user environment > specific su box. That should be a standard dialog controlled by the > app and the user environment controlling the GUI aspects. Too > many Windows programmers are working on Linux IMHO! ;-) FWIW, Debian tries to address this mess with a su-to-root script which tries to do the right thing, launching gksu, kdesu or simply su in a new xterm. Tiago Saboga. From mwalsh at groktech.org Sat Jun 21 05:22:14 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Fri, 20 Jun 2008 22:22:14 -0500 Subject: [Tutor] os.waitpid non spawned pid In-Reply-To: <18035187.post@talk.nabble.com> References: <18035187.post@talk.nabble.com> Message-ID: <485C73E6.5050403@groktech.org> John [H2O] wrote: > Hello, I would like to write a script that would have a command line option > of a pid# (known ahead of time). Then I want my script to wait to execute > until the pid is finished. How do I accomplish this? > > I tried the following: > #!/usr/bin/env python > > import os > import sys > > def run_cmd(cmd): > """RUN A BASH CMD""" > import subprocess as sub > p = sub.Popen( ['/bin/bash' , '-c' , cmd ], > stdout = sub.PIPE , stderr = sub.STDOUT ) > output = p.stdout.read() > return output > > r=os.waitpid(sys.argv[1],0); To approximate the behavior you're looking for, I've seen it suggested that you can send signal number 0 to a non-child process until you get a meaningful result. Never used this approach myself, but it might look something like this: import os, time def waitncpid(pid): while 1: try: os.kill(pid, 0) time.sleep(1) except OSError: break waitncpid(sys.argv[1]) Not sure what this would do on a windows machine. And, I suppose it is possible that your process could end, and another start with the same pid while sleeping between kill attempts, but this seems unlikely to me, YMMV. > > cmd = 'echo "Now %s has finished " ' %r > > run_cmd(cmd) HTH, Marty From kent37 at tds.net Sat Jun 21 05:47:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jun 2008 23:47:14 -0400 Subject: [Tutor] File Stream Assignment? In-Reply-To: <000801c8d321$b744cca0$0301a8c0@brucetower> References: <000801c8d321$b744cca0$0301a8c0@brucetower> Message-ID: <1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com> On Fri, Jun 20, 2008 at 5:47 PM, FT wrote: > I would like to know how a file can be open for a stream event? What is a stream event? > I ask this question because of the SAPI 5 save a wave file and the only > way to do that is with a file stream. The file read is simple and uses the > isfilename flag, but the save file I can not find in all my searches, at > least for python. I have no idea what you are talking about. Kent From mwalsh at groktech.org Sat Jun 21 06:02:01 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Fri, 20 Jun 2008 23:02:01 -0500 Subject: [Tutor] dollarize.py In-Reply-To: <166802.89300.qm@web51605.mail.re2.yahoo.com> References: <166802.89300.qm@web51605.mail.re2.yahoo.com> Message-ID: <485C7D39.9010800@groktech.org> Christopher Spears wrote: > I'm working on an exercise from Core Python Programming. I need to create a function that takes a float value and returns the value as string rounded to obtain a financial amount. Basically, the function does this: > > dollarize(1234567.8901) returns-> $1,234,567,89 > > I strip off the symbols, break the string apart, convert it to a float, and then round it. I'm not sure how to add the commas back after the string has been converted to a rounded float value. Any hints? > Quick and dirty attempt (and did I mention ugly?) ... def addcommas(f): """ This amounts to reversing everything left of the decimal, grouping by 3s, joining with commas, reversing and reassembling. """ # assumes type(f) == float left, right = ('%0.2f' % f).split('.') rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)] return ','.join(rleft)[::-1] + '.' + right I think you can also accomplish your broader goal with the locale module (python2.5), though I don't know it very well. import sys, locale def dollarize(s): s = ''.join([n for n in str(s) if n not in ('$', ',')]) if sys.platform == 'win32': lcl = 'US' else: # linux and mac? lcl = 'en_US.UTF8' locale.setlocale(locale.LC_MONETARY, lcl) return locale.currency(float(s), 1, 1) print dollarize(12345678.9999) # $12,345,679.00 print dollarize('123456780.0999') # $123,456,780.10 print dollarize('$12345670.9999') # $12,345,671.00 print dollarize('$12,345,678.123') # $12,345,678.12 HTH, Marty From wescpy at gmail.com Sat Jun 21 09:14:03 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 21 Jun 2008 00:14:03 -0700 Subject: [Tutor] dollarize.py In-Reply-To: <166802.89300.qm@web51605.mail.re2.yahoo.com> References: <166802.89300.qm@web51605.mail.re2.yahoo.com> Message-ID: <78b3a9580806210014t31c7521bi4be7dc91c707b52d@mail.gmail.com> > dollarize(1234567.8901) returns-> $1,234,567,89 > : > amount = raw_input("Enter an amount: ") > dollar_amount = dollarize(amount) > print dollar_amount the solution you're creating is *slightly* different than the original spec in the problem (Exercise 13-3). the argument to dollarize() is supposed to be a *float*, not a string. other than that, you're well on your way! also, be aware of the typo in the class skeleton provided on p. 619. the published changed the "`"s to "'"s on line 13. since the backtick quotes are going away in Python 3, i would just suggest changing "return `self.value`" to "return repr(self.value)". aside from this, the way i usually solve this problem is to save off the sign, round off the fraction/pennies, and then break it up into dollars and cents, then process the commas into the dollar amount, and finally merge everything back together with the sign and the $. best of luck! -- wesley ps. marty's use of locale is a great add-on to this problem. i've had some students go this distance and implement it in a similar way but not very often. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "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 chester_lab at fltg.net Sat Jun 21 10:04:54 2008 From: chester_lab at fltg.net (FT) Date: Sat, 21 Jun 2008 04:04:54 -0400 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower> <1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com> Message-ID: <000e01c8d375$82a2c980$0301a8c0@brucetower> On: Friday, June 20, 2008 11:47 PM Kent Johnson Wrote: On Fri, Jun 20, 2008 at 5:47 PM, FT wrote: > I would like to know how a file can be open for a stream event? What is a stream event? > I ask this question because of the SAPI 5 save a wave file and the only > way to do that is with a file stream. The file read is simple and uses the > isfilename flag, but the save file I can not find in all my searches, at > least for python. I have no idea what you are talking about. Kent Kent, This is what I got from the Microsoft SAPI web site. They have only code for C and VB and below is the VB version. I am trying to figure out where the stram gets assigned to the speak method for SAPI so a file can be saved. The following code illustrates how to speak a text file in a specific voice in Visual Basic. This example assumes a text file (ttstemp.txt) containing the text to be spoken already exists. ISpeechVoice.SpeakStream is used here to speak an SpFileStream that has been bound to the file. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create SAPI voice Set Voice = New SpVoice 'Assume that ttstemp.txt exists FileName = "c:\ttstemp.txt" 'Open the text file FileStream.Open FileName, SSFMOpenForRead, True 'Select Microsoft Sam voice Set Voice.voice = voice.GetVoices("Name=Microsoft Sam", "Language=409").Item(0) 'Speak the file stream Voice.SpeakStream FileStream 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing So, in this example it assigns a file stream to the file opened then connects to the SAPI Speak method to save it. But when I do that like they did above I get only the data spoken and the file with 0 bytes in it. I have tried looking everywhere for the file stream connection and can not seem to find the method to do so. Bruce From alan.gauld at btinternet.com Sat Jun 21 10:19:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jun 2008 09:19:08 +0100 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower><1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com> <000e01c8d375$82a2c980$0301a8c0@brucetower> Message-ID: "FT" wrote Caveat: I know nothing about MS SAPI. > The following code illustrates how to speak a text file > in a specific voice in Visual Basic. This example assumes > a text file (ttstemp.txt) containing the text to be spoken > already exists. ISpeechVoice.SpeakStream is used here > to speak an SpFileStream that > has been bound to the file. Notice this says nothing about writing to a file. > Dim FileName As String > Dim FileStream As New SpFileStream > Dim Voice As SpVoice > 'Create SAPI voice > Set Voice = New SpVoice > 'Assume that ttstemp.txt exists > FileName = "c:\ttstemp.txt" > 'Open the text file > FileStream.Open FileName, SSFMOpenForRead, True > 'Select Microsoft Sam voice > Set Voice.voice = voice.GetVoices("Name=Microsoft Sam", > "Language=409").Item(0) > 'Speak the file stream > Voice.SpeakStream FileStream > 'Close the Stream > FileStream.Close > 'Release the objects > Set FileStream = Nothing > Set Voice = Nothing And the code nowhere writes to a file. The only file mentioned is the one read. > So, in this example it assigns a file stream to the file opened then > connects to the SAPI Speak method to save it. No, it calls the Speak method to speak it. It never saves anything so far as I can see. > did above I get only the data spoken and the file with 0 bytes in > it. I'm not sure which file has zero bytes. I hope not the one being spoken! But it sounds to me like your code is doing what the VB code does. > I have tried looking everywhere for the file stream connection and > can > not seem to find the method to do so. I have no idea what you mean by this. Where are you looking? This is a COM object which is in the MS library. You will need to access it via PythonWin or ctypes or a Python wrapper of some sort. But the fact you are getting it to speak suggests you have succeeded in that already. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From chester_lab at fltg.net Sat Jun 21 11:34:26 2008 From: chester_lab at fltg.net (FT) Date: Sat, 21 Jun 2008 05:34:26 -0400 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower><1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com><000e01c8d375$82a2c980$0301a8c0@brucetower> Message-ID: <001d01c8d382$0c943d70$0301a8c0@brucetower> Alan Gauld Wrote: "FT" wrote Caveat: I know nothing about MS SAPI. > The following code illustrates how to speak a text file > in a specific voice in Visual Basic. This example Notice this says nothing about writing to a file. > Dim FileName As String > Dim FileStream As New SpFileStream > Dim Voice As SpVoice > 'Create SAPI voice And the code nowhere writes to a file. The only file mentioned is the one read. No, it calls the Speak method to speak it. It never saves anything so far as I can see. > did above I get only the data spoken and the file with 0 bytes in > it. I'm not sure which file has zero bytes. I hope not the one being spoken! But it sounds to me like your code is doing what the VB code does. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site Alan, Sorry about that, I copied over to quickly and actually took the example just below the one I wanted. This is the example and of course I looked back after sending it and discovered the very same conclusion you came up with. Below is the one I am talking about. How to connect the audio stream to an open file for writing is what I am trying to do. Speak to a wav file in automation The following example is written in Visual Basic. It has the same functionality as the above in C++. After the creation of an SpFileStream object, a default format, SAFT22kHz16BitMono, is assigned to the object so that user does not need to explicitly assign a wav format to it unless a specific wav format is needed. In this example, ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the FileStream to the file. The third parameter of ISpeechFileStream.Open is the Boolean, DoEvents. The default of this parameter is set to False. However, the user should always set it to True to display SAPI events while playing back the wav file. If the parameter is set to False, no engine events will be stored in the file, resulting in that no engine events will be fired during the wav file play back. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create a SAPI voice Set Voice = New SpVoice 'The output audio data will be saved to ttstemp.wav file FileName = "c:\ttstemp.wav" 'Create a file; set DoEvents=True so TTS events will be saved to the file FileStream.Open FileName, SSFMCreateForWrite, True 'Set the output to the FileStream Set Voice.AudioOutputStream = FileStream 'Speak the text Voice.Speak "hello world" 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing From chester_lab at fltg.net Sat Jun 21 11:44:27 2008 From: chester_lab at fltg.net (FT) Date: Sat, 21 Jun 2008 05:44:27 -0400 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower><1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com><000e01c8d375$82a2c980$0301a8c0@brucetower> <20080621093625.9BF34FA42BE@mxf1.guaranteedservers.net> Message-ID: <002701c8d383$6a53ea40$0301a8c0@brucetower> Alan, This is what I wrote in python. The onlyu thing I did not do is a declaration of a filestream as the VB example does. I get no errors, just the Speak method just speaks. The saved file has no data, 0 Bytes. Now the note they mentioned was the True flag and I inserted that. import Sapi5, time, os av = Sapi5.SynthDriver() av.init() #AN ASSIGNMENT I COULD PLACE IN FIRST CALL AND CALL THE METHOD .Create() SYNC = av._sync ASYNC = av._async PURGE = av._purge ISFILE = av._is_filename XML = av._xml NOT_XML = av._not_xml PERSIST = av._persist_xml PUNC = av._punc WAIT = av._wait av.Speak("Hello!") av.Speak( "I am speaking in the default voice!") av.Speak( "Number of voices is: %d" % av.getVoiceCount()) av.Speak( "Hello! Now saying the punctuation in this sentence.", PUNC) time.sleep(.5) file4tts = open('test.wav', 'w', True) av.AudioOutputStream = file4tts av.Speak( "Hello World!", ASYNC) file4tts.close Microsoft Example: Speak to a wav file in automation The following example is written in Visual Basic. It has the same functionality as the above in C++. After the creation of an SpFileStream object, a default format, SAFT22kHz16BitMono, is assigned to the object so that user does not need to explicitly assign a wav format to it unless a specific wav format is needed. In this example, ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the FileStream to the file. The third parameter of ISpeechFileStream.Open is the Boolean, DoEvents. The default of this parameter is set to False. However, the user should always set it to True to display SAPI events while playing back the wav file. If the parameter is set to False, no engine events will be stored in the file, resulting in that no engine events will be fired during the wav file play back. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create a SAPI voice Set Voice = New SpVoice 'The output audio data will be saved to ttstemp.wav file FileName = "c:\ttstemp.wav" 'Create a file; set DoEvents=True so TTS events will be saved to the file FileStream.Open FileName, SSFMCreateForWrite, True 'Set the output to the FileStream Set Voice.AudioOutputStream = FileStream 'Speak the text Voice.Speak "hello world" 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing From alan.gauld at btinternet.com Sat Jun 21 19:01:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jun 2008 18:01:13 +0100 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower><1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com><000e01c8d375$82a2c980$0301a8c0@brucetower><20080621093625.9BF34FA42BE@mxf1.guaranteedservers.net> <002701c8d383$6a53ea40$0301a8c0@brucetower> Message-ID: "FT" wrote in message news:002701c8d383$6a53ea40$0301a8c0 at brucetower... > > Alan, > > This is what I wrote in python. > > file4tts = open('test.wav', 'w', True) > av.AudioOutputStream = file4tts > av.Speak( "Hello World!", ASYNC) > file4tts.close You need parentheses after close. Otherwise you are evaluating the function not executing it. Without closing the file thre is a possibility that the buffer is not being flushed to disk. But it could be a typo in which case I don't know what the problem is! :-) Alan G. From chester_lab at fltg.net Sat Jun 21 19:11:15 2008 From: chester_lab at fltg.net (FT) Date: Sat, 21 Jun 2008 13:11:15 -0400 Subject: [Tutor] File Stream Assignment? References: <000801c8d321$b744cca0$0301a8c0@brucetower><1c2a2c590806202047w4b52ee97r8e28bdbb9722e676@mail.gmail.com><000e01c8d375$82a2c980$0301a8c0@brucetower> Message-ID: <000901c8d3c1$dba435e0$0301a8c0@brucetower> Alan Gauld Wrote: "FT" wrote Caveat: I know nothing about MS SAPI. > The following code illustrates how to speak a text file > in a specific voice in Visual Basic. This example assumes > a text file (ttstemp.txt) containing the text to be spoken > already exists. ISpeechVoice.SpeakStream is used here > to speak an SpFileStream that > has been bound to the file. ||||Snip|||| I have no idea what you mean by this. Where are you looking? This is a COM object which is in the MS library. You will need to access it via PythonWin or ctypes or a Python wrapper of some sort. But the fact you are getting it to speak suggests you have succeeded in that already. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld Hi Alan, I did a search and I think it was about the 30'th search or more and finally came out with the exact code. Interesting enough it was on the win32 site and a person did not want to use the working code for something more like I was originally searching for, but it works. Below is the method I placed it into. I use the same Create function but the added feature is the lib and it was inside the Create assignment itself. You were correct in it needed to be in the com stuff. I do not know all that I need to know about this for there is so much to search and read to tie it all together. So I do it one piece at a time. I also used the same naming convention as the built in Speak method and I did not have to use C code to get it runnhing, instead used the same imports I already had. I attached the complete speech class module I am developing and the methods I am using at the moment. Here is the method: from comtypes.client import CreateObject #NEEDED IF THIS METHOD IS A STAND ALONE! #SET AUDIO STREAM FOR OUTPUT TO A FILE! def SpeakToWav(self, filename, text): """THIS METHOD ASSUMES THE IMPORT OF COMTYPES.CLIENT createObject SO A VOICE AND FILE STREAM OBJECT ARE CREATED WITH THE PASSING IN OF THE FILE NAME TO SAVE THE VOICE INTO AND THE TEXT DATA TO SPEAK AND STORE ONCE THE TEXT IS SPOKEN INTO THE FILE IT IS CLOSED AND THE OBJECTS DESTROYED!""" stream = CreateObject("SAPI.SpFileStream") tts4file = CreateObject( 'sapi.SPVoice') from comtypes.gen import SpeechLib stream.Open( filename, SpeechLib.SSFMCreateForWrite) tts4file.AudioOutputStream = stream tts4file.Speak( text, 0) stream.Close() del tts4file del stream -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: SAPI5.py URL: From mikem at blazenetme.net Sat Jun 21 18:47:22 2008 From: mikem at blazenetme.net (Mike Meisner) Date: Sat, 21 Jun 2008 12:47:22 -0400 Subject: [Tutor] WIn32 extension -= exposing methods with a windows handle Message-ID: <000601c8d3be$7b564f00$08a305cf@Parents> I would like to capture information from a multi-player internet game in order to tabulate player statistics. Specifically, I need information from a chat box within the main play window. Using the win32 extension (win32gui module: EnumWindows, EnumChildWIndows) I can obtain a handle to the chat box. At that point, I don't see any apparent win32 functions to expose the methods available in the chat box and, thereby, extract the chat text information I need. So, if I have the handle to a child window, does anyone know how to enumerate the attributes and methods for that window using Python or its extensions? (Since the window is not a Python generated window, __dict__ doesn't work, or I am incorrectly using it: w = CreateWindowFromHandle(hwnd); print w.__dict__). Also, if I know that a particular method is supported by the window's class (e.g., GetText), can I use the window's handle to access the method (i.e., text = hwnd.GetText) ? Or, what is the correct syntax? Thanks for your help. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 21 23:35:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jun 2008 22:35:11 +0100 Subject: [Tutor] WIn32 extension -= exposing methods with a windows handle References: <000601c8d3be$7b564f00$08a305cf@Parents> Message-ID: "Mike Meisner" wrote i > obtain a handle to the chat box. At that point, I don't see any > apparent win32 functions to expose the methods available in > the chat box and, thereby, extract the chat text information I need. It depends on the exact type of the dialog box. You can get the list of methods in the Pythonwin documentation, based on the Win32 API help. > (Since the window is not a Python generated window, > __dict__ doesn't work, or I am incorrectly using it: > w = CreateWindowFromHandle(hwnd); print w.__dict__). Thats the right way to get a Python variable referencing it. > Also, if I know that a particular method is supported by > the window's class (e.g., GetText), can I use the window's > handle to access the method (i.e., text = hwnd.GetText) ? No, you need to do what you did above and get a variable referencing the object so you could do w.GetText(....) - except I don't see GetText as a method of any Windows object I've looked at. Do you know what kind of Window object it is? The object browser in Pytonwin might be able to tell you... but I've never used it so don't really know!! Alan G. From technorapture at gmail.com Sat Jun 21 23:55:44 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Sat, 21 Jun 2008 17:55:44 -0400 Subject: [Tutor] Tkinter on OS X Message-ID: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> I've been writing a simple Tkinter interface to one of my programs. But it looks rather bad on OS X leopard. I was wondering why that was the case, since it seemed to take up at least some GUI elements (like button styles). I then came upon the following page: http://developer.apple.com/unix/toolkits.html that says that the Aqua version of Tk hasn't been integrated with Tkinter. Is this correct? Is there another way to write a front-end that looks more like a native app. I put a screenshot of my current UI up on my blog. http://bytebaker.com/2008/06/21/cocoa-python-and-the-quest-for-platform-independence/ -- The ByteBaker : http://www.bytebaker.com From steve at alchemy.com Sun Jun 22 00:29:05 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 21 Jun 2008 15:29:05 -0700 Subject: [Tutor] Tkinter on OS X In-Reply-To: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> References: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> Message-ID: <485D80B1.40906@alchemy.com> Shrutarshi Basu wrote: > I've been writing a simple Tkinter interface to one of my programs. > But it looks rather bad on OS X leopard. I was wondering why that was > the case, since it seemed to take up at least some GUI elements (like > button styles). I then came upon the following page: > http://developer.apple.com/unix/toolkits.html > that says that the Aqua version of Tk hasn't been integrated with > Tkinter. Is this correct? Is there another way to write a front-end > that looks more like a native app. I put a screenshot of my current UI > up on my blog. > http://bytebaker.com/2008/06/21/cocoa-python-and-the-quest-for-platform-independence/ > Have you considered something like wx? That's a bit more heavyweight to develop to (but not a great deal), but it gives complete native look and feel on Unix, Windows and OSX. From kent37 at tds.net Sun Jun 22 00:29:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Jun 2008 18:29:38 -0400 Subject: [Tutor] Tkinter on OS X In-Reply-To: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> References: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> Message-ID: <1c2a2c590806211529x24c55d30j228340a072330352@mail.gmail.com> On Sat, Jun 21, 2008 at 5:55 PM, Shrutarshi Basu wrote: > I've been writing a simple Tkinter interface to one of my programs. > But it looks rather bad on OS X leopard. I was wondering why that was > the case, since it seemed to take up at least some GUI elements (like > button styles). I then came upon the following page: > http://developer.apple.com/unix/toolkits.html I'm pretty sure that page is out-of-date, Tkinter does not require X11, it is integrated with Aqua. > that says that the Aqua version of Tk hasn't been integrated with > Tkinter. Is this correct? Is there another way to write a front-end > that looks more like a native app. Tkinter has a reputation as quick and ugly. Some dispute that and there may be ways to make it look better but if you are after good looks you might want to choose a different toolkit. wxPython, PyQt and PyGTK all have their proponents. Kent From zmanji at gmail.com Sun Jun 22 06:00:25 2008 From: zmanji at gmail.com (Zameer Manji) Date: Sun, 22 Jun 2008 00:00:25 -0400 Subject: [Tutor] Is this the right way to create a Message-ID: <485DCE59.70409@gmail.com> I'm trying to create a library for the Last.fm webservice[1] and the first thing I created was a class for the Profile Information.[2] Is this the proper way of creating it? Is this useful to another programmer? import urllib import xml.etree.ElementTree as ET from BeautifulSoup import BeautifulStoneSoup as BSS BASEURL = 'http://ws.audioscrobbler.com/1.0/user/' class UserProfile(object): """Represents the user profile data""" def __init__(self, username): """Give the username""" self.username = username def getxmldata(self): url = BASEURL + self.username + '/profile.xml' self.xmldata = urllib.urlopen(url).read() def parsedata(self): soup = BSS(self.xmldata) self.url = soup.url.string self.realname = soup.realname.string self.sha1 = soup.mbox_sha1sum.string self.regdate = soup.registered.string self.unixregdate = soup.registered['unixtime'] self.age = soup.age.string self.gender = soup.gender.string self.country = soup.country.string self.playcount = soup.playcount.string self.avatar = soup.avatar.string self.icon = soup.icon.string self.id = soup.profile['id'] Also, how do I then begin to approach the whole API ? Do I create a User class the inherits from the UserProfile class and other classes for their Neighbours', Top Artists, etc ? Do a create a separate class for each web service ? I have never coded something like this before and all advice is welcome. [1] http://www.audioscrobbler.net/data/webservices/ [2] http://ws.audioscrobbler.com/1.0/user/RJ/profile.xml From jordangreenberg at gmail.com Sun Jun 22 08:09:03 2008 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Sun, 22 Jun 2008 02:09:03 -0400 Subject: [Tutor] dollarize.py In-Reply-To: <485C7D39.9010800@groktech.org> References: <166802.89300.qm@web51605.mail.re2.yahoo.com> <485C7D39.9010800@groktech.org> Message-ID: <485DEC7F.4010302@gmail.com> Martin Walsh wrote: > def addcommas(f): > """ > This amounts to reversing everything left > of the decimal, grouping by 3s, joining > with commas, reversing and reassembling. > """ > # assumes type(f) == float > left, right = ('%0.2f' % f).split('.') > rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)] > return ','.join(rleft)[::-1] + '.' + right def addcommas(s): # assumes type(s)==str b=[] l=len(s) for i,v in enumerate(s): i+=1 # easier to understand w/ 1-based indexing, i think. b.append(v) if (l-i)%3==0 and not i==l: b.append(',') return ''.join(b) or, somewhat more tersely: def addcommas2(s): l=len(s) return ''.join(v+',' if (l-(i+1))%3==0 and not i+1-l==0 else v for i,v in enumerate(s)) From alan.gauld at btinternet.com Sun Jun 22 09:57:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Jun 2008 08:57:13 +0100 Subject: [Tutor] Tkinter on OS X References: <376fbdcf0806211455t2af94143x21557f1917fb0aad@mail.gmail.com> <1c2a2c590806211529x24c55d30j228340a072330352@mail.gmail.com> Message-ID: "Kent Johnson" wrote > I'm pretty sure that page is out-of-date, Tkinter does not require > X11, it is integrated with Aqua. This is true, as a recent posting confirmed re the limitations of colouring buttons under Aqua. But... > Tkinter has a reputation as quick and ugly. Thats a good description in my experience. And on Aqua it still isn't as slick as some other toolkits. > there may be ways to make it look better You can make Tkinter look OK on any platform but it takes an inordinate amount of timwe to tweak all the settings on every widget. > looks you might want to choose a different toolkit. wxPython, PyQt > and > PyGTK all have their proponents. If cross platform compatibility isn;t important then considr using the Cocoa bindings for MacOS X. You can't get any more native than that and you get the advantage of being able to use XCode as your GUI BUilder. But it won't work on anything but a Mac! HTH, Alan G From alan.gauld at btinternet.com Sun Jun 22 10:03:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Jun 2008 09:03:26 +0100 Subject: [Tutor] Is this the right way to create a References: <485DCE59.70409@gmail.com> Message-ID: "Zameer Manji" wrote > Also, how do I then begin to approach the whole API ? Do I create a > User > class the inherits from the UserProfile class and other classes for > their Neighbours', Top Artists, etc ? I don;t know enough about the underlying service to answer that but... > Do a create a separate class for each web service ? Web services are usually procedural in nature so that you don't need to create classes at all. So to provbide maximum flexibility you might be better just creating a module that exposes the services as functions. The users can then create their own classes built on the underlying API functions. If you do want to go with classes, think about how you would ideally like to use the API to build applications. Try writing some simple applications as if the classes existed. Calling the methods you would want to have. Then go back and build those classes. Design from the outside in for maximum usability. And of course it might be a good idea to do both things. Write the basic module that handles all the SOAP and networking stuff then write the user friendly classses on top of that as a separate module. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Jun 22 13:24:43 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Jun 2008 07:24:43 -0400 Subject: [Tutor] Is this the right way to create a In-Reply-To: <485DCE59.70409@gmail.com> References: <485DCE59.70409@gmail.com> Message-ID: <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> On Sun, Jun 22, 2008 at 12:00 AM, Zameer Manji wrote: > I'm trying to create a library for the Last.fm webservice[1] and the > first thing I created was a class for the Profile Information.[2] Is > this the proper way of creating it? Is this useful to another programmer? > > import urllib > import xml.etree.ElementTree as ET > from BeautifulSoup import BeautifulStoneSoup as BSS > BASEURL = 'http://ws.audioscrobbler.com/1.0/user/' > class UserProfile(object): > """Represents the user profile data""" > def __init__(self, username): > """Give the username""" > self.username = username > def getxmldata(self): > url = BASEURL + self.username + '/profile.xml' > self.xmldata = urllib.urlopen(url).read() > def parsedata(self): > soup = BSS(self.xmldata) > self.url = soup.url.string > This looks like a good start. A few things I would change: - getxmldata() will be shared among all your API routines so you might make it a separate function that returns the data instead of assigning it to an attribute. - This class is probably not very useful without the parsed data so you might call getxmldata() & parsedata() from the constructor (__init__() method). There is no reason to make client code call these. You certainly don't want your client code to have to call getxmldata() and parsedata() both in the correct order. - You might want to use one of the two common naming conventions for your methods, either getXmlData() or get_xml_data(). A couple of other ways you could organize this that might be useful: - Have the UserProfile constructor take a BeautifulSoup node as its argument. Then have a separate function that gets and parses the XML. This wil be a useful structure for Artists, for example, because you have to parse lists of Artists. - alternately, you could have a function that pokes values into a UserProfile. > Also, how do I then begin to approach the whole API ? Do I create a User > class the inherits from the UserProfile class and other classes for > their Neighbours', Top Artists, etc ? Do a create a separate class for > each web service ? I have never coded something like this before and all > advice is welcome. A User class that has a UserProfile as an attribute, and accessors for Neighbors, etc, sounds good to me. You may want an Artist class, probably not a Top Artists class. The User.getTopArtists() method would access the web services API and return a list of Artists. At a first guess, it looks like you may want classes for each of the types listed under "Categories" on the Web Services page. Pull as much of the web services code into shared functions as possible (or possibly a utility class). For example, you will probably want a function that creates a list of Artists from a parsed XML page. Kent From kent37 at tds.net Sun Jun 22 13:27:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Jun 2008 07:27:11 -0400 Subject: [Tutor] Is this the right way to create a In-Reply-To: References: <485DCE59.70409@gmail.com> Message-ID: <1c2a2c590806220427w5807a4e9x3f3b7767f7e658e4@mail.gmail.com> On Sun, Jun 22, 2008 at 4:03 AM, Alan Gauld wrote: > Web services are usually procedural in nature so that you don't > need to create classes at all. So to provbide maximum flexibility > you might be better just creating a module that exposes the > services as functions. The users can then create their own classes > built on the underlying API functions. In this case I think you would at least want to make a class to hold the results of the call because there are so many fields to return. Kent From danny_laya at yahoo.com Sun Jun 22 12:45:28 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Sun, 22 Jun 2008 03:45:28 -0700 (PDT) Subject: [Tutor] From Newbie Message-ID: <75481.39840.qm@web59809.mail.ac4.yahoo.com> Hi ! I have learned wiki tutor for non-programmer and I found some hill that stopping me. In Non-Programmer's Tutorial for Python/Count to 10, wiki ask me to write this code : a = 1 s = 0 print 'Enter Numbers to add to the sum.' print 'Enter 0 to quit.' while a != 0: print 'Current Sum:', s a = int(raw_input('Number? ')) s = s + a print 'Total Sum =', s But when i write while a != 0: and then i press enter, python terminal tell me : >>> while a ! = 0: File "", line 1 while a ! = 0: ^ SyntaxError: invalid syntax Can you find my mistake, guys ? Sorry to bother you, I try to find the answer in google, but I can't found the answer. Please help me soon guys, whatever your answer. If you don't want to answer my question, please give me some site that could answer this newbie question. Thank's. -------------- next part -------------- An HTML attachment was scrubbed... URL: From broek at cc.umanitoba.ca Sun Jun 22 16:03:06 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 22 Jun 2008 09:03:06 -0500 Subject: [Tutor] From Newbie In-Reply-To: <75481.39840.qm@web59809.mail.ac4.yahoo.com> References: <75481.39840.qm@web59809.mail.ac4.yahoo.com> Message-ID: <20080622090306.qm2vgkdr4gw0ook4@webware.cc.umanitoba.ca> > But when i write while a != 0: and then i press enter, > python terminal tell me : >>>> while a ! = 0: > File "", line 1 > while a ! = 0: > ^ > SyntaxError: invalid syntax > > Can you find my mistake, guys ? Sorry to bother you, I try to Hi, Python's trying to give you a hint: > while a ! = 0: > ^ > SyntaxError: invalid syntax So, there's something it doesn't like around the `!' character. Compare the error message to what you say you wrote: > while a != 0: Notice any differences? Best, Brian vdB From bhaaluu at gmail.com Sun Jun 22 17:06:40 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 22 Jun 2008 11:06:40 -0400 Subject: [Tutor] From Newbie In-Reply-To: <75481.39840.qm@web59809.mail.ac4.yahoo.com> References: <75481.39840.qm@web59809.mail.ac4.yahoo.com> Message-ID: On Sun, Jun 22, 2008 at 6:45 AM, Danny Laya wrote: > Hi ! I have learned wiki tutor for non-programmer and I found some hill that > stopping me. In Non-Programmer's Tutorial for Python/Count to 10, wiki ask > me to write this code : > > a = 1 > s = 0 > print 'Enter Numbers to add to the sum.' > print 'Enter 0 to quit.' > while a != 0: > print 'Current Sum:', s > a = int(raw_input('Number? ')) > s = s + a > print 'Total Sum =', s > The above code, copy/pasted to a file, and run from the command-line gives the following output: Enter Numbers to add to the sum. Enter 0 to quit. Current Sum: 0 Number? 1 Current Sum: 1 Number? 2 Current Sum: 3 Number? 3 Current Sum: 6 Number? 4 Current Sum: 10 Number? 0 Total Sum = 10 > But when i write while a != 0: and then i press enter, > python terminal tell me : >>>> while a ! = 0: > File "", line 1 > while a ! = 0: > ^ > SyntaxError: invalid syntax > > Can you > find my mistake, guys ? Sorry to bother you, I try to > find the answer in google, but I can't found the answer. > Please help me soon guys, whatever your answer. If you don't > want to answer my question, please give me some site that could > answer this newbie question. Thank's. > The syntax error seems to be the space between the '!' and the '='. '!=' means 'does not equal' '! =' doesn't mean anything, thus, the syntax error. When you're beginning, you'll make plenty of errors like that. Stop and read the error carefully, then look at the code closely. As you gain experience, you'll learn to see those nit-picky syntax errors. It doesn't matter which computer programming language you start out with, each one has a specific syntax that must be followed, or you'll get syntax errors. Python is very friendly, and the error messages it gives you are much more helpful than other languages. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From danny_laya at yahoo.com Sun Jun 22 17:14:37 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Sun, 22 Jun 2008 08:14:37 -0700 (PDT) Subject: [Tutor] From Newbie Message-ID: <692717.15107.qm@web59811.mail.ac4.yahoo.com> Few... Thanks all, i have found the wrong, i miss some space between != and 0. Thank's for the help. I really apreciate it ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at assured-networks.co.uk Sun Jun 22 16:55:09 2008 From: paul at assured-networks.co.uk (paul at assured-networks.co.uk) Date: Sun, 22 Jun 2008 15:55:09 +0100 Subject: [Tutor] From Newbie Message-ID: <200806221455.m5MEsrL8004956@mta4.iomartmail.com> An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Sun Jun 22 21:28:29 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 22 Jun 2008 12:28:29 -0700 (PDT) Subject: [Tutor] [Fwd: Re: From Newbie] Message-ID: <55588.66.218.47.125.1214162909.squirrel@mail.tigertech.net> On Sun, June 22, 2008 7:55 am, paul at assured-networks.co.uk wrote: > hi Danny, > > > As far as i am aware you must declare your variable first, something like > a=0 That's a good thought. But he did initialize his variable. The '!' and the '=' in '!=' are all smashed together without spaces. So: > while a ! = 0: Should be: while a != 0: That should get you going again. Marilyn Davis > > The same would go for s > > > hope that helps > > paul > > On Sun Jun 22 10:45 , Danny Laya sent: > > > > > > Hi ! I have learned wiki tutor for non-programmer and I found some hill > that stopping me. In Non-Programmer's Tutorial for Python/Count to 10, > wiki ask me to write this code : a = 1 s = 0 print 'Enter Numbers to add to > the sum.' print 'Enter 0 to quit.' while a != 0: print 'Current Sum:', s a = > int(raw_input('Number? ')) s = s + a print 'Total Sum =', s > > But when i write while a != 0: and then i press enter, > python terminal tell me : >>>> while a ! = 0: > File "", line 1 > while a ! = 0: ^ > SyntaxError: invalid syntax > > > Can you find my mistake, guys ? Sorry to bother you, I try to > find the answer in google, but I can't found the answer. Please help me > soon guys, whatever your answer. If you don't want to answer my question, > please give me some site that could answer this newbie question. Thank's. > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From zmanji at gmail.com Sun Jun 22 21:50:14 2008 From: zmanji at gmail.com (Zameer Manji) Date: Sun, 22 Jun 2008 15:50:14 -0400 Subject: [Tutor] Is this the right way to create a In-Reply-To: <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> References: <485DCE59.70409@gmail.com> <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> Message-ID: <485EACF6.1090107@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Kent Johnson wrote: > A User class that has a UserProfile as an attribute, and accessors for > Neighbors, etc, sounds good to me. You may want an Artist class, > probably not a Top Artists class. The User.getTopArtists() method > would access the web services API and return a list of Artists. At a > first guess, it looks like you may want classes for each of the types > listed under "Categories" on the Web Services page. I'm quite new to OOP, so forgive me if I am missing something obvious. When you say that the User class should have a UserProfile as an attribute, would it look something like this? from lastfmapi import UserProfile class User (object): def __init__: self.UserProfile = UserProfile('Bob') Also what do you mean by 'accessors' for Neighbors ? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) iQEcBAEBCgAGBQJIXqz2AAoJEA759sZQuQ1BKWgIAJMAXzcUkL1MNjXE2xbFXpgf cKAnNfiHpCLp9X8503Fdn8yMA8dq16ktOS7L5EeqsZnU4lpns6XeWzO1RbiUcxY7 i0ojWffBgvtfaK/3b6IteDvL7/+rKKXHiQRzPLDET8XUfoAe9kIXppN49JEfl7s7 JCrEXLv6/eHLcHT+aMCtcKLGF9s85kSW7pipIg61n2H0X3rYl3kZeRE5unjbc2rJ ++YM4CSOrG3n8U3o/NCdnP23p8W2x6WNnndeWG2C7tLa2n/k3QkY2cOpG/tELU+p tpwT9VAeoEvOyKAhtfqfwBS9gCa3hrbnuUt9IDvcHR0TmKJ+rytbLqHOGLtH5rU= =2Ifq -----END PGP SIGNATURE----- From chester_lab at fltg.net Sun Jun 22 22:58:32 2008 From: chester_lab at fltg.net (FT) Date: Sun, 22 Jun 2008 16:58:32 -0400 Subject: [Tutor] A SAPI Module With Pitch and Create Message-ID: <001801c8d4aa$c143bd30$0301a8c0@brucetower> Hi! I have reduced down and added a few features into the SAPI 5 speech module I have created. You can now save and read wav files. The test module tests most of the features I have in it at the moment. I added the ability inside the Create method to set all the voice parameters. You can change the voice, volume, rate, and pitch in the Create method. They are dict values and just assign the values you want. Pitch and rate are from -10 to 10 with 0 the norm. Where the volume is from 0% to 100% but do not use the (%) symbol, just the integer number. The default for change is 0 for any of the values and the default voice will be the first on the list, which is Sam if you are using the Microsoft SAPI 5 voices. The names are listed in the test. So assignment depends on what you have installed onto your machine. I have not changed any usage of eSpeak voices to allow pitch adjustment yet. An error comes up for those voices because I have not looked into what it wants. This SAPI 5 engine will at least allow you to get started and includes the methods saving and reading a wav file. The wav methods are .SpeakToWav and SpeakFromWav so you could use it for other possible things, such as web sites and games. Enjoy testing it. I have not played with the bookmark method yet. Bruce -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Sapi5.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Test4Sapi.py URL: From kent37 at tds.net Sun Jun 22 23:25:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Jun 2008 17:25:08 -0400 Subject: [Tutor] Is this the right way to create a In-Reply-To: <485EACF6.1090107@gmail.com> References: <485DCE59.70409@gmail.com> <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> <485EACF6.1090107@gmail.com> Message-ID: <1c2a2c590806221425t9f67d66v89a6d8b67cf47b76@mail.gmail.com> On Sun, Jun 22, 2008 at 3:50 PM, Zameer Manji wrote: > I'm quite new to OOP, so forgive me if I am missing something obvious. > When you say that the User class should have a UserProfile as an > attribute, would it look something like this? > > from lastfmapi import UserProfile > class User (object): > def __init__: > self.UserProfile = UserProfile('Bob') Yes, that's about right. Of course 'Bob' should be an argument passed to __init__() > Also what do you mean by 'accessors' for Neighbors ? class User(object): ... def getNeighbors(): """ Returns a list of this user's neighbors """ and similar for getTopArtists(), etc. Kent > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (MingW32) > > iQEcBAEBCgAGBQJIXqz2AAoJEA759sZQuQ1BKWgIAJMAXzcUkL1MNjXE2xbFXpgf > cKAnNfiHpCLp9X8503Fdn8yMA8dq16ktOS7L5EeqsZnU4lpns6XeWzO1RbiUcxY7 > i0ojWffBgvtfaK/3b6IteDvL7/+rKKXHiQRzPLDET8XUfoAe9kIXppN49JEfl7s7 > JCrEXLv6/eHLcHT+aMCtcKLGF9s85kSW7pipIg61n2H0X3rYl3kZeRE5unjbc2rJ > ++YM4CSOrG3n8U3o/NCdnP23p8W2x6WNnndeWG2C7tLa2n/k3QkY2cOpG/tELU+p > tpwT9VAeoEvOyKAhtfqfwBS9gCa3hrbnuUt9IDvcHR0TmKJ+rytbLqHOGLtH5rU= > =2Ifq > -----END PGP SIGNATURE----- > From mwalsh at groktech.org Mon Jun 23 00:29:36 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 22 Jun 2008 17:29:36 -0500 Subject: [Tutor] dollarize.py In-Reply-To: <485DEC7F.4010302@gmail.com> References: <166802.89300.qm@web51605.mail.re2.yahoo.com> <485C7D39.9010800@groktech.org> <485DEC7F.4010302@gmail.com> Message-ID: <485ED250.4010506@groktech.org> Jordan Greenberg wrote: > def addcommas(s): # assumes type(s)==str > b=[] > l=len(s) > for i,v in enumerate(s): > i+=1 # easier to understand w/ 1-based indexing, i think. > b.append(v) > > if (l-i)%3==0 and not i==l: > b.append(',') > return ''.join(b) > > > or, somewhat more tersely: > > > def addcommas2(s): > l=len(s) > return ''.join(v+',' if (l-(i+1))%3==0 and not i+1-l==0 > else v for i,v in enumerate(s)) Excellent, thanks Jordan! That's much more elegant, and efficient, than my juggling act :) From dineshbvadhia at hotmail.com Mon Jun 23 02:13:01 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 22 Jun 2008 17:13:01 -0700 Subject: [Tutor] endless processing through for loop Message-ID: I have a program with 2 for loops like this (in pseudocode): fw = open(newLine.txt, 'w') for i in xrange(0, 700,000, 1): read a file fname from folder for line in open(fname, 'r'): do some simple string processing on line fw.write(newline) fw.close() That's it. Very simple but after i reaches about 550,000 the program begins to crawl. As an example, the loops to 550,000 takes about an hour. From 550,000 to 580,000 takes an additional 4 hours. Any ideas about what could be going on? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 23 02:30:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jun 2008 01:30:16 +0100 Subject: [Tutor] endless processing through for loop References: Message-ID: "Dinesh B Vadhia" wrote fw = open(newLine.txt, 'w') for i in xrange(0, 700,000, 1): read a file fname from folder for line in open(fname, 'r'): do some simple string processing on line fw.write(newline) fw.close() > From 550,000 to 580,000 takes an additional 4 hours. Sounds like a memory problem,. Can you look in Task manager (assuming Windows) or top(Linux) to see what the memory usage looks like? In theory the read files should get closed automatically but being extra cautious I might try the inner loop as: fr = open(fname, 'r') for line in fr: do some simple string processing on line fw.write(newline) fr.close() Just to be sure. I might also try adding an fw.flush() after the write to ensure it goes to disk. If that isn't enough I might try opening and closing the write file each time using append mode. In theiry that shouldn't make any difference but it might be that its trying to hold the entire output file (which must be huge!) in memory... Not certain any of those will help but its something to try! Alan G. From kent37 at tds.net Mon Jun 23 02:39:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Jun 2008 20:39:49 -0400 Subject: [Tutor] endless processing through for loop In-Reply-To: References: Message-ID: <1c2a2c590806221739k223f97bv1dce25586269bbed@mail.gmail.com> On Sun, Jun 22, 2008 at 8:13 PM, Dinesh B Vadhia wrote: > That's it. Very simple but after i reaches about 550,000 the program begins > to crawl. As an example, the loops to 550,000 takes about an hour. From > 550,000 to 580,000 takes an additional 4 hours. > > Any ideas about what could be going on? What happens to memory use? Does it start to thrash the disk? Are you somehow keeping the file contents in memory for all the files you read? Kent From dineshbvadhia at hotmail.com Mon Jun 23 03:03:29 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 22 Jun 2008 18:03:29 -0700 Subject: [Tutor] endless processing through for loop In-Reply-To: <1c2a2c590806221739k223f97bv1dce25586269bbed@mail.gmail.com> References: <1c2a2c590806221739k223f97bv1dce25586269bbed@mail.gmail.com> Message-ID: There is no thrashing of disk as I have > 2gb RAM and I'm not keeping the file contents in memory. One line is read at a time, some simple string processing and then writing out the modified line. From: Kent Johnson Sent: Sunday, June 22, 2008 5:39 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] endless processing through for loop On Sun, Jun 22, 2008 at 8:13 PM, Dinesh B Vadhia wrote: > That's it. Very simple but after i reaches about 550,000 the program begins > to crawl. As an example, the loops to 550,000 takes about an hour. From > 550,000 to 580,000 takes an additional 4 hours. > > Any ideas about what could be going on? What happens to memory use? Does it start to thrash the disk? Are you somehow keeping the file contents in memory for all the files you read? Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Jun 23 03:07:54 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 23 Jun 2008 13:07:54 +1200 Subject: [Tutor] endless processing through for loop In-Reply-To: References: Message-ID: <5e58f2e40806221807t64ac585du7924cab9ff352e27@mail.gmail.com> On 23/06/2008, Dinesh B Vadhia wrote: > I have a program with 2 for loops like this (in pseudocode): > > fw = open(newLine.txt, 'w') > for i in xrange(0, 700,000, 1): > read a file fname from folder > for line in open(fname, 'r'): > do some simple string processing on line > fw.write(newline) > fw.close() > > That's it. Very simple but after i reaches about 550,000 the program begins > to crawl. As an example, the loops to 550,000 takes about an hour. From > 550,000 to 580,000 takes an additional 4 hours. > > Any ideas about what could be going on? What happens if you reverse the loop? i.e. change to: for i in xrange(699999, -1, -1): -- John. From meanburrito920 at yahoo.com Mon Jun 23 06:17:30 2008 From: meanburrito920 at yahoo.com (John Gunderman) Date: Sun, 22 Jun 2008 21:17:30 -0700 (PDT) Subject: [Tutor] references to containing objects Message-ID: <873425.89499.qm@web56315.mail.re3.yahoo.com> I am looking for a way to tell a object the properties of its containing object. For example, I have an object foo, of class Bar, which I have stored in a dict in the object I want to access. Basically: container_object.contained_object["foo"].action() What I want is for the object "foo" to be able to access properties of container_object through its action() method. the problem is that I don't know what the containing object's name is going to be before hand, so I can't just access it through the object's name. I'm thinking I could create a dict of the container_objects, so when the object was created the name could be passed to the action() method, but is there another way to do it? Thanks in advance. John -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 23 10:29:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jun 2008 09:29:00 +0100 Subject: [Tutor] references to containing objects References: <873425.89499.qm@web56315.mail.re3.yahoo.com> Message-ID: "John Gunderman" wrote >I am looking for a way to tell a object the properties of its >containing object. Can you explain why. Thats usually a bad idea. At the very least it should call a method of the containing object rather than "access its properties" (assuming you mean its data) > What I want is for the object "foo" to be able to access > properties of container_object through its action() method. The normal way to do this is to pass a "parent" argument to the constructor or in a method at assignment: class Container: def __init__(self) self.objects = [] def add(self, item) self.objects.append(item) class Contained: def __init__(self.parent = None): self.parent = parent parent.add(self) def setParent(self,parent): self.parent = parent parent.add(self) def action(self): self.parent.doSomething() # do stuff here box = Container() bag = Container() item = Contained(box) irtem2 = Contained(bag) item3 = Contained() item3.setParent(box) > the problem is that I don't know what the containing > object's name is going to be before hand, I assume you know at the point of assignment? In which case the addParent would work. > I'm thinking I could create a dict of the container_objects, so > when the object was created the name could be passed > to the action() method, The whole problem with this technique (and with the idea of accessing the container properties) is that it breaks the concept of data hiding and self containment. Objects should be loosely coupled - ie know very little about each other except the public interface(ie the methods) and tightly coherent - ie should be the only entity operating on their internal data. Any time one object has to access the innards of another object, or has to access an external data source to perform an internal action its a warning sign. Not necessarily an error just a warning that something may be wrong withthe design. A bad smell if you like. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cfuller084 at thinkingplanet.net Mon Jun 23 11:58:45 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 23 Jun 2008 04:58:45 -0500 Subject: [Tutor] references to containing objects In-Reply-To: <873425.89499.qm@web56315.mail.re3.yahoo.com> References: <873425.89499.qm@web56315.mail.re3.yahoo.com> Message-ID: <200806230458.45606.cfuller084@thinkingplanet.net> You can also subclass the dictionary type so that this happens transparently. You could do something similar with lists. class Container(dict): def __setitem__(self, key, value): dict.__setitem__(self, key, value) if hasattr(value, 'setParent'): if callable(value.setParent): value.setParent(self) class Contained: def setParent(self, p): self.parent = p bag = Container() print id(bag) item1 = Contained() item2 = Contained() bag['a'] = item1 bag['b'] = item2 print id(item1.parent) print id(item2.parent) Cheers From kent37 at tds.net Mon Jun 23 12:54:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jun 2008 06:54:11 -0400 Subject: [Tutor] references to containing objects In-Reply-To: <873425.89499.qm@web56315.mail.re3.yahoo.com> References: <873425.89499.qm@web56315.mail.re3.yahoo.com> Message-ID: <1c2a2c590806230354g70d6aeb0s472f88341de3a41c@mail.gmail.com> On Mon, Jun 23, 2008 at 12:17 AM, John Gunderman wrote: > I am looking for a way to tell a object the properties of its containing > object. > For example, I have an object foo, of class Bar, which I have stored in a > dict > in the object I want to access. Basically: > > container_object.contained_object["foo"].action() > > What I want is for the object "foo" to be able to access properties of > container_object > through its action() method. Maybe the actions can be bound methods of the container object class? For example: class Container(object): def __init__(self): self.actions = {} self.actions['foo'] = self.foo self.value = 3 def foo(self): print 'foo', self.value c = Container() c.actions['foo']() Otherwise I would go with Alan's suggestion of passing the parent to the action class constructor. Kent From bgailer at gmail.com Mon Jun 23 13:55:12 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 23 Jun 2008 07:55:12 -0400 Subject: [Tutor] endless processing through for loop In-Reply-To: References: Message-ID: <485F8F20.4080100@gmail.com> Dinesh B Vadhia wrote: > I have a program with 2 for loops like this (in pseudocode): > > fw = open(newLine.txt, 'w') > for i in xrange(0, 700,000, 1): > read a file fname from folder > for line in open(fname, 'r'): > do some simple string processing on line > fw.write(newline) > fw.close() > > That's it. Very simple but after i reaches about 550,000 the program > begins to crawl. As an example, the loops to 550,000 takes about an > hour. From 550,000 to 580,000 takes an additional 4 hours. Here's my simplistic Python version: fw = open("newLine.txt", 'w') for i in xrange(700000): if i % 1000 == 0: print i for line in open("file1.txt"): # 10 lines each 7 characters newline = line.replace("x","y") fw.write(newline) fw.close() It runs evenly, takes a couple of minutes. Try it, see if you get the same outcome. If you do then let's examine how your program differs. -- Bob Gailer 919-636-4239 Chapel Hill, NC From robert.d.kirkpatrick at gmail.com Mon Jun 23 19:27:13 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Mon, 23 Jun 2008 10:27:13 -0700 Subject: [Tutor] Possible to import imports? Message-ID: <10ea1c60806231027x3c795dcdy17219155c58103fc@mail.gmail.com> I've googled a bit and tried some things on my own, but can't seem to determine if it's possible to declare some standard library imports in one package/module then import that package/module somewhere else and reap the benefit of those initial imports. For example, if I have a setup like this: foo __init__.py bar __init__.py hello.py Could I put "import datetime" in foo's __init__.py and do an import of foo from hello.py and start using datetime in hello.py without importing datetime specifically in hello.py? All the examples I see import all the necessary standard library mods in the script/module that specifically uses them so either what I want to do is not possible or a bad idea. Thoughts? Cheers, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jun 23 21:03:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jun 2008 15:03:01 -0400 Subject: [Tutor] Possible to import imports? In-Reply-To: <10ea1c60806231027x3c795dcdy17219155c58103fc@mail.gmail.com> References: <10ea1c60806231027x3c795dcdy17219155c58103fc@mail.gmail.com> Message-ID: <1c2a2c590806231203p4a43c06al8bdd9f2a0dd89e6a@mail.gmail.com> On Mon, Jun 23, 2008 at 1:27 PM, Rob Kirkpatrick wrote: > I've googled a bit and tried some things on my own, but can't seem to > determine if it's possible to declare some standard library imports in one > package/module then import that package/module somewhere else and reap the > benefit of those initial imports. > > For example, if I have a setup like this: > > foo > __init__.py > bar > __init__.py > hello.py > > Could I put "import datetime" in foo's __init__.py and do an import of foo > from hello.py and start using datetime in hello.py without importing > datetime specifically in hello.py? Yes but it will be foo.datetime. The 'import datetime' in foo.__init__.py binds the name datetime in foo's module namespace. > All the examples I see import all the > necessary standard library mods in the script/module that specifically uses > them so either what I want to do is not possible or a bad idea. Thoughts? Why do this? For clarity, import the modules you need in the modules that need them. import foo foo.datetime... is just obscure IMO. Kent From robert.d.kirkpatrick at gmail.com Mon Jun 23 21:37:54 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Mon, 23 Jun 2008 12:37:54 -0700 Subject: [Tutor] Possible to import imports? In-Reply-To: <1c2a2c590806231203p4a43c06al8bdd9f2a0dd89e6a@mail.gmail.com> References: <10ea1c60806231027x3c795dcdy17219155c58103fc@mail.gmail.com> <1c2a2c590806231203p4a43c06al8bdd9f2a0dd89e6a@mail.gmail.com> Message-ID: <10ea1c60806231237l39c62d9erf39cc9ede5f04f34@mail.gmail.com> It was mostly an exercise in understanding import orders/precedence but I thought I might be able to use it to simplify imports for modules within a package that might all use the same or similar standard imports. The one I see a lot of is modules in the package routinely importing os and sys so I thought that if I could just import them once at the highest package level then just have the modules import their parent package, things would be cleaner. You make a good point about that causing more confusion than it's worth though, so I'll shelve that idea for the time being. Funny though that I did try using something like foo.datetime but I must have buggered up something cause I couldn't get it to work... Thanks Kent! On Mon, Jun 23, 2008 at 12:03 PM, Kent Johnson wrote: > On Mon, Jun 23, 2008 at 1:27 PM, Rob Kirkpatrick > wrote: > > I've googled a bit and tried some things on my own, but can't seem to > > determine if it's possible to declare some standard library imports in > one > > package/module then import that package/module somewhere else and reap > the > > benefit of those initial imports. > > > > For example, if I have a setup like this: > > > > foo > > __init__.py > > bar > > __init__.py > > hello.py > > > > Could I put "import datetime" in foo's __init__.py and do an import of > foo > > from hello.py and start using datetime in hello.py without importing > > datetime specifically in hello.py? > > Yes but it will be foo.datetime. The 'import datetime' in > foo.__init__.py binds the name datetime in foo's module namespace. > > > All the examples I see import all the > > necessary standard library mods in the script/module that specifically > uses > > them so either what I want to do is not possible or a bad idea. > Thoughts? > > Why do this? For clarity, import the modules you need in the modules > that need them. > import foo > foo.datetime... > is just obscure IMO. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Mon Jun 23 22:06:21 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 23 Jun 2008 13:06:21 -0700 Subject: [Tutor] I need to learn more about sorting! Message-ID: <20080623200635.75FBA1E4008@bag.python.org> An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Jun 23 22:18:10 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 23 Jun 2008 16:18:10 -0400 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <20080623200635.75FBA1E4008@bag.python.org> References: <20080623200635.75FBA1E4008@bag.python.org> Message-ID: <16651e80806231318h42ff0249i55b94f106010ab91@mail.gmail.com> On Mon, Jun 23, 2008 at 4:06 PM, Dick Moores wrote: > I needed to sort a list of 2-element tuples by their 2nd elements. I > couldn't see a ready-made function around to do this, so I rolled my own: ... > colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)), > ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)), > ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ] > > print sort_tuple_list_by_2nd_elements(colors) > > """ > OUTPUT: > [('khaki4', (0, 205, 205)), ('antiquewhite', (16, 78, 139)), ('cyan3', (139, > 131, 120)), ('antiquewhite1', (139, 134, 78)), ('dodgerblue4', (238, 223, > 204)), ('antiquewhite4', (250, 235, 215))] > """ > ================================================================== > It works, but did I really need to roll my own? I think I wouldn't have had > to if I understood what arguments to use for either of the built-ins, sort() > or sorted(). Can someone give me a clue? Did that really work the way you wanted!? It switched elements around between tuples, which doesn't seem right. For example, in the input list you had ('khaki4', (139, 134, 78)) in the output list that became ('khaki4', (0, 205, 205)). Assuming you just want to sort the list of tuples by the second element without actually changing the tuples, you can do the following: >>> colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)), ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)), ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ] >>> from operator import itemgetter >>> sorted_colors = sorted(colors, key=itemgetter(1)) >>> sorted_colors [('cyan3', (0, 205, 205)), ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ('khaki4', (139, 134, 78)), ('antiquewhite1', (238, 223, 204)), ('antiquewhite', (250, 235, 215))] >>> -- Jerry From kent37 at tds.net Mon Jun 23 22:30:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jun 2008 16:30:24 -0400 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <20080623200635.75FBA1E4008@bag.python.org> References: <20080623200635.75FBA1E4008@bag.python.org> Message-ID: <1c2a2c590806231330yec7df79o2b7d6d9a692a4e7d@mail.gmail.com> On Mon, Jun 23, 2008 at 4:06 PM, Dick Moores wrote: > I needed to sort a list of 2-element tuples by their 2nd elements. We just talked about this: http://thread.gmane.org/gmane.comp.python.tutor/48646/ > I > couldn't see a ready-made function around to do this, so I rolled my own: > > """ > OUTPUT: > [('khaki4', (0, 205, 205)), ('antiquewhite', (16, 78, 139)), ('cyan3', (139, > 131, 120)), ('antiquewhite1', (139, 134, 78)), ('dodgerblue4', (238, 223, > 204)), ('antiquewhite4', (250, 235, 215))] > """ Is that really what you want? You have sorted the second element of the list independently of the first - the order of first elements hasn't changed. > ================================================================== > It works, but did I really need to roll my own? I think I wouldn't have had > to if I understood what arguments to use for either of the built-ins, sort() > or sorted(). Can someone give me a clue? > > BTW what list comprehension would have accomplished the same thing as my > function? If you really want to sort the second element separately, you could use e0_list, e1_list = zip(*alist) e1_list = sorted(e1_list) # Have to use sorted; e1_list is a tuple alist_sorted_by_e1 = zip(e0_list, e1_list) Kent From Mike.Hansen at atmel.com Mon Jun 23 22:40:39 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 23 Jun 2008 14:40:39 -0600 Subject: [Tutor] Possible to import imports? In-Reply-To: <10ea1c60806231237l39c62d9erf39cc9ede5f04f34@mail.gmail.com> References: <10ea1c60806231027x3c795dcdy17219155c58103fc@mail.gmail.com><1c2a2c590806231203p4a43c06al8bdd9f2a0dd89e6a@mail.gmail.com> <10ea1c60806231237l39c62d9erf39cc9ede5f04f34@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D02A311C2@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Rob Kirkpatrick > It was mostly an exercise in understanding import > orders/precedence but I thought I might be able to use it to > simplify imports for modules within a package that might all > use the same or similar standard imports. The one I see a > lot of is modules in the package routinely importing os and > sys so I thought that if I could just import them once at the > highest package level then just have the modules import their > parent package, things would be cleaner. You make a good > point about that causing more confusion than it's worth > though, so I'll shelve that idea for the time being. > > Funny though that I did try using something like foo.datetime > but I must have buggered up something cause I couldn't get it > to work... > > Thanks Kent! > > Someone on the list can correct me if I'm wrong, but I think performing imports on the same module doesn't have any negative impact. I try to keep each of my modules importing what they need. If my main program also needs that module, I'll import it in the main program. I think it helps for readability. Also each module can stand on it's own and not use another modules import of other modules. Mike From ricaraoz at gmail.com Tue Jun 24 01:22:03 2008 From: ricaraoz at gmail.com (Ricardo Araoz) Date: Mon, 23 Jun 2008 20:22:03 -0300 Subject: [Tutor] Is this the right way to create a In-Reply-To: <1c2a2c590806221425t9f67d66v89a6d8b67cf47b76@mail.gmail.com> References: <485DCE59.70409@gmail.com> <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> <485EACF6.1090107@gmail.com> <1c2a2c590806221425t9f67d66v89a6d8b67cf47b76@mail.gmail.com> Message-ID: <4860301B.5000801@gmail.com> Kent Johnson wrote: > On Sun, Jun 22, 2008 at 3:50 PM, Zameer Manji wrote: > >> I'm quite new to OOP, so forgive me if I am missing something obvious. >> When you say that the User class should have a UserProfile as an >> attribute, would it look something like this? >> >> from lastfmapi import UserProfile >> class User (object): >> def __init__: >> self.UserProfile = UserProfile('Bob') > > Yes, that's about right. Of course 'Bob' should be an argument passed > to __init__() > >> Also what do you mean by 'accessors' for Neighbors ? > > class User(object): > ... > def getNeighbors(): > """ Returns a list of this user's neighbors """ > > and similar for getTopArtists(), etc. > A couple of caveats though. Don't forget "self", it should be : class User (object): def __init__(self): self.UserProfile = UserProfile('Bob') Passing 'Bob' to __init__ would be : class User (object): def __init__(self, User='Bob'): self.UserProfile = UserProfile(User) From kent37 at tds.net Tue Jun 24 01:37:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jun 2008 19:37:27 -0400 Subject: [Tutor] Is this the right way to create a In-Reply-To: <4860301B.5000801@gmail.com> References: <485DCE59.70409@gmail.com> <1c2a2c590806220424ld2c2d9fkafda9fa5ba37b02f@mail.gmail.com> <485EACF6.1090107@gmail.com> <1c2a2c590806221425t9f67d66v89a6d8b67cf47b76@mail.gmail.com> <4860301B.5000801@gmail.com> Message-ID: <1c2a2c590806231637y5949a69ci71b4e5383dd408d7@mail.gmail.com> On Mon, Jun 23, 2008 at 7:22 PM, Ricardo Araoz wrote: > Kent Johnson wrote: >> >> On Sun, Jun 22, 2008 at 3:50 PM, Zameer Manji wrote: >>> Also what do you mean by 'accessors' for Neighbors ? >> >> class User(object): >> ... >> def getNeighbors(): >> """ Returns a list of this user's neighbors """ >> >> and similar for getTopArtists(), etc. >> > > A couple of caveats though. > Don't forget "self", it should be : > > class User (object): > def __init__(self): > self.UserProfile = UserProfile('Bob') > > > Passing 'Bob' to __init__ would be : > > class User (object): > def __init__(self, User='Bob'): > self.UserProfile = UserProfile(User) Good catch; also def getNeighbors(self): Kent From rdm at rcblue.com Tue Jun 24 02:09:41 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 23 Jun 2008 17:09:41 -0700 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <20080623200635.75FBA1E4008@bag.python.org> References: <20080623200635.75FBA1E4008@bag.python.org> Message-ID: <20080624000955.58FEA1E4008@bag.python.org> An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jun 24 04:15:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jun 2008 22:15:34 -0400 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <20080624000955.58FEA1E4008@bag.python.org> References: <20080623200635.75FBA1E4008@bag.python.org> <20080624000955.58FEA1E4008@bag.python.org> Message-ID: <1c2a2c590806231915u3cdae8d1ta96a69e523e55548@mail.gmail.com> On Mon, Jun 23, 2008 at 8:09 PM, Dick Moores wrote: > def sort_tuple_list_by_2nd_elements(alist): > alist.sort Doesn't do anything. > alist_tup_elements_reversed = [] > for x in alist: > alist_tup_elements_reversed.append((x[1], x[0])) You should learn how to use list comprehensions: alist_tup_elements_reversed.append = [ (x[1], x[0]) for x in alist ] > alist_tup_elements_reversed.sort() > print alist_tup_elements_reversed > > alist_tup_elements_reversed_and_reversed_again = [] > for x in alist_tup_elements_reversed: > alist_tup_elements_reversed_and_reversed_again.append((x[1], x[0])) Another list comp and you have pretty much reinvented decorate-sort-undecorate (second time in a week for that!) - google it or see my link in previous thread. Kent From rdm at rcblue.com Tue Jun 24 07:15:22 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 23 Jun 2008 22:15:22 -0700 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <1c2a2c590806231915u3cdae8d1ta96a69e523e55548@mail.gmail.co m> References: <20080623200635.75FBA1E4008@bag.python.org> <20080624000955.58FEA1E4008@bag.python.org> <1c2a2c590806231915u3cdae8d1ta96a69e523e55548@mail.gmail.com> Message-ID: <20080624051535.006EC1E4008@bag.python.org> At 07:15 PM 6/23/2008, Kent Johnson wrote: >On Mon, Jun 23, 2008 at 8:09 PM, Dick Moores wrote: > > > def sort_tuple_list_by_2nd_elements(alist): > > alist.sort > >Doesn't do anything. > > > alist_tup_elements_reversed = [] > > for x in alist: > > alist_tup_elements_reversed.append((x[1], x[0])) > >You should learn how to use list comprehensions: >alist_tup_elements_reversed.append = [ (x[1], x[0]) for x in alist ] Now, that's why I don't use them. They don't make sense, I thought. But that's a typo, or a paste-o, right? You meant alist_tup_elements_reversed = [ (x[1], x[0]) for x in alist ], which works. That's a start. Thanks > > alist_tup_elements_reversed.sort() > > print alist_tup_elements_reversed > > > > alist_tup_elements_reversed_and_reversed_again = [] > > for x in alist_tup_elements_reversed: > > alist_tup_elements_reversed_and_reversed_again.append((x[1], x[0])) > >Another list comp and you have pretty much reinvented >decorate-sort-undecorate (second time in a week for that!) - google it >or see my link in previous thread. I plan to study your essay of sorting at . Also, one of the authors of OOPIP (), Michael Goldwasser (who reads this list), wrote me directly, suggesting I skip ahead in his book to chapter 14, "Sorting Algorithms", and read the first few pages. Looks understandable to me, so I will, even though that's a skip-ahead of about 300 pages for me. Dick From kent37 at tds.net Tue Jun 24 12:18:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jun 2008 06:18:28 -0400 Subject: [Tutor] I need to learn more about sorting! In-Reply-To: <20080624051535.006EC1E4008@bag.python.org> References: <20080623200635.75FBA1E4008@bag.python.org> <20080624000955.58FEA1E4008@bag.python.org> <1c2a2c590806231915u3cdae8d1ta96a69e523e55548@mail.gmail.com> <20080624051535.006EC1E4008@bag.python.org> Message-ID: <1c2a2c590806240318o3ee1d1c6u5c06bc35d597c668@mail.gmail.com> On Tue, Jun 24, 2008 at 1:15 AM, Dick Moores wrote: > At 07:15 PM 6/23/2008, Kent Johnson wrote: >> You should learn how to use list comprehensions: >> alist_tup_elements_reversed.append = [ (x[1], x[0]) for x in alist ] > > Now, that's why I don't use them. They don't make sense, I thought. But > that's a typo, or a paste-o, right? You meant > alist_tup_elements_reversed = [ (x[1], x[0]) for x in alist ], which works. Yes, a paste-o. I have a short introduction to list comprehensions here: http://personalpages.tds.net/~kent37/kk/00003.html Although the syntax takes a little getting used to, I think it is just because it is an unusual concept. I find list comps easier to write and understand than the equivalent loop. Kent From danny_laya at yahoo.com Tue Jun 24 12:23:41 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Tue, 24 Jun 2008 03:23:41 -0700 (PDT) Subject: [Tutor] Another Newbie question Message-ID: <885032.5622.qm@web59807.mail.ac4.yahoo.com> Hi I got some problem about writting convention in python. Some tutorial ask me to write this : a = 1 s = 0 print 'Enter Numbers to add to the sum.' print 'Enter 0 to quit.' while a != 0: print 'Current Sum:', s a = int(raw_input('Number? ')) s = s + a print 'Total Sum =', s And the response must be like this : Enter Numbers to add to the sum. Enter 0 to quit. Current Sum: 0 Number? 200 Current Sum: 200 Number? -15.25 Current Sum: 184.75 Number? -151.85 Current Sum: 32.9 Number? 10.00 Current Sum: 42.9 Number? 0 Total Sum = 42.9 But when I write until this : >>> a = 1 >>> s = 0 >>> print 'Enter Numbers to add the sum' I press enter, and alas my python response me : Enter Numbers to add the sum It didn't want waiting me until I finish writing the rest. I know there is some mistake about my writing convention, but what ??? Can you find it ?? But you know it's not finish,I ignore the error message and writng the rest, but until i write this: >>> while a != 0: .... print 'Current Sum:', s .... a = int(raw_input('Number?')) .... s = s+a .... print 'Total Sum =', s Oh, man... another error message : File "", line 5 print 'Total Sum =', s ^ Can you help me guys ?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Tue Jun 24 12:56:45 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 12:56:45 +0200 Subject: [Tutor] Another Newbie question In-Reply-To: <885032.5622.qm@web59807.mail.ac4.yahoo.com> References: <885032.5622.qm@web59807.mail.ac4.yahoo.com> Message-ID: <200806241256.45541.omer@no-log.org> Le Tuesday 24 June 2008 12:23:41 Danny Laya, vous avez ?crit?: > Hi I got some problem about writting convention in python. Some tutorial > ask me to write this : > > a = 1 > s = 0 > print 'Enter Numbers to add to the sum.' > print 'Enter 0 to quit.' > while a != 0: > print 'Current Sum:', s > a = int(raw_input('Number? ')) > s = s + a > print 'Total Sum =', s > > And the response must be like this : > > > But when I write until this : > >>> a = 1 > >>> s = 0 > >>> print 'Enter Numbers to add the sum' > > I press enter, and alas my python response me : > Enter Numbers to add the sum This is because you're doing this in an interactive session, so python interprets and runs each line immediately after you write them. I guess this example was supposed to be put in a file and executed from there, but you can also put all this in a function : def test_func() : a = 1 s = 0 print 'Enter numbers to add to the sum.' ... This won't do anything until you call the function: test_func() > > It didn't want waiting me until I finish writing the rest. > I know there is some mistake about my writing convention, > but what ??? Can you find it ?? > > But you know it's not finish,I ignore the error message and > > writng the rest, but until i write this: > >>> while a != 0: > > .... print 'Current Sum:', s > .... a = int(raw_input('Number?')) > .... s = s+a > .... print 'Total Sum =', s > > Oh, man... another error message : > > File "", line 5 > print 'Total Sum =', s > ^ You just forgot the most important: the error message itself :) Probably an indentation error, but we'll need the full message to help (something like "SomeError: blah blah...") -- C?dric Lucantis From bhaaluu at gmail.com Tue Jun 24 13:39:09 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 24 Jun 2008 07:39:09 -0400 Subject: [Tutor] Another Newbie question In-Reply-To: <885032.5622.qm@web59807.mail.ac4.yahoo.com> References: <885032.5622.qm@web59807.mail.ac4.yahoo.com> Message-ID: On Tue, Jun 24, 2008 at 6:23 AM, Danny Laya wrote: > Hi I got some problem about writting convention in python. Some tutorial ask > me to write this : > > a = 1 > s = 0 > print 'Enter Numbers to add to the sum.' > print 'Enter 0 to quit.' > while a != 0: > print 'Current Sum:', s > a = int(raw_input('Number? ')) > s = s + a > print 'Total Sum =', s > > And the response must be like this : > > Enter Numbers to add to the sum. > Enter 0 to quit. > Current Sum: 0 > Number? 200 > Current Sum: 200 > Number? -15.25 > Current Sum: 184.75 > Number? -151.85 > Current Sum: 32.9 > Number? 10.00 > Current Sum: 42.9 > Number? 0 > Total Sum = 42.9 > > But when I write until this : > >>>> a = 1 >>>> s = 0 >>>> print 'Enter Numbers to add the sum' > Try putting the program in a function. A function is defined using: def functionName(): Everything inside the function is indented. For example: def main(): a = 1 s = 0 print 'Enter Numbers to add to the sum.' print 'Enter 0 to quit.' while a != 0: print 'Current Sum:', s a = int(raw_input('Number? ')) s = s + a print 'Total Sum =', s main() In this example, the function is called main() and it is defined with with the keyword 'def' followed by the name of the function, parentheses, and finally a colon (:). Don't forget the colon! The body of the function is indented. Make sure you indent the lines inside the function when you are entering it in the interactive interpreter. The while loop needs more indentation with the function body! Look at it carefully! Finally, call the function. In the above example, the function is called by entering: main() on a line by itself. It is NOT a part of the function body. I hope this is helpful. I remember when I was first starting out with the Python interactive interpreter. It wasn't easy. Good luck! Stick with it. It won't be long before you look back on these beginning days and laugh. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! > I press enter, and alas my python response me : > Enter Numbers to add the sum > > It didn't want waiting me until I finish writing the rest. > I know there is some mistake about > my writing convention, > but what ??? Can you find it ?? > > But you know it's not finish,I ignore the error message and > writng the rest, but until i write this: > >>>> while a != 0: > ... print 'Current Sum:', s > ... a = int(raw_input('Number?')) > ... s = s+a > ... print 'Total Sum =', s > > Oh, man... another error message : > > File "", line 5 > print 'Total Sum =', s > ^ > > Can you help me guys ?? > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From danny_laya at yahoo.com Tue Jun 24 14:47:29 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Tue, 24 Jun 2008 05:47:29 -0700 (PDT) Subject: [Tutor] fibonacci.py task ??? Message-ID: <635556.24859.qm@web59810.mail.ac4.yahoo.com> Hi all, can you explain me what this code mean : Fibonacci.py # This program calculates the Fibonacci sequence a = 0 b = 1 count = 0 max_count = 20 while count < max_count: count = count + 1 # we need to keep track of a since we change it old_a = a old_b = b a = old_b b = old_a + old_b # Notice that the , at the end of a print statement keeps it # from switching to a new line print old_a, Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 Do you understand it ??? Can you explain me....ahhh.... you know i'm a newbie so please explain it with a simple expalanation. And I got many tutorial with title *.py(e.g: Fibonacci.py and Password.py), can you explain me what *.py mean? Thank's for helping me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Tue Jun 24 15:26:39 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 15:26:39 +0200 Subject: [Tutor] fibonacci.py task ??? In-Reply-To: <635556.24859.qm@web59810.mail.ac4.yahoo.com> References: <635556.24859.qm@web59810.mail.ac4.yahoo.com> Message-ID: <200806241526.39670.omer@no-log.org> Le Tuesday 24 June 2008 14:47:29 Danny Laya, vous avez ?crit?: > Hi all, can you explain me what this code mean : > > Fibonacci.py > > # This program calculates the Fibonacci sequence > a = 0 > b = 1 > count = 0 > max_count = 20 > while count < max_count: > count = count + 1 > # we need to keep track of a since we change it > old_a = a > old_b = b > a = old_b > b = old_a + old_b > # Notice that the , at the end of a print statement keeps it > # from switching to a new line > print old_a, > > > Output: > > 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 > > Do you understand it ??? Can you explain me....ahhh.... you know > i'm a newbie so please explain it with a simple expalanation. see http://en.wikipedia.org/wiki/Fibonacci_number > And I got many tutorial with title *.py(e.g: Fibonacci.py and Password.py), > can you explain me what *.py mean? Thank's for helping me. .py is just the extension for python source files, so you're supposed to copy the example in a file called Fibonacci.py and run it with python Fibonacci.py but of course you can choose any name you want for it. -- C?dric Lucantis From bhaaluu at gmail.com Tue Jun 24 15:34:23 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 24 Jun 2008 09:34:23 -0400 Subject: [Tutor] fibonacci.py task ??? In-Reply-To: <635556.24859.qm@web59810.mail.ac4.yahoo.com> References: <635556.24859.qm@web59810.mail.ac4.yahoo.com> Message-ID: On Tue, Jun 24, 2008 at 8:47 AM, Danny Laya wrote: > Hi all, can you explain me what this code mean : > Fibonacci.py > > # This program calculates the Fibonacci sequence > a = 0 > b = 1 > count = 0 > max_count = 20 > while count < max_count: > count = count + 1 > # we need to keep track of a since we change it > old_a = a > old_b = b > a = old_b > b = old_a + old_b > # Notice that the , at the end of a print statement keeps it > # from switching to a new line > print old_a, > > Output: > > 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 > > Do you understand it > ??? Can you explain me....ahhh.... you know > i'm a newbie so please explain it with a simple expalanation. You can start by using Google or Wikipedia to get basic definitions of things like "Fibonacci sequence". It has to do with mathematics or something? http://www.google.com http://www.wikipedia.org/ > > And I got many tutorial with title *.py(e.g: Fibonacci.py and Password.py), > can you explain me what *.py mean? Thank's for helping me. That is the file extention for a Python Script. The file extension for a BASIC script is BAS (Fibonacci.bas), for a Perl script is PL (Fibonacci.pl), for a Scheme script is SCM (Fibonacci.scm), for a Logo script is LG (Fibonacci.lg) ................. > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From j_gerdem at informatik.uni-kl.de Tue Jun 24 15:40:26 2008 From: j_gerdem at informatik.uni-kl.de (John Patrick Gerdeman) Date: Tue, 24 Jun 2008 15:40:26 +0200 Subject: [Tutor] fibonacci.py task ??? In-Reply-To: <635556.24859.qm@web59810.mail.ac4.yahoo.com> References: <635556.24859.qm@web59810.mail.ac4.yahoo.com> Message-ID: <1214314826.6861.16.camel@HunterOrion> Fibonacci.py calculates the Fibonacci numbers (the sum of the two previous numbers), also see http://en.wikipedia.org/wiki/Fibonacci_number Files that end in .py are python files. Much like .txt are text files and .odc is OpenOffice Calc file. Though you can name any file as you wish, the convention for the usual files is to use the correct extension, so to avoid confusion. (Sometimes it is preferable to use another extension, or to omit them altogether, but that's not the point I'm trying to make here) > > Fibonacci.py > # This program calculates the Fibonacci sequence > a = 0 We'll initialize the variable a as 0. Since the first element of the Fibonacci Sequence is 0 > b = 1 ?We'll initialize the variable b ?as 1. Since the second element of the Fibonacci Sequence is 1 We have to supply 0 and 1 as starting values. Without these we wouldn't know where to start our sequence. (You could potentially start the sequence anywhere, e.g at a=5 and b=7, or over all prime numbers, it would still be a Fibonacci sequence, though not the one commonly known) > count = 0 ?We'll initialize the variable count > max_count = 20 ?We'll initialize the variable max_count > while count < max_count: While count is smaller then max_count do the following > count = count + 1 Increase count > # we need to keep track of a since we change it > old_a = a > old_b = b assign a and b to two help_variables, so we don't accidently change the values > a = old_b a now holds the current sequence element > b = old_a + old_b b holds the next element > # Notice that the , at the end of a print statement keeps it > # from switching to a new line > print old_a, I guess this is supposed to show some of the programming basics, though I find the contents of the while-loop rather more confusing then necessary. From sdragon1984 at gmail.com Tue Jun 24 17:37:00 2008 From: sdragon1984 at gmail.com (nathan virgil) Date: Tue, 24 Jun 2008 11:37:00 -0400 Subject: [Tutor] Hands-on beginner's project? Message-ID: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> I'm very new to Python, and (to a slightly lesser extent) programming in general. I'd like to get some experience by practicing simple-yet-functional programs, with a bit of an emphasis on games. The first game I'd like to attempt would be a simple, non-linear story, similar to those choose-your-adventure books. I don't want to start with anything too complicated, like having mapped-out directions, or interactive objects, although I do eventually want to get into stuff like that. Python seems to me like it would be a good language for this sort of stuff. I figure I just need to use a lot of print, if/elif/else, raw_input(), and a ton and a half of variables. My problem at the moment is that I don't know how to get from one section of the story to the next. I vaguely remember reading about some language using a "goto" command for something like this, but I'm not sure how that would be handled in Python. A rough idea of what I'm trying to do (in a presumably hypothetical language) would be something like this: 0100 print "Ahead of you, you see a chasm. 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") 0300 if jump = Y: 0400 goto 1700 0500 if jump = N: 0600 goto 2100 Does this make any sense? Is there some way I could do this in Python? Any and all help is definitely appreciated! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Tue Jun 24 18:00:07 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 24 Jun 2008 12:00:07 -0400 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> Message-ID: Take a look at this page, and see if it is what you're looking for: http://www.geocities.com/ek.bhaaluu/python/index.html I haven't worked on this project in awhile because I got sidetracked by other things, but it's still on the backburner. One day I'll pick it up again. I think Text Adventure Games are ripe for learning Python Object-Oriented Programming (something I'm interested in learning). Fell free to download the source code and play around with it, modify it, whatever. It is a beginner's learning project. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! On Tue, Jun 24, 2008 at 11:37 AM, nathan virgil wrote: > I'm very new to Python, and (to a slightly lesser extent) programming in > general. I'd like to get some experience by practicing simple-yet-functional > programs, with a bit of an emphasis on games. The first game I'd like to > attempt would be a simple, non-linear story, similar to those > choose-your-adventure books. I don't want to start with anything too > complicated, like having mapped-out directions, or interactive objects, > although I do eventually want to get into stuff like that. > > > Python seems to me like it would be a good language for this sort of stuff. > I figure I just need to use a lot of print, if/elif/else, raw_input(), and a > ton and a half of variables. My problem at the moment is that I don't know > how to get from one section of the story to the next. I vaguely remember > reading about some language using a "goto" command for something like this, > but I'm not sure how that would be handled in Python. > > A rough idea of what I'm trying to do (in a presumably hypothetical > language) would be something like this: > > 0100 print "Ahead of you, you see a chasm. > 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") > 0300 if jump = Y: > 0400 goto 1700 > 0500 if jump = N: > 0600 goto 2100 > > Does this make any sense? Is there some way I could do this in Python? Any > and all help is definitely appreciated! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bgailer at gmail.com Tue Jun 24 18:20:13 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 24 Jun 2008 12:20:13 -0400 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> Message-ID: <48611EBD.9040303@gmail.com> nathan virgil wrote: > I'm very new to Python, and (to a slightly lesser extent) programming > in general. I'd like to get some experience by practicing > simple-yet-functional programs, with a bit of an emphasis on games. > The first game I'd like to attempt would be a simple, non-linear > story, similar to those choose-your-adventure books. I don't want to > start with anything too complicated, like having mapped-out > directions, or interactive objects, although I do eventually want to > get into stuff like that. > > > Python seems to me like it would be a good language for this sort of > stuff. I figure I just need to use a lot of print, if/elif/else, > raw_input(), and a ton and a half of variables. My problem at the > moment is that I don't know how to get from one section of the story > to the next. I vaguely remember reading about some language using a > "goto" command for something like this, but I'm not sure how that > would be handled in Python. > > A rough idea of what I'm trying to do (in a presumably hypothetical > language) would be something like this: > > 0100 print "Ahead of you, you see a chasm. > 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") > 0300 if jump = Y: > 0400 goto 1700 > 0500 if jump = N: > 0600 goto 2100 > > Does this make any sense? Yes > Is there some way I could do this in Python? Definitely. Python is a "structured programming language". This means it has no GOTO statement. You could, for starters, use the following algorithm: room = 1 while True: # retrieve data for current room if room == 1: desc = "Ahead of you, you see a chasm." ques = "Do you wish to try jumping over it? Y/N" destY = 2 destN = 3 elif room == 2: desc = "Ahead of you, you see a warty green ogre." ques = "Do you wish to eat it? Y/N" destY = 4 destN = 5 # etc for the rest of the rooms # ask current question and move to next room print ques ans = raw_input(ques).upper() # allow for lower case input if ans == "Y": room = destY elif ans == "N": room = destN elif ans == "Q": # give us a way out. break else: print "Please answer Y or N" Start with this. Try to get it running. Then come back with questions. Notice that I have separated the "data" (description of rooms and flow between rooms) from the program logic. This makes things a LOT easier. There are more complicated structures in Python that make game programming a LOT easier and more flexible that the above. -- Bob Gailer 919-636-4239 Chapel Hill, NC From marc.tompkins at gmail.com Tue Jun 24 18:49:37 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 24 Jun 2008 09:49:37 -0700 Subject: [Tutor] fibonacci.py task ??? In-Reply-To: <1214314826.6861.16.camel@HunterOrion> References: <635556.24859.qm@web59810.mail.ac4.yahoo.com> <1214314826.6861.16.camel@HunterOrion> Message-ID: <40af687b0806240949p109a2216l82ebbb5fdce0ac81@mail.gmail.com> On Tue, Jun 24, 2008 at 6:40 AM, John Patrick Gerdeman < j_gerdem at informatik.uni-kl.de> wrote: > (You could potentially start the sequence anywhere, e.g at a=5 and b=7, or > over all prime numbers, it > would still be a Fibonacci sequence, though not the one commonly known) > Actually, a series that follows the same rule as the Fibonacci sequence (each member is the sum of the previous two members) but starts somewhere other than 0 and 1 is called a "Lucas sequence", after a mathematician named ?douard Lucas. Put it another way: the Fibonacci sequence is just one of an infinite number of Lucas sequences. Sorry - just a bit of trivia I happened to recall. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Tue Jun 24 19:16:55 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 19:16:55 +0200 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> Message-ID: <200806241916.55194.omer@no-log.org> Le Tuesday 24 June 2008 17:37:00 nathan virgil, vous avez ?crit?: > I'm very new to Python, and (to a slightly lesser extent) programming in > general. I'd like to get some experience by practicing > simple-yet-functional programs, with a bit of an emphasis on games. The > first game I'd like to attempt would be a simple, non-linear story, similar > to those > choose-your-adventure books. I don't want to start with anything too > complicated, like having mapped-out directions, or interactive objects, > although I do eventually want to get into stuff like that. > > > Python seems to me like it would be a good language for this sort of stuff. > I figure I just need to use a lot of print, if/elif/else, raw_input(), and > a ton and a half of variables. My problem at the moment is that I don't > know how to get from one section of the story to the next. I vaguely > remember reading about some language using a "goto" command for something > like this, but I'm not sure how that would be handled in Python. > > A rough idea of what I'm trying to do (in a presumably hypothetical > language) would be something like this: > > 0100 print "Ahead of you, you see a chasm. > 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") > 0300 if jump = Y: > 0400 goto 1700 > 0500 if jump = N: > 0600 goto 2100 hmm, back to the 80's :) Hard-coding all your story would be a very bad method and a nightmare to maintain. Ideally, such a game would be written in two parts: an 'engine' which contains all the logic, and a set of datas, containing the story itself in some special form understood by the engine. One of the multiple advantages of this approach is that you will be able to easily write new stories by reusing the engine with different datas (this is what we call a 'mod' in modern games) > Does this make any sense? Is there some way I could do this in Python? Any > and all help is definitely appreciated! Python is a good choice to learn programing. Below is a simple example. It might look complicated to a beginner, but if you take the time to read the python tutorial you should be able to understand it. Of course feel free to ask for more help about it. # ------------------------------------------------------------------ # --- GAME ENGINE --- # A global map of the nodes NODES = {} # Print one node's text and ask the user for a choice. # Return the next node or None if the game is over. # def process_node (node) : tag = node[0] text = node[1] options = node[2] # print the title print print tag print '-' * len(tag) print # print the node's text print text print # if there are no options, the game is over if not options : print 'GAME OVER' return None # print the various options index = 1 for opt in options : opt_text = opt[0] opt_tag = opt[1] print 'If you want to', opt_text, 'then press', index index = index + 1 # read the user's choice print choice = int(raw_input("Your choice: ")) opt = options[choice-1] # -1 because an array starts at 0 return NODES[opt[1]] # Start the story. # def run () : # global initialisation for node in NODES_LIST : tag = node[0] NODES[tag] = node # find the starting node node = NODES["start"] # let's play now while node : node = process_node(node) print "See you for a new exciting adventure!" # --- GAME DATAS --- # All your story goes here. A 'node' is a paragraph of the story and is made # of three things: # # * a 'tag' identifying the node and used to jump from one to another # (all tags must be unique) # # * the text of the paragraph # # * a list of user choices, each option being itself a list a two items: # - a text to display # - the name (tag) of the destination node # NODES_LIST =[ [ "start", "You're in front of a door.", [["open the door", "open_door"], ["go back", "go_back"]] ], [ "open_door", "Cool, you found the Holy Graal - YOU WON!", [] ], [ "go_back", "A troll is in the way", [["fight it", "fight_troll"], ["run away", "start"]] ], [ "fight_troll", "Sorry, it's stronger than you and you die - YOU LOST!", [] ] ] # start the game run() # ------------------------------------------------------------------ -- C?dric Lucantis From muchanek at gmail.com Tue Jun 24 19:24:31 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Tue, 24 Jun 2008 20:24:31 +0300 Subject: [Tutor] Tutor Digest, Vol 52, Issue 66 In-Reply-To: References: Message-ID: <1214328271.5730.70.camel@www.kinuthia.com> On Tue, 2008-06-24 at 15:26 +0200, tutor-request at python.org wrote: > Message: 5 > Date: Tue, 24 Jun 2008 05:47:29 -0700 (PDT) > From: Danny Laya > Subject: [Tutor] fibonacci.py task ??? > To: tutor at python.org > Message-ID: <635556.24859.qm at web59810.mail.ac4.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi all, can you explain me what this code mean : > > Fibonacci.py > > # This program calculates the Fibonacci sequence > a = 0 > b = 1 > count = 0 > max_count = 20 > while count < max_count: > count = count + 1 > # we need to keep track of a since we change it > old_a = a > old_b = b > a = old_b > b = old_a + old_b > # Notice that the , at the end of a print statement keeps it > # from switching to a new line > print old_a, > > > Output: > > 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 > > Do you understand it ??? Can you explain me....ahhh.... you know > i'm a newbie so please explain it with a simple expalanation. > > And I got many tutorial with title *.py(e.g: Fibonacci.py and > Password.py), > can you explain me what *.py mean? Thank's for helping me. > If you have an algorithm to calculate the sum of exactly two(!) numbers you could do it in the Python prompt by: >>> 3+4 7 ... or you could start you fire up a text editor (something like Notepad in Windows, or nano in Linux and type "3+4"(without the quotes!), hmmm..., and save the file as anything you want, lets say for now you save the file as "threePlusFour". Every time you invoke the python interpreter (do you know how to do that?) with "threePlusFour", you will get the value seven! Because there are many programming languages, such as C, java, perl, ruby, haskell(!), you might want to be more specific as to what programming language you save saved your code in. .c for C, .rb for Ruby, .java for java and, of course .py for python. ... or you could define a function... One of the indefatigable contributors to this mailing list, Alan Gauld (where do you get the time?), has an excellent tutorial for beginners. Check it out at http://www.freenetpages.co.uk/hp/alan.gauld (correct?) Kinuthia... From rdm at rcblue.com Tue Jun 24 19:43:54 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 10:43:54 -0700 Subject: [Tutor] Astonishing timing result Message-ID: <20080624174429.BF2F11E4009@bag.python.org> An HTML attachment was scrubbed... URL: From jeffpeery at yahoo.com Tue Jun 24 20:33:24 2008 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 24 Jun 2008 11:33:24 -0700 (PDT) Subject: [Tutor] closing a internet explorer com object Message-ID: <34379.73766.qm@web43131.mail.sp1.yahoo.com> hello, I'm using internet explorer to print out html documents and I'm not sure how to close it once it is created. How do I do this? below is the simple bit of code I use to print documents. thanks! Jeff ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 0 ie.Navigate(doc_name) if ie.Busy: sleep(1) # print the current IE document without prompting # the user for the printerdialog ie.ExecWB(win32com.client.constants.OLECMDID_PRINT, win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kdsudac at yahoo.com Tue Jun 24 21:03:03 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Tue, 24 Jun 2008 12:03:03 -0700 (PDT) Subject: [Tutor] Python to exe--how much work? Message-ID: <378333.93132.qm@web54301.mail.re2.yahoo.com> Hi All, Question: How hard is it to convert python code to an exe? Details: I've written some test software in python for my company.? We'd like to be able to distribute the software without having to install python on the instrument computer. The software itself is several hundred lines of code, that imports and uses several modules: SciPy, NumPy, PIL (python imaging library) and matplotlib.? My background is in ME, so I'm far from an expert at coding and I'd still consider myself a begginer when it comes to Python.? My code is still a little cumbersome (due to my past experience in Matlab) and is far from pythonic.? I've had some success generating .exe files using pyinstaller for a few simple python programs i've written (less than 100 lines of code, that just use the os module).? How much harder will this be for longer code with more modules imported? In general I think we have a few options: 1)? If it's easy I can do it myself.? I'm just worried that including the modules will make things messy/impossible. 2)? If it's too hard for me, but easy for an expert.? We could probably hire a consultant to package. 3)? If it's too hard for anybody (unlikely).? We could have someone in-house port the code to C or VB. Any other general advice would be appreciated. Thanks, Keith -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jun 24 21:44:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jun 2008 15:44:56 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080624174429.BF2F11E4009@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> Message-ID: <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> On Tue, Jun 24, 2008 at 1:43 PM, Dick Moores wrote: > Output: > t1 is 0.000104, no function > t2 is 5.87e-006, function explicit > t3 is 0.000126, function imported > t1/t2 is 17.8 > t1/t3 is 0.827 > t3/t2 is 21.5 > > Now, I'd heard that code in a function runs faster than the same code not in > a function, but even so I was surprised at the t1/t2 ratio of 17.8. > > The astonishing (to me, anyway) result was the t3/t2 ratio. I had no idea > that importing from mycalc slowed a script down at all, let alone by a > factor of 21! Note that t1 and t3 are pretty close to each other. Perhaps you should be suspicious of t2. What if __name__ != '__main__' ? Kent From omer at no-log.org Tue Jun 24 21:50:09 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 21:50:09 +0200 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <111a9ddb0806241213g4ba6d173o842b86e4ee89009d@mail.gmail.com> References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> <200806242053.16762.omer@no-log.org> <111a9ddb0806241213g4ba6d173o842b86e4ee89009d@mail.gmail.com> Message-ID: <200806242150.09956.omer@no-log.org> > > No, it was whether or not the engine and data could be separated into two > different files, like most modern games. If I ever manage to make really > complex stuff, I might want to take a page out of Id's book and make the > engine open source. > Yes that's what you should do. In python terms, they should go in different modules (and thus in different files) but don't worry too much about that for now, the most important being to keep them clearly separated in your mind. If your code is well written it won't require a lot of work to split it when you feel the need for it. (you'll learn more about modules in the tutorial and the library reference) This is an important concept in programing : "separate the concerns". Each part of your code should focus on a simple and specific task, and should stay as independent as possible from the rest of the program. This makes the maintenance easier and improves reusability. And open source is a sure way to learn a lot and write great softwares :) -- C?dric Lucantis From wizzardx at gmail.com Tue Jun 24 22:16:56 2008 From: wizzardx at gmail.com (David) Date: Tue, 24 Jun 2008 22:16:56 +0200 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> Message-ID: <18c1e6480806241316g224d665es187614dc7b5fe13b@mail.gmail.com> On Tue, Jun 24, 2008 at 5:37 PM, nathan virgil wrote: > I'm very new to Python, and (to a slightly lesser extent) programming in > general. I'd like to get some experience by practicing simple-yet-functional > programs, with a bit of an emphasis on games. The first game I'd like to > attempt would be a simple, non-linear story, similar to those > choose-your-adventure books. I don't want to start with anything too > complicated, like having mapped-out directions, or interactive objects, > although I do eventually want to get into stuff like that. > Slightly off-topic, but you might find Ren'Py interesting: http://www.renpy.org/wiki/renpy/Home_Page Ren'Py is a Python-driven engine for visual novels. ie, interactive stories with pictures, sound, music, etc. From oldmantaggie at gmail.com Tue Jun 24 22:25:19 2008 From: oldmantaggie at gmail.com (John Chandler) Date: Tue, 24 Jun 2008 15:25:19 -0500 Subject: [Tutor] closing a internet explorer com object In-Reply-To: <34379.73766.qm@web43131.mail.sp1.yahoo.com> References: <34379.73766.qm@web43131.mail.sp1.yahoo.com> Message-ID: <8e087c6d0806241325te6e86ebx4260c908c6d524ce@mail.gmail.com> Below is a bit of code that should work, you might want to change ieregex because right now it will close anything that has "Microsoft Internet Explorer" in the title bar. Have fun. import win32con import win32gui import win32process import re def getHwnds(): def callback(hwnd, hwnds): if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd): _, found_pid = win32process.GetWindowThreadProcessId(hwnd) hwnds.append(hwnd) return True hwnds = [] win32gui.EnumWindows(callback, hwnds) return hwnds ieregex = re.compile(".*Microsoft Internet Explorer.*") for hwnd in getHwnds(): name = win32gui.GetWindowText(hwnd) if ieregex.match(name): print hwnd win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) On Tue, Jun 24, 2008 at 1:33 PM, Jeff Peery wrote: > hello, > I'm using internet explorer to print out html documents and I'm not sure > how to close it once it is created. How do I do this? below is the simple > bit of code I use to print documents. > > thanks! > Jeff > > ie = win32com.client.Dispatch("InternetExplorer.Application") > ie.Visible = 0 > ie.Navigate(doc_name) > if ie.Busy: sleep(1) > # print the current IE document without prompting > # the user for the printerdialog > ie.ExecWB(win32com.client.constants.OLECMDID_PRINT, > win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -John Chandler -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 24 22:32:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Jun 2008 21:32:52 +0100 Subject: [Tutor] Hands-on beginner's project? References: <111a9ddb0806240837k42b171edl120fbf781a2a0fe5@mail.gmail.com> Message-ID: "nathan virgil" wrote > I'm very new to Python, and (to a slightly lesser extent) > programming in > general. I'd like to get some experience by practicing > simple-yet-functional > programs, That is not a bad idea but... > I figure I just need to use a lot of print, if/elif/else, > raw_input(), and a > ton and a half of variables. That's a terrible idea! :-) > reading about some language using a "goto" command for something > like this, > but I'm not sure how that would be handled in Python. It's not. Goto is one of the bad ideas of programming from the 1960s and almost all modern languages do not support it. It leads to very unstructured programs that rapidly become unreadable and therefore unmaintainable. Python tries very hard to stop you writing bad code so it does not have a goto. > A rough idea of what I'm trying to do (in a presumably hypothetical > language) would be something like this: > > 0100 print "Ahead of you, you see a chasm. > 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") > 0300 if jump = Y: > 0400 goto 1700 > 0500 if jump = N: > 0600 goto 2100 > > Is there some way I could do this in Python? Fortunately not. However there are much better alternatives and if you take just a few hours to go through any of the non-programmers guides on the python web site you will find out what they are. I would recommend Josh Calgierri's(sp?) tutor since it is very hands-on which seems to be your preferred style but he will lead you through examples that show you how to structure your code much more effectively than using gotos. http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python/Contents In particular look at the Decisions and Defining Functions topics. I suspect you would find my tutorial to be too heavily biased to the theory and foundation stuff. But you can try it if you like, the Branching and Functions topics apply. Doing these tutorials may seem a bit slow and dry but they will save you a lot of time later and prevent you from learning a heap of bad habits that will make life harder inthe long run. (It will also save you posting lots of very basic questions here and then waiting for the replies!) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jun 24 22:37:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Jun 2008 21:37:54 +0100 Subject: [Tutor] Tutor Digest, Vol 52, Issue 66 References: <1214328271.5730.70.camel@www.kinuthia.com> Message-ID: "kinuthiA muchanE" wrote > ... or you could start you fire up a text editor (something like > Notepad > in Windows, or nano in Linux and type "3+4"(without the quotes!), Actually it would need to be print 3+4 otherwise Python would silently evaluate the expression but not display the result. > One of the indefatigable contributors to this mailing list, Alan > Gauld > (where do you get the time?), With increasing difficulty! :-) > Check it out at http://www.freenetpages.co.uk/hp/alan.gauld > (correct?) Correct, thanks for the plug! Sadly it will need to move soon since Freenet have announced that they will soon be decommissioning their free web site(*). I'm trying to decide whether to go to another free site or spend the money for a proper hosted site with dedicated domain name etc... (*) They have already blocked ftp so I can't post updates anymore :-( -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Jun 24 22:44:00 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 13:44:00 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.co m> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> Message-ID: <20080624204413.6A4E91E4009@bag.python.org> At 12:44 PM 6/24/2008, Kent Johnson wrote: >On Tue, Jun 24, 2008 at 1:43 PM, Dick Moores wrote: > > Output: > > t1 is 0.000104, no function > > t2 is 5.87e-006, function explicit > > t3 is 0.000126, function imported > > t1/t2 is 17.8 > > t1/t3 is 0.827 > > t3/t2 is 21.5 > > > > Now, I'd heard that code in a function runs faster than the same > code not in > > a function, but even so I was surprised at the t1/t2 ratio of 17.8. > > > > The astonishing (to me, anyway) result was the t3/t2 ratio. I had no idea > > that importing from mycalc slowed a script down at all, let alone by a > > factor of 21! > >Note that t1 and t3 are pretty close to each other. Perhaps you should >be suspicious of t2. What if __name__ != '__main__' ? With that, t1 is 0.000104, no function t2 is 0.000117, function explicit t3 is 0.000113, function imported t1/t2 is 0.885 t1/t3 is 0.914 t3/t2 is 0.969 Explain? Dick From broek at cc.umanitoba.ca Tue Jun 24 23:06:35 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Tue, 24 Jun 2008 16:06:35 -0500 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080624204413.6A4E91E4009@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> Message-ID: <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> ----- Message from rdm at rcblue.com --------- Date: Tue, 24 Jun 2008 13:44:00 -0700 From: Dick Moores > At 12:44 PM 6/24/2008, Kent Johnson wrote: >> On Tue, Jun 24, 2008 at 1:43 PM, Dick Moores wrote: >>> Output: >>> t1 is 0.000104, no function >>> t2 is 5.87e-006, function explicit >>> t3 is 0.000126, function imported >>> t1/t2 is 17.8 >>> t1/t3 is 0.827 >>> t3/t2 is 21.5 >>> >>> Now, I'd heard that code in a function runs faster than the same >> code not in >>> a function, but even so I was surprised at the t1/t2 ratio of 17.8. >>> >>> The astonishing (to me, anyway) result was the t3/t2 ratio. I had no idea >>> that importing from mycalc slowed a script down at all, let alone by a >>> factor of 21! >> >> Note that t1 and t3 are pretty close to each other. Perhaps you should >> be suspicious of t2. What if __name__ != '__main__' ? > > With that, > t1 is 0.000104, no function > t2 is 0.000117, function explicit > t3 is 0.000113, function imported > t1/t2 is 0.885 > t1/t3 is 0.914 > t3/t2 is 0.969 > > Explain? > > Dick Hey Dick, I'm not too clear on what it is that you want explained. It seems to me that the difference between t2 and t3 is 1) is so small as to be most likely due to (effectively) random fluctuations of your environment (the demands that other processes were making on your system at the time) and 2) so small so as to not be worth worrying about (). I'd further wager that if you repeat the timing a few times, you'll find that on some runs t2 is less than t3. Best, Brian vdB From rdm at rcblue.com Tue Jun 24 23:20:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 14:20:16 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> Message-ID: <20080624212032.7409C1E4010@bag.python.org> At 02:06 PM 6/24/2008, broek at cc.umanitoba.ca wrote: >----- Message from rdm at rcblue.com --------- > Date: Tue, 24 Jun 2008 13:44:00 -0700 > From: Dick Moores > >>At 12:44 PM 6/24/2008, Kent Johnson wrote: >>>On Tue, Jun 24, 2008 at 1:43 PM, Dick Moores wrote: >>>>Output: >>>>t1 is 0.000104, no function >>>>t2 is 5.87e-006, function explicit >>>>t3 is 0.000126, function imported >>>>t1/t2 is 17.8 >>>>t1/t3 is 0.827 >>>>t3/t2 is 21.5 >>>> >>>>Now, I'd heard that code in a function runs faster than the same >>>code not in >>>>a function, but even so I was surprised at the t1/t2 ratio of 17.8. >>>> >>>>The astonishing (to me, anyway) result was the t3/t2 ratio. I had no idea >>>>that importing from mycalc slowed a script down at all, let alone by a >>>>factor of 21! >>> >>>Note that t1 and t3 are pretty close to each other. Perhaps you should >>>be suspicious of t2. What if __name__ != '__main__' ? >> >>With that, >>t1 is 0.000104, no function >>t2 is 0.000117, function explicit >>t3 is 0.000113, function imported >>t1/t2 is 0.885 >>t1/t3 is 0.914 >>t3/t2 is 0.969 >> >>Explain? >> >>Dick > > >Hey Dick, > >I'm not too clear on what it is that you want explained. Well, Kent suggested trying if __name__ != '__main__' . Why would that make such a difference? >It seems to me that the difference between t2 and t3 is 1) is so small >as to be most likely due to (effectively) random fluctuations of your >environment (the demands that other processes were making on your >system at the time) and 2) so small so as to not be worth worrying >about (). Basically, I'm not worried, just curious. Not about the small differences, but why did the use of the standard if __name__ == '__main__' result it such speed? This was not a fluke. Before posting, I got similar results with different functions, albeit not quite as extreme. Am I not doing the timing correctly? Dick From john at fouhy.net Wed Jun 25 00:02:09 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 25 Jun 2008 10:02:09 +1200 Subject: [Tutor] closing a internet explorer com object In-Reply-To: <34379.73766.qm@web43131.mail.sp1.yahoo.com> References: <34379.73766.qm@web43131.mail.sp1.yahoo.com> Message-ID: <5e58f2e40806241502s6eb3cd48k5feb700fa5b8f743@mail.gmail.com> On 25/06/2008, Jeff Peery wrote: > hello, > I'm using internet explorer to print out html documents and I'm not sure how > to close it once it is created. How do I do this? below is the simple bit of > code I use to print documents. > > ie = > win32com.client.Dispatch("InternetExplorer.Application") You may be able to call ie.Close(True) or ie.Exit(True) or something like that -- I'm not sure. If you run the MakePy utility (from the pythonwin tools menu, or just run the script) it will generate python code that includes effectively method signatures for the different COM objects you can control. By inspecting this, you may be able to learn what methods you can call on InternetExplorer.Application objects and what arguments you need to give them. -- John. From alan.gauld at btinternet.com Wed Jun 25 00:09:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Jun 2008 23:09:45 +0100 Subject: [Tutor] Python to exe--how much work? References: <378333.93132.qm@web54301.mail.re2.yahoo.com> Message-ID: "Keith Suda-Cederquist" wrote > Question: How hard is it to convert python code to an exe? Not too hard if you know computers. Quite hard for a complete novice. py2exe seems to be the most popular option. > Details: I've written some test software in python for my company. > We'd like to be able to distribute the software without having to > install python on the instrument computer. If you'd written it in Java would you use a native compiler for Java or just install the JRE on the target PC? If you used .NET would you insist on compiling the C# to exe or just install .NET on the target? Why not do the same for python? > The software itself is several hundred lines of code, If you said 10s of thousands of lines I might be concerned. Hundreds is near trivial. > that imports and uses several modules: SciPy, NumPy, > PIL (python imaging library) and matplotlib. I'm not aware of anty issues with those modules/libraries but you never know till you try! > harder will this be for longer code with more modules imported? For a few hundred lines it shouldn't be much harder. > 3) We could have someone in-house port the code to C or VB. That shouldn't really be needed, it would be much cheaper and more reliable to just install Python - its not very big and thats all the exe 'copilers' do anyway. They just package the interpreter and libraries into a self launching file! In fact if you are going to have several such scripts you really should install Python, it will take up much less room and resource than installing a version of Python for each script! [ You may have gathered that I'm not a big fan of compiling python to exe's - I've rarely seen a valid case for it :-] -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From marilyn at deliberate.com Wed Jun 25 01:49:24 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 24 Jun 2008 16:49:24 -0700 (PDT) Subject: [Tutor] Astonishing timing result In-Reply-To: <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> Message-ID: <34169.66.218.47.125.1214351364.squirrel@mail.tigertech.net> On Tue, June 24, 2008 2:06 pm, broek at cc.umanitoba.ca wrote: > ----- Message from rdm at rcblue.com --------- > Date: Tue, 24 Jun 2008 13:44:00 -0700 > From: Dick Moores > > >> At 12:44 PM 6/24/2008, Kent Johnson wrote: >> >>> On Tue, Jun 24, 2008 at 1:43 PM, Dick Moores wrote: >>> >>>> Output: >>>> t1 is 0.000104, no function t2 is 5.87e-006, function explicit t3 is >>>> 0.000126, function imported >>>> t1/t2 is 17.8 t1/t3 is 0.827 t3/t2 is 21.5 >>>> >>>> Now, I'd heard that code in a function runs faster than the same >>>> >>> code not in >>>> a function, but even so I was surprised at the t1/t2 ratio of 17.8. >>>> >>>> >>>> The astonishing (to me, anyway) result was the t3/t2 ratio. I had >>>> no idea that importing from mycalc slowed a script down at all, let >>>> alone by a factor of 21! >>> >>> Note that t1 and t3 are pretty close to each other. Perhaps you >>> should be suspicious of t2. What if __name__ != '__main__' ? >> >> With that, >> t1 is 0.000104, no function t2 is 0.000117, function explicit t3 is >> 0.000113, function imported >> t1/t2 is 0.885 t1/t3 is 0.914 t3/t2 is 0.969 >> >> Explain? Does this mean that if __name__ == "__main__" takes the extra time? and that that's brings t2 in line with the others? and that the difference represents the time it takes to set up a code-block? Something like that? Marilyn Davis >> >> >> Dick >> > > > Hey Dick, > > > I'm not too clear on what it is that you want explained. > > > It seems to me that the difference between t2 and t3 is 1) is so small > as to be most likely due to (effectively) random fluctuations of your > environment (the demands that other processes were making on your system > at the time) and 2) so small so as to not be worth worrying about > (). > > > I'd further wager that if you repeat the timing a few times, you'll > find that on some runs t2 is less than t3. > > Best, > > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Wed Jun 25 02:27:42 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 17:27:42 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <34169.66.218.47.125.1214351364.squirrel@mail.tigertech.net > References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <34169.66.218.47.125.1214351364.squirrel@mail.tigertech.net> Message-ID: <20080625002807.E6BEC1E4009@bag.python.org> At 04:49 PM 6/24/2008, Marilyn Davis wrote: >Does this mean that if __name__ == "__main__" takes the extra time? and >that that's brings t2 in line with the others? I don't think so. Please refer to the code again: . Line 21 is if __name__ == '__main__': . Changing this line to if __name__ != '__main__': increases the time dramatically. But maybe you meant if __name__ != '__main__': ? If so, you must be correct. But what's going on here?? Hey, Kent? > and that the difference >represents the time it takes to set up a code-block? What's a code-block? Dick >Something like that? > >Marilyn Davis From kent37 at tds.net Wed Jun 25 02:35:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jun 2008 20:35:33 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080624212032.7409C1E4010@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> Message-ID: <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> On Tue, Jun 24, 2008 at 5:20 PM, Dick Moores wrote: > Basically, I'm not worried, just curious. Not about the small differences, > but why did the use of the standard if __name__ == '__main__' result > it such speed? Because __name__ is not equal to "__main__", so you were basically skipping the whole test. The most common cause of unexpected timing results is tests that don't do what you think they do. The test code is not run in the main module. You can dig into the timeit module if you want the details. > Am I not doing the timing correctly? Right. Kent From rdm at rcblue.com Wed Jun 25 02:52:17 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 17:52:17 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.co m> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> Message-ID: <20080625005231.D03231E4009@bag.python.org> At 05:35 PM 6/24/2008, Kent Johnson wrote: >On Tue, Jun 24, 2008 at 5:20 PM, Dick Moores wrote: > > > Basically, I'm not worried, just curious. Not about the small differences, > > but why did the use of the standard if __name__ == '__main__' result > > it such speed? > >Because __name__ is not equal to "__main__", so you were basically >skipping the whole test. Ah. >The most common cause of unexpected timing >results is tests that don't do what you think they do. > >The test code is not run in the main module. You can dig into the >timeit module if you want the details. OK, I'll dig. Thanks, Dick From john at fouhy.net Wed Jun 25 03:02:45 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 25 Jun 2008 13:02:45 +1200 Subject: [Tutor] Python to exe--how much work? In-Reply-To: References: <378333.93132.qm@web54301.mail.re2.yahoo.com> Message-ID: <5e58f2e40806241802m67e187f4i89d34251b3a20d4b@mail.gmail.com> On 25/06/2008, Alan Gauld wrote: > "Keith Suda-Cederquist" wrote > > that imports and uses several modules: SciPy, NumPy, > > PIL (python imaging library) and matplotlib. > I'm not aware of anty issues with those modules/libraries > but you never know till you try! I've used PIL and py2exe -- PIL does some dynamic imports that confuse py2exe's module finder. From memory, it was easy enough to fix -- you just need to include extra import statements, so that the modules you need are in the bundle. (e.g. something like "from PIL import GifImagePlugin" if you will be using GIFs) -- John. From jtp at nc.rr.com Wed Jun 25 03:32:30 2008 From: jtp at nc.rr.com (James) Date: Tue, 24 Jun 2008 21:32:30 -0400 Subject: [Tutor] python mechanize - clicking javascript button Message-ID: Hi, I'm having a bit of a problem and am hoping that someone can assist (I realize this may be slightly off-topic, but I haven't found a good place to post this question, so... ;)) I'm writing a script to interact with a website. There's a form similar to the following in the website:
...stuff... ...stuff... Everything in this form is sent to the server and push.do is the script that runs in the backend. There is *one* button, however, will change the action on the form to "delete.do", as can be seen in the javascript function definition below: function delete() { document.form.action = "delete.do"; document.form.submit(); } Seems simple enough, right? When I use mechanize and print the form that I'm working with (name="form"), I see the following: >>> br.select_form(name="form") >>> print br.form )> )>> The only other button on this form is "Commit", which apparently results in a POST to "push.do". The javascript "delete" button is the *only* entity in the form that POSTs to delete.do. The Python mechanize website states that in this situation the best thing to do is set up a POST to the web server (since mechanize cannot interpret javascript). A few things boggle me: a) When submitting the form, how do I deal with cookies? I'm unsure about how to pass the web tool the appropriate cookie (I'm not even sure the web server wants a cookie in the first place) b) Do I have to pass *all* the values listed in the "print br.form"? If not, then how do I figure out what precisely the server "requires" from a POST? (TamperData seems to indicate that most of the stuff is sent to the server on *either* button click, but I'm not sure...is there a better way to find out?) d) Is POST my only option, or is there a simpler way? I realize the only thing the javascript snippet is doing is changing the "form action" from push.do to delete.do...seems like something simple enough to change without writing code to set up a POST. (I've tried, but have not had any success, unfortunately). Can I "modify" the "form"? (how would I go about modifying br.form, anyways?) ... I found a website that explains how to set up a POST in Python using urllib2, below: http://love-python.blogspot.com/2008/04/get-content-html-source-of-url-by-http.html It structures the post as follows: url = 'http://www.example.com' values = {'key1' : 'value1', 'key2' : 'value2', 'key3' : 'value3', } try: data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page except Exception, detail: print "Err ", detail Is this the best way to set up a POST? (by configuring a dictionary with all the values that are required for the post?) I believe the last time I tried doing this the server returned a 501 error. Any thoughts *greatly* appreciated! - j From marilyn at deliberate.com Wed Jun 25 04:02:52 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue, 24 Jun 2008 19:02:52 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Astonishing timing result] Message-ID: <43559.66.218.47.125.1214359372.squirrel@mail.tigertech.net> On Tue, June 24, 2008 5:52 pm, Dick Moores wrote: > At 05:35 PM 6/24/2008, Kent Johnson wrote: > >> On Tue, Jun 24, 2008 at 5:20 PM, Dick Moores wrote: >> >> >>> Basically, I'm not worried, just curious. Not about the small >>> differences, but why did the use of the standard if __name__ == >>> '__main__' result >>> it such speed? >> >> Because __name__ is not equal to "__main__", so you were basically >> skipping the whole test. > > Ah. Ah. So the difference we see is the whole sort. That makes sense. Thank you for the understanding. Has anyone ever timed the difference between using a function that was imported with: from my_module import MyFunction and: import my_module and then my_module.MyFunction() Also, if anyone is still wondering, a "code block" is the stuff that is indented. The stuff between a ':' and the unindent. Marilyn Davis > > >> The most common cause of unexpected timing >> results is tests that don't do what you think they do. >> >> The test code is not run in the main module. You can dig into the >> timeit module if you want the details. > > OK, I'll dig. > > > Thanks, > > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From optomatic at rogers.com Wed Jun 25 05:00:51 2008 From: optomatic at rogers.com (Patrick) Date: Tue, 24 Jun 2008 23:00:51 -0400 Subject: [Tutor] python web documentation ( without frameworks?) Message-ID: <4861B4E3.9000004@rogers.com> Hi Everyone This is my first post here. I would like to switch from php/mysql to python(mod_python) and postgresql. There are several recent books on cherrypy, django and turbogears but for some reason I just don't want to use a framework. Are there any current books you could recommend for general python web programming? Most of the general web programming books seem to be from 2004 or before. Thanks-Patrick From rdm at rcblue.com Wed Jun 25 07:16:52 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 24 Jun 2008 22:16:52 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <36097.66.218.47.125.1214359253.squirrel@mail.tigertech.net > References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <36097.66.218.47.125.1214359253.squirrel@mail.tigertech.net> Message-ID: <20080625051706.C8CCB1E4009@bag.python.org> At 07:00 PM 6/24/2008, Marilyn Davis wrote: >Has anyone ever timed the difference between using a function that was >imported with: > >from my_module import MyFunction > >and: > >import my_module Here are 2 comparisons: , and I don't see a significant difference. Dick From ben at pacificu.edu Wed Jun 25 03:27:59 2008 From: ben at pacificu.edu (Ben) Date: Tue, 24 Jun 2008 18:27:59 -0700 Subject: [Tutor] Using Python in Windows Message-ID: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> Hi, I'm trying to learn Python in Windows XP. I've been going through the Python version of Allen Downey's open source textbook. I frequently find that the instructions he gives don't work for me when I try to run them in IDLE. For example, in Ch. 4 he says you should load up GASP (http://openbookproject.net//thinkCSpy/ch04.xhtml#auto10) and play around with it. Here's what happens when I try what he says to do: IDLE 1.2.2 >>> from gasp import * Traceback (most recent call last): File "", line 1, in from gasp import * ImportError: No module named gasp >>> When I try to put all the information in a module, save it, and run it, I get "there's an error in your program: invalid syntax", and it highlights instance. Below is what my module looks like. from gasp import * begin_graphics() Circle((200, 200), 60) Circle instance at (200, 200) with radius 60 Line((100, 400), (580, 200)) Line instance from (100, 400) to (590, 250) Box((400, 350), 120, 100) Box instance at (400, 350) with width 120 and height 100 end_graphics() Similarly, I can't get the truth table to work in the Exercises section at the bottom of ch. 4. I'm wondering if this is because I'm using Windows. I've tried using Ubuntu, and it doesn't display correctly. Thanks, Ben From kent37 at tds.net Wed Jun 25 10:30:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jun 2008 04:30:17 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080625051706.C8CCB1E4009@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <36097.66.218.47.125.1214359253.squirrel@mail.tigertech.net> <20080625051706.C8CCB1E4009@bag.python.org> Message-ID: <1c2a2c590806250130w700297abn4d861199ed76b599@mail.gmail.com> On Wed, Jun 25, 2008 at 1:16 AM, Dick Moores wrote: > At 07:00 PM 6/24/2008, Marilyn Davis wrote: > >> Has anyone ever timed the difference between using a function that was >> imported with: >> >> from my_module import MyFunction >> >> and: >> >> import my_module > > Here are 2 comparisons: , and > > > I don't see a significant difference. I wouldn't expect much. The only difference is the extra attribute lookup in the second form. Attribute lookup is slow enough to be measurable and fast enough that you will only care if you are doing it a lot of times. Kent From broek at cc.umanitoba.ca Wed Jun 25 10:35:46 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Wed, 25 Jun 2008 03:35:46 -0500 Subject: [Tutor] Using Python in Windows In-Reply-To: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> References: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> Message-ID: <20080625033546.vsu521q8008084w8@webware.cc.umanitoba.ca> ----- Message from ben at pacificu.edu --------- Date: Tue, 24 Jun 2008 18:27:59 -0700 From: Ben > Hi, > > I'm trying to learn Python in Windows XP. I've been going through the > Python version of Allen Downey's open source textbook. I frequently > find that the instructions he gives don't work for me when I try to > run them in IDLE. For example, in Ch. 4 he says you should load up > GASP (http://openbookproject.net//thinkCSpy/ch04.xhtml#auto10) and > play around with it. Here's what happens when I try what he says to > do: > > IDLE 1.2.2 >>>> from gasp import * > > Traceback (most recent call last): > File "", line 1, in > from gasp import * > ImportError: No module named gasp >>>> Hi Ben, gasp isn't part of python; it is a module specific to the book you are reading. There should be a link somewhere on the book's site from which you can dowload it. > When I try to put all the information in a module, save it, and run > it, I get "there's an error in your program: invalid syntax", and it > highlights instance. Below is what my module looks like. > > from gasp import * > begin_graphics() > Circle((200, 200), 60) > Circle instance at (200, 200) with radius 60 > Line((100, 400), (580, 200)) > Line instance from (100, 400) to (590, 250) > Box((400, 350), 120, 100) > Box instance at (400, 350) with width 120 and height 100 > end_graphics() If you look at the page again, you will see that the relevant text looks like: >>> from gasp import * >>> begin_graphics() >>> Circle((200, 200), 60) Circle instance at (200, 200) with radius 60 >>> Line((100, 400), (580, 200)) Line instance from (100, 400) to (590, 250) >>> Box((400, 350), 120, 100) Box instance at (400, 350) with width 120 and height 100 >>> end_graphics() >>> The `>>>' are the prompts for the interactive interpreter[*] and the lines without them are the results of running the commands typed at the prompts. So, if you want to put it into a module, you will have to include only the `>>>' lines (don't include the `>>>'s themselves, though. [*] Do you know what I mean by `interactive interpreter'? Trying to run that will take you back to your first problem. So, see if you can find a download link for the module on the book's site, and give it another go. Report back if still stymied. Best, Brian vdB From jacqui.russell at gmail.com Wed Jun 25 12:16:24 2008 From: jacqui.russell at gmail.com (Jacqui) Date: Wed, 25 Jun 2008 11:16:24 +0100 Subject: [Tutor] Hands-on beginner's project? Message-ID: <1214388984.6922.14.camel@jacqui-ubu> Hi, I'm a total newbie too, and I'm kind of replying to see if my instinct on the whole GOTO thing is correct. It's hard to learn a language without any feedback! I used GW and Color Basic when I was a kid so I know all about GOTO (and it was a mess! I programmed one of those interactive stories in grade 12 using it, it took all semester and was anything but elegant!) I would expect with Python, instead of using GOTO you use defined functions. So for instance, you could define chapters as functions def chapter2(): print "You've chosen to leap over the chasm" print "too bad you forgot you were carrying an anvil" print "What part of b-bye don't you understand?" so that in your code, instead of ?> 0100 print "Ahead of you, you see a chasm. > 0200 jump = raw_input("Do you wish to try jumping over it? Y/N") > 0300 if jump = Y: > 0400 goto 1700 > 0500 if jump = N: > 0600 goto 2100 you could have ?> 0100 print "Ahead of you, you see a chasm." > 0200 jumpQ = raw_input("Do you wish to try jumping over it? y/n: ") > 0300 if jumpQ == "y": > 0400 chapter2() > 0500 elif jumpQ == "n": > 0600 chapter3() I just tried this bit out def chapter1(): print "this is an interactive story test" print def chapter2(): print "You have chosen to leap across the chasm" print "Sadly you forgot you are carrying an anvil" print "What part of b-bye don't you understand?" def chapter3(): print "You wisely chose to turn back home" print "The anvil you are carrying would surely cause you" print "to plummet to your death" def main(): chapter1() print "You come across a chasm, would you like to jump?" jumpQ = raw_input("y/n: ") if jumpQ == "y": chapter2() elif jumpQ == "n": chapter3() main() and it worked although I have doubts about how good it would be overall once the story got very involved. I'm interested to see what others think. Jacqui From kent37 at tds.net Wed Jun 25 13:11:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jun 2008 07:11:30 -0400 Subject: [Tutor] python web documentation ( without frameworks?) In-Reply-To: <4861B4E3.9000004@rogers.com> References: <4861B4E3.9000004@rogers.com> Message-ID: <1c2a2c590806250411v4ad7f3cfh5c476a3b05cdeec2@mail.gmail.com> On Tue, Jun 24, 2008 at 11:00 PM, Patrick wrote: > Hi Everyone > > This is my first post here. I would like to switch from php/mysql to > python(mod_python) and postgresql. There are several recent books on > cherrypy, django and turbogears but for some reason I just don't want to use > a framework. Are there any current books you could recommend for general > python web programming? Most of the general web programming books seem to be > from 2004 or before. If you don't want to use a framework that pretty much limits you to plain CGI or mod_python handlers. They don't provide much so there is not much documentation. At this level of programming I don't think much has changed since 2004. The cgi module docs are one place to start: http://docs.python.org/lib/module-cgi.html Foundations of Network Programming covers many different aspects of network programming including a chapter on CGI: http://www.apress.com/book/view/1590593715 My guess is that, coming from php, you will find this level of web programming to be pretty primitive and you will soon be looking at the frameworks or at least a templating package. Kent From chester_lab at fltg.net Wed Jun 25 14:01:46 2008 From: chester_lab at fltg.net (FT) Date: Wed, 25 Jun 2008 08:01:46 -0400 Subject: [Tutor] Transporting Voices For Sapi Message-ID: <002101c8d6bb$43a05ab0$0301a8c0@brucetower> Hi! I am sending the latest version of my voice package and 2 different tests. When compiling the Voice2.py you may get an error if you do not have MSVcp.dll copied into your setup.py file. In other words a copy command to copy the dll from your system32 folder. For if you do not, some computers it is run on will fail if they do not have that dll installed. I noticed that when compiling the Voice2 using py2exe and sending it to someone else that it does not take the voices with it. I was wondering if anyone knows how that can be done? How to wrap the voices you have installed into the py2exe compiled version? Sincerely Bruce -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Sapi5.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Voice2.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: TestSapi.py URL: From omer at no-log.org Wed Jun 25 14:45:40 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Wed, 25 Jun 2008 14:45:40 +0200 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <1214388984.6922.14.camel@jacqui-ubu> References: <1214388984.6922.14.camel@jacqui-ubu> Message-ID: <200806251445.40753.omer@no-log.org> Le Wednesday 25 June 2008 12:16:24 Jacqui, vous avez ?crit?: > Hi, I'm a total newbie too, and I'm kind of replying to see if my > instinct on the whole GOTO thing is correct. It's hard to learn a > language without any feedback! > > I used GW and Color Basic when I was a kid so I know all about GOTO (and > it was a mess! I programmed one of those interactive stories in grade 12 > using it, it took all semester and was anything but elegant!) > > I would expect with Python, instead of using GOTO you use defined > functions. > > So for instance, you could define chapters as functions > > I just tried this bit out > > def chapter1(): > print "this is an interactive story test" > print > > def chapter2(): > print "You have chosen to leap across the chasm" > print "Sadly you forgot you are carrying an anvil" > print "What part of b-bye don't you understand?" > > def chapter3(): > print "You wisely chose to turn back home" > print "The anvil you are carrying would surely cause you" > print "to plummet to your death" > > > > def main(): > chapter1() > print "You come across a chasm, would you like to jump?" > jumpQ = raw_input("y/n: ") > if jumpQ == "y": > chapter2() > elif jumpQ == "n": > chapter3() > main() > > and it worked although I have doubts about how good it would be overall > once the story got very involved. I'm interested to see what others > think. > You instinct is not too bad :) but the main function will soon become unreadable and very hard to modify. In your examples the functions act as simple strings, you could write it like this: chapter1 = "This is an interactive story test" chapter2 = "..." def main () : print chapter1 ... One problem is that in such a game you often go back on your step and read the same chapter several times (ie there might be cycles in the story graph). This would be impossible to do this way. But the idea is not so bad, if the game logic is rather handled by the chapter function itself: def chapter1 () : print "You come across a chasm, would you like to jump?" jumpQ = raw_input("y/n: ") if jumpQ == "y": chapter2() elif jumpQ == "n": chapter3() def chapter2 () : print "OK, but you can still change your mind" r = raw_input("go back to the chasm ?") if r == "y" : chapter1() else : chapter4() def main () : chapter1() Which introduces another problem: as functions/chapters will be called in chain (chapter1 calls chapter2 which calls chapterX...), you will soon fill the system stack and end with a 'maximum recursion error'. But in python functions are objects which can be handled like anything else, so they could return the destination chapter rather than calling it directly, and a main loop would do the job of calling them (note there is no () after the "return chapterX", so we return the function itself without calling it) : def chapter1 () : print "..." r = raw_input("y/n: ") if r == "y" : return chapter2 else : return chapter3 def chapter2 () : ... def main () : # Store the 'chapter1' function in 'current_chapter' # without calling it current_chapter = chapter1 while True : # Call the function stored in current_chapter # and keep the returned function object. # Could also be written as 'current_chapter = current_chapter()' next_chapter = current_chapter() current_chapter = next_chapter This way the 'main' function won't have to be modified and the content of each chapter is kept in a simple logical unit. It will make the future modifications much easier. -- C?dric Lucantis From chester_lab at fltg.net Wed Jun 25 14:59:08 2008 From: chester_lab at fltg.net (FT) Date: Wed, 25 Jun 2008 08:59:08 -0400 Subject: [Tutor] Transporting Voices For Sapi and DLL Correction References: <20080625120422.8DD724091B@cloak.guaranteedservers.net> Message-ID: <001001c8d6c3$47bfd460$0301a8c0@brucetower> Hi! I am sending the latest version of my voice package and 2 different tests. When compiling the Voice2.py you may get an error if you do not have MSVcp71.dll copied into your setup.py file. In other words a copy command to copy the dll from your system32 folder. For if you do not, some computers it is run on will fail if they do not have that dll installed. I noticed that when compiling the Voice2 using py2exe and sending it to someone else that it does not take the voices with it. I was wondering if anyone knows how that can be done? How to wrap the voices you have installed into the py2exe compiled version? Sincerely Bruce ---------------------------------------------------------------------------- ---- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Wed Jun 25 15:22:55 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 25 Jun 2008 09:22:55 -0400 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <1214388984.6922.14.camel@jacqui-ubu> References: <1214388984.6922.14.camel@jacqui-ubu> Message-ID: <486246AF.6040801@gmail.com> Jacqui wrote: > Hi, I'm a total newbie too, and I'm kind of replying to see if my > instinct on the whole GOTO thing is correct. It's hard to learn a > language without any feedback! > > I used GW and Color Basic when I was a kid so I know all about GOTO (and > it was a mess! I programmed one of those interactive stories in grade 12 > using it, it took all semester and was anything but elegant!) > > I would expect with Python, instead of using GOTO you use defined > functions. > > So for instance, you could define chapters as functions > > > def chapter2(): > print "You've chosen to leap over the chasm" > print "too bad you forgot you were carrying an anvil" > print "What part of b-bye don't you understand?" > Even better is to define a Chapter class, with the various properties and methods pertinent thereto, then make each chapter an instance of that class. class Chapter: def __init__(self, desc, ques=None, **actions): self.desc = desc self.ques = ques self.actions = actions self.prompt = ", ".join(actions.keys()) def describe(self): print self.desc def ask(self): if self.ques: print self.ques for i in range(10): ans = raw_input(self.prompt).lower() next = self.actions.get(ans, None) if next: return next else: print "Invalid response" else: print "Too many failed attempts" def main(): chapters = [None]*11 # allow for 10 chapters starting with 1 chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to jump over it?", y=2, n=3) chapters[2] = Chapter("Oops - that anvil is heavy. You die.") chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5) chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2) chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3) chapters[6] = Chapter("Congratulations - you found the gold.") next = 1 while True: chapter = chapters[next] chapter.describe() next = chapter.ask() if not next: print "Game over" break main() -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Wed Jun 25 15:32:06 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 25 Jun 2008 09:32:06 -0400 Subject: [Tutor] Hands-on beginner's project? CORRECTION In-Reply-To: <486246AF.6040801@gmail.com> References: <1214388984.6922.14.camel@jacqui-ubu> <486246AF.6040801@gmail.com> Message-ID: <486248D6.8050603@gmail.com> bob gailer wrote: > Jacqui wrote: >> Hi, I'm a total newbie too, and I'm kind of replying to see if my >> instinct on the whole GOTO thing is correct. It's hard to learn a >> language without any feedback! >> >> I used GW and Color Basic when I was a kid so I know all about GOTO (and >> it was a mess! I programmed one of those interactive stories in grade 12 >> using it, it took all semester and was anything but elegant!) >> >> I would expect with Python, instead of using GOTO you use defined >> functions. >> >> So for instance, you could define chapters as functions >> >> >> def chapter2(): >> print "You've chosen to leap over the chasm" >> print "too bad you forgot you were carrying an anvil" >> print "What part of b-bye don't you understand?" >> > > Even better is to define a Chapter class, with the various properties > and methods pertinent thereto, then make each chapter an instance of > that class. > > class Chapter: > > def __init__(self, desc, ques=None, **actions): > self.desc = desc > self.ques = ques > self.actions = actions > self.prompt = ", ".join(actions.keys()) > def describe(self): > print self.desc > > def ask(self): > if self.ques: > print self.ques > for i in range(10): > ans = raw_input(self.prompt).lower() > next = self.actions.get(ans, None) > if next: > return next > else: > print "Invalid response" > else: > print "Too many failed attempts" # CORRECTION - indent > def main(): > chapters = [None]*11 # allow for 10 chapters starting with 1 > chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to > jump over it?", y=2, n=3) > chapters[2] = Chapter("Oops - that anvil is heavy. You die.") > chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5) > chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, > w=2) > chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3) > chapters[6] = Chapter("Congratulations - you found the gold.") > next = 1 > while True: > chapter = chapters[next] > chapter.describe() > next = chapter.ask() > if not next: > print "Game over" > break > > main() -- Bob Gailer 919-636-4239 Chapel Hill, NC From jacqui.russell at gmail.com Wed Jun 25 15:39:17 2008 From: jacqui.russell at gmail.com (Jacqui) Date: Wed, 25 Jun 2008 14:39:17 +0100 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <486246AF.6040801@gmail.com> References: <1214388984.6922.14.camel@jacqui-ubu> <486246AF.6040801@gmail.com> Message-ID: <1214401157.6878.4.camel@jacqui-ubu> LOL You rock! That's definitely better than my example. I can't wait to get better at this! :-D On Wed, 2008-06-25 at 09:22 -0400, bob gailer wrote: > > > > Even better is to define a Chapter class, with the various properties > and methods pertinent thereto, then make each chapter an instance of > that class. > > class Chapter: > > def __init__(self, desc, ques=None, **actions): > self.desc = desc > self.ques = ques > self.actions = actions > self.prompt = ", ".join(actions.keys()) > > def describe(self): > print self.desc > > def ask(self): > if self.ques: > print self.ques > for i in range(10): > ans = raw_input(self.prompt).lower() > next = self.actions.get(ans, None) > if next: > return next > else: > print "Invalid response" > else: > print "Too many failed attempts" > > def main(): > chapters = [None]*11 # allow for 10 chapters starting with 1 > chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to > jump over it?", y=2, n=3) > chapters[2] = Chapter("Oops - that anvil is heavy. You die.") > chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5) > chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2) > chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3) > chapters[6] = Chapter("Congratulations - you found the gold.") > next = 1 > while True: > chapter = chapters[next] > chapter.describe() > next = chapter.ask() > if not next: > print "Game over" > break > > main() > From bhaaluu at gmail.com Wed Jun 25 16:17:36 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 25 Jun 2008 10:17:36 -0400 Subject: [Tutor] Hands-on beginner's project? In-Reply-To: <1214401157.6878.4.camel@jacqui-ubu> References: <1214388984.6922.14.camel@jacqui-ubu> <486246AF.6040801@gmail.com> <1214401157.6878.4.camel@jacqui-ubu> Message-ID: Brian Wisti has a very nice tutorial for Python beginners that uses Interactive Fiction as the basis of a tutorial: http://coolnamehere.com/geekery/python/ifiction/index.html http://coolnamehere.com/geekery/python/ifiction/single-round.html http://coolnamehere.com/geekery/python/ifiction/multiple-scenes.html http://coolnamehere.com/geekery/python/ifiction/multiple-turns.html Paul McGuire made an example adventure game using pyparsing: http://wiki.python.org/moin/PyCon2006/Talks#4 http://www.geocities.com/ptmcg/python/pycon06/adventureEngine.py.txt (you'll need the pyparsing package for it to work) http://pyparsing.wikispaces.com/ Python Universe Builder (PUB) is an Interactive Fiction module for Python. It provides a programming environment similar to that of Inform or TADS but runs under any Python interpreter. http://py-universe.sourceforge.net/ Here's a link to the Interactive Fiction archive containing a huge array of text adventure games and other adventure development tools. http://www.ifarchive.org/ And finally, another link to TAGs based on Creating Adventure Games On Your Computer. http://www.geocities.com/ek.bhaaluu/python/index.html Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! On Wed, Jun 25, 2008 at 9:39 AM, Jacqui wrote: > LOL You rock! That's definitely better than my example. I can't wait to > get better at this! > > :-D > > On Wed, 2008-06-25 at 09:22 -0400, bob gailer wrote: >> > >> >> Even better is to define a Chapter class, with the various properties >> and methods pertinent thereto, then make each chapter an instance of >> that class. >> >> class Chapter: >> >> def __init__(self, desc, ques=None, **actions): >> self.desc = desc >> self.ques = ques >> self.actions = actions >> self.prompt = ", ".join(actions.keys()) >> >> def describe(self): >> print self.desc >> >> def ask(self): >> if self.ques: >> print self.ques >> for i in range(10): >> ans = raw_input(self.prompt).lower() >> next = self.actions.get(ans, None) >> if next: >> return next >> else: >> print "Invalid response" >> else: >> print "Too many failed attempts" >> >> def main(): >> chapters = [None]*11 # allow for 10 chapters starting with 1 >> chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to >> jump over it?", y=2, n=3) >> chapters[2] = Chapter("Oops - that anvil is heavy. You die.") >> chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5) >> chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2) >> chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3) >> chapters[6] = Chapter("Congratulations - you found the gold.") >> next = 1 >> while True: >> chapter = chapters[next] >> chapter.describe() >> next = chapter.ask() >> if not next: >> print "Game over" >> break >> >> main() >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Wed Jun 25 17:24:57 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Jun 2008 22:24:57 +0700 Subject: [Tutor] Another Newbie question Message-ID: <1214407497.20623.13.camel@lieryan-laptop> That's because you're doing it in interactive mode. In interactive mode, the code is treated like commands, it is executed immediately after the command is finished. You may differentiate Interactive Mode and Normal/Coding Mode by the prompt, in Coding Mode there is no prompt cause, in Interactive mode, there is the '>>>' (default) Example in Interactive Mode: >>> print 'Blah blah blah' ?Blah blah blah >>> for i in xrange(5): ... print i ... 0 1 2 3 4 >>> Some "commands", like 'for', 'while', dictionary literal, etc may require more than one line, for those, the secondary prompt is shown '...', although that depends on how you start python, if you started python from IDLE, the secondary prompt is not, by default, shown. That's a bit basic. Now to the specific reason why python (interactive mode) "doesn't wait" you to finish your command. In interactive mode, a blank line is considered to be the end of multi-line command, so: >>> for i in xrange(4): ... print i ... # The next line is empty ... 0 1 2 3 >>> that empty line is an instruction to start executing the multi-line commands immediately (or another way to see it, an empty line is considered to be the end of current instruction) From lie.1296 at gmail.com Wed Jun 25 18:05:18 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Jun 2008 23:05:18 +0700 Subject: [Tutor] Astonishing timing result Message-ID: <1214409918.20623.27.camel@lieryan-laptop> I'm a bit curious about how you do the timing. I think there is a flaw in how you measured the time. I made this code and the result is inconclusive. ## CODE: test.py #!/usr/bin/env python import imported import time from imported import * def b(): a = 1 r = range(5000000) t_a, t_b, t_c, t_d = 1000, 1000, 1000, 1000 for n in xrange(20): # a - direct, no function call start = time.time() for _ in r: a = 1 end = time.time() t_A = end - start # b - function call start = time.time() for _ in r: b() end = time.time() t_B = end - start # c - imported module start = time.time() for _ in r: imported.c() end = time.time() t_C = end - start # d - imported function start = time.time() for _ in r: c() end = time.time() t_D = end - start t_a = min(t_A, t_a) t_b = min(t_A, t_b) t_c = min(t_A, t_c) t_d = min(t_A, t_d) print t_a print t_b print t_c print t_d ## CODE: imported.py def c(): a = 1 ## OUTPUT # 1.02956604958 # 1.02956604958 # 1.02956604958 # 1.02956604958 From lie.1296 at gmail.com Wed Jun 25 18:43:47 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Jun 2008 23:43:47 +0700 Subject: [Tutor] Hands-on beginner's project? Message-ID: <1214412227.20623.52.camel@lieryan-laptop> If it was me, I'd elaborate it a bit more by separating between program (logic) and story (data). This would make it possible to tell story without touching the program's code. like this (in pseudocode): # main.py def querier(query): while True: print query.prompt t = raw_input() if t in query.ans: return query.ans[t] else: print 'Unrecognized prompt' def tell(storyfile): """ Tell a story and process response """ # read from the storyfile, the node print storyfile.story try: if storyfile.end: quit() except AttributeError: pass # process the prompts and answers if storyfile.query: return querier(storyfile.query) def main(): while True: nextstory = tell(story) if nextstory = ending: break else: story = nextstory # chapter1.sto this is an interactive story test ?You come across a chasm, would you like to jump? y ? n? ?# chapter2.sto You have chosen to leap across the chasm Sadly you forgot you are carrying an anvil What part of b-bye don't you understand? ?# chapter3.sto You wisely chose to turn back home The anvil you are carrying would surely cause you to plummet to your death From kent37 at tds.net Wed Jun 25 18:56:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jun 2008 12:56:22 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <1214409918.20623.27.camel@lieryan-laptop> References: <1214409918.20623.27.camel@lieryan-laptop> Message-ID: <1c2a2c590806250956vad7667cmce2190b92c6ec755@mail.gmail.com> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan wrote: > t_a = min(t_A, t_a) > t_b = min(t_A, t_b) > t_c = min(t_A, t_c) > t_d = min(t_A, t_d) What is this for? It should at least be t_B, t_C, t_D. > ## OUTPUT > # 1.02956604958 > # 1.02956604958 > # 1.02956604958 > # 1.02956604958 It's *very easy* to write bogus timing tests, as this thread demonstrates. Some protections: - when comparing different implementations of a function, make sure each implementation returns the correct result by checking the return value. You probably want to make this check outside the actual timing test. - when your results don't make sense, suspect your tests. Kent Kent From lie.1296 at gmail.com Wed Jun 25 20:06:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Jun 2008 01:06:53 +0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806250956vad7667cmce2190b92c6ec755@mail.gmail.com> References: <1214409918.20623.27.camel@lieryan-laptop> <1c2a2c590806250956vad7667cmce2190b92c6ec755@mail.gmail.com> Message-ID: <1214417213.20623.64.camel@lieryan-laptop> On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote: > On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan wrote: > > > t_a = min(t_A, t_a) > > t_b = min(t_A, t_b) > > t_c = min(t_A, t_c) > > t_d = min(t_A, t_d) > > What is this for? It should at least be t_B, t_C, t_D. A common pitfall in benchmarking is averaging the benchmark result. That is WRONG, FLAT WRONG. Why? Variations of how long a code is executed is caused by the environment, not the code itself. The correct way to benchmark is to use the one with the lowest time (i.e. min() function), since the lowest one is the one that is least interfered by the environment. > > ## OUTPUT > > # 1.02956604958 > > # 1.02956604958 > > # 1.02956604958 > > # 1.02956604958 > > It's *very easy* to write bogus timing tests, as this thread > demonstrates. Some protections: > - when comparing different implementations of a function, make sure > each implementation returns the correct result by checking the return > value. Since the purpose of the test is to benchmark the difference of where the code is located, we should use a very simple function, that doesn't even do much of anything, thus 'a = 1'. If that simple code is substituted with anything else, I'm still confident that the result won't be far off. > You probably want to make this check outside the actual timing > test. Actually the timing is all equal because of the timer's resolution. I don't have a high-precision timer on hand. > - when your results don't make sense, suspect your tests. > Kent > Kent From muchanek at gmail.com Wed Jun 25 20:50:15 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Wed, 25 Jun 2008 21:50:15 +0300 Subject: [Tutor] Tutor Digest, Vol 52, Issue 69 In-Reply-To: References: Message-ID: <1214419815.5947.21.camel@www.kinuthia.com> On Wed, 2008-06-25 at 01:49 +0200, tutor-request at python.org wrote: > > ... or you could start you fire up a text editor (something like > > Notepad > > in Windows, or nano in Linux and type "3+4"(without the quotes!), > > Actually it would need to be > > print 3+4 > > otherwise Python would silently evaluate the expression but > not display the result. Oh my, I was in the middle of something, something like http://projecteuler.net/index.php?section=problems&id=74 > > > One of the indefatigable contributors to this mailing list, Alan > > Gauld > > (where do you get the time?), > > With increasing difficulty! :-) I can understand that. > > > Check it out at http://www.freenetpages.co.uk/hp/alan.gauld > > (correct?) > > Correct, thanks for the plug! > > Sadly it will need to move soon since Freenet have > announced that they will soon be decommissioning > their free web site(*). I'm trying to decide whether to go to > another free site or spend the money for a proper > hosted site with dedicated domain name etc... Here (in Kenya) the cheapest unlimited internet access option costs you around 9600 Kenya Shillings, about $146 a month! I am already stumped! > > (*) They have already blocked ftp so I can't post updates > anymore :-( Dommage, dommage... > From kent37 at tds.net Wed Jun 25 21:53:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jun 2008 15:53:09 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <1214417213.20623.64.camel@lieryan-laptop> References: <1214409918.20623.27.camel@lieryan-laptop> <1c2a2c590806250956vad7667cmce2190b92c6ec755@mail.gmail.com> <1214417213.20623.64.camel@lieryan-laptop> Message-ID: <1c2a2c590806251253k637999ceka84b2df534c62c5@mail.gmail.com> On Wed, Jun 25, 2008 at 2:06 PM, Lie Ryan wrote: > On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote: >> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan wrote: >> >> > t_a = min(t_A, t_a) >> > t_b = min(t_A, t_b) >> > t_c = min(t_A, t_c) >> > t_d = min(t_A, t_d) >> >> What is this for? It should at least be t_B, t_C, t_D. > > A common pitfall in benchmarking is averaging the benchmark result. That > is WRONG, FLAT WRONG. Yes, I agree. I missed the outer loop that this is in. But your code is still WRONG, FLAT WRONG! t_b = min( *** t_A ***, t_b) // should be t_B, etc. >> > ## OUTPUT >> > # 1.02956604958 >> > # 1.02956604958 >> > # 1.02956604958 >> > # 1.02956604958 >> >> It's *very easy* to write bogus timing tests, as this thread >> demonstrates. Some protections: >> - when comparing different implementations of a function, make sure >> each implementation returns the correct result by checking the return >> value. > Actually the timing is all equal because of the timer's resolution. I > don't have a high-precision timer on hand. Or maybe they are all equal because they are all t_A... Kent From alan.gauld at btinternet.com Wed Jun 25 22:23:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Jun 2008 21:23:19 +0100 Subject: [Tutor] python web documentation ( without frameworks?) References: <4861B4E3.9000004@rogers.com> Message-ID: "Patrick" wrote > cherrypy, django and turbogears but for some reason I just don't > want to use a framework. Are there any current books you could > recommend for general python web programming? Most of the general > web programming books seem to be from 2004 or before. There's a good reason for that! Vanilla CGI - the most basic web programming mechanism available is a rsource hog, non scaleable and very hard to maintain beyiond small trivial projects. So people have moved to Frameworks which offer better performance, easier implementation and far better maintainablility. All Frameworks aim to achieve that, the choice is pretty much a personal prefernce. The good news is that if you want to continuously reinvent the wheel by using vanilla CGI the books from 2004 will all pretty much still work. CGI hasn't changed much and neither have the core web modules in Python. HTH, From chase.mp at gmail.com Wed Jun 25 23:21:25 2008 From: chase.mp at gmail.com (chase pettet) Date: Wed, 25 Jun 2008 16:21:25 -0500 Subject: [Tutor] Removing files based upon time stamps Message-ID: I'm trying to create a basic script that will remove old backup files (more than 30 days) from a directory based upon timestamp. The system it will run on is Windows XP. I created this and ran it on one box and it seemed to work fine, when I ported it to the actual box it needs to run on it is not removing the files. I ran the script with "python -i" so it dumped me into interactive mode and I confirmed that the current object was ok, I confirmed it is in the correct directory, I confirmed I could so a manual os.remove("file") and it would actually delete the file. This makes me think it is not a permissions issue. But when I run the script it is a no go. I'm basically at a loss as to what to try for troubleshooting next. Backstory, this directory is an iis ftp directory if that makes a difference. import os, time, sys current = time.time() os.chdir("c:\BACKUPS\DEV1") for f in os.listdir('.'): modtime = os.path.getmtime('.') if modtime < current - 30 * 86400: os.remove(f) This is my first list post. Thanks for any help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Jun 25 23:35:16 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Jun 2008 04:35:16 +0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806251253k637999ceka84b2df534c62c5@mail.gmail.com> References: <1214409918.20623.27.camel@lieryan-laptop> <1c2a2c590806250956vad7667cmce2190b92c6ec755@mail.gmail.com> <1214417213.20623.64.camel@lieryan-laptop> <1c2a2c590806251253k637999ceka84b2df534c62c5@mail.gmail.com> Message-ID: <1214429716.6821.47.camel@lieryan-laptop> On Wed, 2008-06-25 at 15:53 -0400, Kent Johnson wrote: > On Wed, Jun 25, 2008 at 2:06 PM, Lie Ryan wrote: > > On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote: > >> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan wrote: > >> > >> > t_a = min(t_A, t_a) > >> > t_b = min(t_A, t_b) > >> > t_c = min(t_A, t_c) > >> > t_d = min(t_A, t_d) > >> > >> What is this for? It should at least be t_B, t_C, t_D. > > > > A common pitfall in benchmarking is averaging the benchmark result. That > > is WRONG, FLAT WRONG. > > Yes, I agree. I missed the outer loop that this is in. But your code > is still WRONG, FLAT WRONG! > t_b = min( *** t_A ***, t_b) // should be t_B, etc. Ah, yes sorry, a slip of hand when copying the code. The corrected timing. Outer loop: 10x Inner Loop: 5000000x per Innerloop Overall a | 1.05028605461 | 10.6743688583 ?b | 2.21457099915 | 22.3394482136 ?c | 3.53437685966 | 35.6701157093 ?d | 2.5965359211 | 26.1492891312 Overall Running Time: 94.8337771893 Well, it's obvious that direct-method is the fastest, simply because it bypasses function calling and module name look up ?overhead. Method C (module) is the slowest because the name look up is done twice, the module's name then the function's name inside the module, then function calling. But anyway, considering that this overhead of (3.5 - 1 = 2.5 second) is accumulated over 5 000 000 iteration, it is silly to to use method-a (not using function and method) for reason of speed. The difference between method a and c is 2.5 second / 5 000 000 = 0.0000005 second = 0.5 microsecond. (DISCLAIMER: Timing is valid on my machine only) Sure, at a glance, it seems that the saving is good enough 1:3.5, that's 28.6% a saving of 71.4%, but remember that most functions are much more complex than this 'a = 1', to put it into perspective: a = n**2 ?Outer loop: 10x Inner Loop: 5000000x a | 2.1795668602 | 21.9916498661 b | 3.4880130291 | 35.1593179703 c | 4.97427606583 | 50.6705505848 d | 3.84812307358 | 39.1990897655 time: 43%, saving 57% ? 'a = math.sqrt(n ** 2 + n ** 2)' ?'print 1' ?Outer loop: 10x Inner Loop: 50000x a | 0.805603027344 | 8.24900960922 b | 0.921233177185 | 9.31604623795 c | 1.03809094429 | 10.4301710129 d | 0.956300973892 | 9.58661794662 Total Time: 37.582244873 time: 78%, saving: 22% 'print 1' ?Outer loop: 10x Inner Loop: 50000x ? per Innerloop Overall a | 0.573838949203 | 6.04536104202 ?b | 0.578473091125? | 6.05607891083 ?c | 0.579005002975? | 6.08867025375 ?d | 0.570523023605? | 5.93990397453 Negligible. So unless your function is extremely simple like 'a = 1', there is no benefit of avoiding function/methods. A single print statement (print is a very slow function/statement) would immediately nullify the speed gain. Even an intermediate complexity function would make the saving useless, and to think about it, I think nobody would make 'a = 1' to be a function right? > >> > ## OUTPUT > >> > # 1.02956604958 > >> > # 1.02956604958 > >> > # 1.02956604958 > >> > # 1.02956604958 > >> > >> It's *very easy* to write bogus timing tests, as this thread > >> demonstrates. Some protections: > >> - when comparing different implementations of a function, make sure > >> each implementation returns the correct result by checking the return > >> value. > > > Actually the timing is all equal because of the timer's resolution. I > > don't have a high-precision timer on hand. > > Or maybe they are all equal because they are all t_A... > > Kent From lie.1296 at gmail.com Wed Jun 25 23:53:14 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Jun 2008 04:53:14 +0700 Subject: [Tutor] Removing files based upon time stamps Message-ID: <1214430794.6821.52.camel@lieryan-laptop> I'm not sure what caused your problem, but... > ?os.chdir("c:\BACKUPS\DEV1") This is a no-no. What if you have a path like this: 'C:\nice\try' what do you think would python be doing? It would parse \n as newline and \t as tab You should do this instead: r'?C:\nice\try' OR 'C:\\nice\\try' the first way is called raw string, the backslash lose its meaning the second way is by escaping the backslash. From steve at alchemy.com Wed Jun 25 23:51:45 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 25 Jun 2008 14:51:45 -0700 Subject: [Tutor] Removing files based upon time stamps In-Reply-To: <1214430794.6821.52.camel@lieryan-laptop> References: <1214430794.6821.52.camel@lieryan-laptop> Message-ID: <20080625215145.GA39651@dragon.alchemy.com> On Thu, Jun 26, 2008 at 04:53:14AM +0700, Lie Ryan wrote: > I'm not sure what caused your problem, but... Look at where you're checking the file time. You're not checking the file itself, but '.' (the time of the current directory). -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at alchemy.com Wed Jun 25 23:52:40 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 25 Jun 2008 14:52:40 -0700 Subject: [Tutor] Removing files based upon time stamps In-Reply-To: <1214430794.6821.52.camel@lieryan-laptop> References: <1214430794.6821.52.camel@lieryan-laptop> Message-ID: <20080625215240.GB39651@dragon.alchemy.com> You might also want to consider using the path walk facility in Python's standard lib as well, so you can recurse into subdirectories doing this (if that is helpful) -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Thu Jun 26 00:02:02 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 25 Jun 2008 22:02:02 +0000 (GMT) Subject: [Tutor] Fw: python web documentation ( without frameworks?) Message-ID: <35387.39997.qm@web86701.mail.ukl.yahoo.com> Forwarding to list. Please use Reply All when reponding to posts. ----- Forwarded Message ---- From: Jeff Johnson To: Alan Gauld Sent: Wednesday, 25 June, 2008 9:51:33 PM Subject: Re: [Tutor] python web documentation ( without frameworks?) This was crazy. The presenter at our Python user group last night left everything at home. So he proceeded to borrow someone's laptop, download and install Python and web.py (http://webpy.org/) and we all went through building the demo which displayed records in an SQLite table and allowed you to add one and redisplay. I have used Django and web.py works pretty much the same way using templates and all, but web.py is significantly "lighter". You might want to install web.py and go through the demo. Put it in a folder called "deleteme" and you can just delete the folder if you're not interested. Alan Gauld wrote: > > "Patrick" wrote > >> cherrypy, django and turbogears but for some reason I just don't want >> to use a framework. Are there any current books you could recommend >> for general python web programming? Most of the general web >> programming books seem to be from 2004 or before. > > There's a good reason for that! Vanilla CGI - the most basic web > programming mechanism available is a rsource hog, non scaleable > and very hard to maintain beyiond small trivial projects. So people > have moved to Frameworks which offer better performance, > easier implementation and far better maintainablility. All Frameworks > aim to achieve that, the choice is pretty much a personal prefernce. > > The good news is that if you want to continuously reinvent the wheel > by using vanilla CGI the books from 2004 will all pretty much still work. > CGI hasn't changed much and neither have the core web modules in > Python. > > HTH, -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From broek at cc.umanitoba.ca Thu Jun 26 00:17:59 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Wed, 25 Jun 2008 17:17:59 -0500 Subject: [Tutor] Removing files based upon time stamps In-Reply-To: <1214430794.6821.52.camel@lieryan-laptop> References: <1214430794.6821.52.camel@lieryan-laptop> Message-ID: <20080625171759.mn89v0ifk8owkgg8@webware.cc.umanitoba.ca> ----- Message from lie.1296 at gmail.com --------- Date: Thu, 26 Jun 2008 04:53:14 +0700 From: Lie Ryan Reply-To: lie.1296 at gmail.com Subject: [Tutor] Removing files based upon time stamps To: tutor at python.org > I'm not sure what caused your problem, but... > >> ?os.chdir("c:\BACKUPS\DEV1") > > This is a no-no. What if you have a path like this: > 'C:\nice\try' > > what do you think would python be doing? > It would parse \n as newline and \t as tab > > You should do this instead: > r'?C:\nice\try' > OR > 'C:\\nice\\try' > > the first way is called raw string, the backslash lose its meaning > the second way is by escaping the backslash. Or, better still, 'C:/nice/try' --- windows accepts the fwd slash as a path separator. Best, Brian vdB From optomatic at rogers.com Thu Jun 26 00:47:00 2008 From: optomatic at rogers.com (Patrick) Date: Wed, 25 Jun 2008 18:47:00 -0400 Subject: [Tutor] python web documentation ( without frameworks?) In-Reply-To: <35387.39997.qm@web86701.mail.ukl.yahoo.com> References: <35387.39997.qm@web86701.mail.ukl.yahoo.com> Message-ID: <4862CAE4.5000102@rogers.com> Thanks guys for responding to my post. I did buy a book on turbogears today and I am watching some screencasts as well, I don't want to be ignorant of frameworks. I don't think anyone could argue that working without a framework is better for the majority of people, I can clearly see the value of frameworks. However the idea of having a bunch of directories that I don't understand does not appeal to me, and learning a framework specific way of working with MySql, Postgresql etc rather then their native manner won't help me to transfer that knowledge into other areas such as desktop applications or other languages such as C. I have been working with PHP and I don't really like it. However there is tons of code out there that I can copy, paste and modify, I don't need to re-invent the wheel, just modify it for my own needs. This does not seem to be the case with mod_python code. Would it be logical for me to take python cgi code and rework it for mod_python? The two don't seem that different, am I wrong about this? Kent was saying that working without a framework would be fairly primitive, are there features I just can't get without a framework? If so why is this? Is a framework not just a collection of off the shelf technologies bundled into a slick package? Can I not access the same features without a framework? Am I the only one who wants an end-to-end understanding of my web app? Am I crazy? I am feeling a bit alienated here-Patrick ALAN GAULD wrote: > Forwarding to list. > Please use Reply All when reponding to posts. > > ----- Forwarded Message ---- > From: Jeff Johnson > To: Alan Gauld > Sent: Wednesday, 25 June, 2008 9:51:33 PM > Subject: Re: [Tutor] python web documentation ( without frameworks?) > > This was crazy. The presenter at our Python user group last night left > everything at home. So he proceeded to borrow someone's laptop, > download and install Python and web.py (http://webpy.org/) and we all > went through building the demo which displayed records in an SQLite > table and allowed you to add one and redisplay. I have used Django and > web.py works pretty much the same way using templates and all, but > web.py is significantly "lighter". > > You might want to install web.py and go through the demo. Put it in a > folder called "deleteme" and you can just delete the folder if you're > not interested. > > Alan Gauld wrote: > >> "Patrick" wrote >> >> >>> cherrypy, django and turbogears but for some reason I just don't want >>> to use a framework. Are there any current books you could recommend >>> for general python web programming? Most of the general web >>> programming books seem to be from 2004 or before. >>> >> There's a good reason for that! Vanilla CGI - the most basic web >> programming mechanism available is a rsource hog, non scaleable >> and very hard to maintain beyiond small trivial projects. So people >> have moved to Frameworks which offer better performance, >> easier implementation and far better maintainablility. All Frameworks >> aim to achieve that, the choice is pretty much a personal prefernce. >> >> The good news is that if you want to continuously reinvent the wheel >> by using vanilla CGI the books from 2004 will all pretty much still work. >> CGI hasn't changed much and neither have the core web modules in >> Python. >> >> HTH, >> > > From kent37 at tds.net Thu Jun 26 01:25:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jun 2008 19:25:50 -0400 Subject: [Tutor] python web documentation ( without frameworks?) In-Reply-To: <4862CAE4.5000102@rogers.com> References: <35387.39997.qm@web86701.mail.ukl.yahoo.com> <4862CAE4.5000102@rogers.com> Message-ID: <1c2a2c590806251625u2c9058e0r3e6bad1c67d29970@mail.gmail.com> On Wed, Jun 25, 2008 at 6:47 PM, Patrick wrote: > I don't think anyone could argue that working without a framework is better > for the majority of people, I can clearly see the value of frameworks. > However the idea of having a bunch of directories that I don't understand > does not appeal to me, and learning a framework specific way of working with > MySql, Postgresql etc rather then their native manner won't help me to > transfer that knowledge into other areas such as desktop applications or > other languages such as C. There are a number of different ways of working with databases in Python. You can use DB-API which is a fairly simple interface to SQL. You can use SQLAlchemy to make easier to write the SQL. You can use SQLAlchemy, SQLObject or other ORMs to hide the SQL pretty thoroughly. Most of these methods are portable to other Python apps including desktop apps. None of them are truly portable to other languages though if you stick with DB-API the SQL knowledge will certainly apply in other languages. > > I have been working with PHP and I don't really like it. However there is > tons of code out there that I can copy, paste and modify, I don't need to > re-invent the wheel, just modify it for my own needs. This does not seem to > be the case with mod_python code. mod_python by itself is not too popular IMO. > Would it be logical for me to take python cgi code and rework it for > mod_python? The two don't seem that different, am I wrong about this? I think you could do that. Do you have Python CGI code to start with? > Kent was saying that working without a framework would be fairly primitive, > are there features I just can't get without a framework? If so why is this? > Is a framework not just a collection of off the shelf technologies bundled > into a slick package? Can I not access the same features without a > framework? Python is a general-purpose language, it is not specific to web programming. It has basic facilities built in for, for example, socket communication, sending email, http requests, etc. There are many features you will want in a web app that have to be built on top of the basic capabilities of the language and standard libs. For example, - request parsing - request dispatching - authentication and authorization - session management - object-relational mapping - etc, etc., just look at the feature lists of any of the existing frameworks. I don't think you understand how little you get with plain Python. I'm not dissing Python, but again, it is a general purpose language, it doesn't provide the same facilities as a single-purpose language like php. Maybe you should try writing a CGI to see what is available. TurboGears and Pylons do use off-the-shelf technologies, though they are still third-party technology. Certainly you can use SQLAlchemy, Genshi, Routes, etc without TurboGears, or you can write equivalent features yourself, or you can let someone else help with picking components and gluing them together. Not every framework repackages other off-the-shelf components. Django is just Django, AFAIK so is web.py. Anyway, it really is your choice. If your needs are simple, or you want to learn how stuff works, you can use plain CGI or mod_python. If you will need the features of a framework, you might be better off starting with a framework. Kent From alan.gauld at btinternet.com Thu Jun 26 02:29:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jun 2008 01:29:50 +0100 Subject: [Tutor] python web documentation ( without frameworks?) References: <35387.39997.qm@web86701.mail.ukl.yahoo.com><4862CAE4.5000102@rogers.com> <1c2a2c590806251625u2c9058e0r3e6bad1c67d29970@mail.gmail.com> Message-ID: "Kent Johnson" wrote > Anyway, it really is your choice. If your needs are simple, or you > want to learn how stuff works, you can use plain CGI or mod_python. > If > you will need the features of a framework, you might be better off > starting with a framework. I'd go so far as to say that its a good idea to write ONE web app using CGI just to get a feel for it and to understand howmuch (or little) a framework gives you. But to use CGI as your normal web tool would be a bit like using assembler when you could use C or using C when you could use python... Its possible but just a lot more work. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jun 26 02:31:27 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jun 2008 01:31:27 +0100 Subject: [Tutor] Removing files based upon time stamps References: <1214430794.6821.52.camel@lieryan-laptop> Message-ID: "Lie Ryan" wrote > You should do this instead: > r'?C:\nice\try' > OR > 'C:\\nice\\try' > > the first way is called raw string, the backslash lose its meaning > the second way is by escaping the backslash. Or just use forward slashes which work on *nix or windows... 'C:/nice/try' HTH, Alan G. From marc.tompkins at gmail.com Thu Jun 26 02:40:32 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 25 Jun 2008 17:40:32 -0700 Subject: [Tutor] Removing files based upon time stamps In-Reply-To: References: Message-ID: <40af687b0806251740h658b56beq1cb94d5788e6fdea@mail.gmail.com> On Wed, Jun 25, 2008 at 2:21 PM, chase pettet wrote: > import os, time, sys > current = time.time() > os.chdir("c:\BACKUPS\DEV1") > > for f in os.listdir('.'): > modtime = os.path.getmtime('.') > if modtime < current - 30 * 86400: > os.remove(f) > I'm not in a place where I can test anything at the moment, but the first thing I always do in situations like this is to throw print/logging statements all over the place so I can see what's going on. (Slows it down terribly, but it's temporary, right?) I would do something like this: for f in os.listdir('.'): modtime = os.path.getmtime('.') print f, modtime if modtime < current - 30 * 86400: print f, " should be removed... is it?" os.remove(f) At least it'll give you some idea of where things are going wrong. As I say, it's always the first thing I try. It's rarely the last. > This is my first list post. Thanks for any help! > Welcome to the list! Pull up a chair... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marilyn at deliberate.com Thu Jun 26 02:50:14 2008 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed, 25 Jun 2008 17:50:14 -0700 (PDT) Subject: [Tutor] Astonishing timing result In-Reply-To: <20080625051706.C8CCB1E4009@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <36097.66.218.47.125.1214359253.squirrel@mail.tigertech.net> <20080625051706.C8CCB1E4009@bag.python.org> Message-ID: <33213.66.218.47.125.1214441414.squirrel@mail.tigertech.net> On Tue, June 24, 2008 10:16 pm, Dick Moores wrote: > At 07:00 PM 6/24/2008, Marilyn Davis wrote: > > >> Has anyone ever timed the difference between using a function that was >> imported with: >> >> from my_module import MyFunction >> >> and: >> >> >> import my_module > > Here are 2 comparisons: , > and > > I don't see a significant difference. Good. Thank you. I'm attaching another astonishing timing result, also wrong. It's probably always true that if a timing result is astonishing, there's a mistake somewhere, maybe in your thinking. This one compares using os.popen, os.listdir, and subprocess.Popen. Marilyn Davis > > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: labxxx_1.py Type: text/x-python Size: 3126 bytes Desc: not available URL: From muchanek at gmail.com Thu Jun 26 07:46:51 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Thu, 26 Jun 2008 08:46:51 +0300 Subject: [Tutor] Invoking Python In-Reply-To: <947637.75540.qm@web59815.mail.ac4.yahoo.com> References: <947637.75540.qm@web59815.mail.ac4.yahoo.com> Message-ID: <1214459211.5721.23.camel@www.kinuthia.com> On Tue, 2008-06-24 at 11:11 -0700, Danny Laya wrote: > ... or you could start you fire up a text editor (something like > Notepad > in Windows, or nano in Linux and type "3+4"(without the quotes!), > hmmm..., and save the file as anything you want, lets say for now you > save the file as "threePlusFour". Every time you invoke the python > interpreter (do you know how to do that?) with "threePlusFour", you > will > get the value seven! > > Well HE..HE i don't know. Let say I write the "threePlusFour" file in > /home/danny/threePlusFour.py > How I can invoke that file > ??? >From the forward slashes in the file path I assume you are using a Linux based OS, Ubuntu perhaps? Well, to use python you need to to start the terminal or the shell. In Ubuntu, go to Main Menu ==> Accessories and click on Terminal, you will now have a new window open with something like this --- kinuthia at tchane:~$ . Enter the name "python" followed by the name of your file. In this case you should enter "python /home/danny/threePlusFour.py"(without the quotes!). If you want to enter into the Python interactive prompt, simply type python and you should be rewarded with something like: Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> The ">>>" there means python is waiting for you to enter commands. Try 3+4, or 4/3 Does this help? Kinuthia... From rdm at rcblue.com Thu Jun 26 09:18:30 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 26 Jun 2008 00:18:30 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080625005231.D03231E4009@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> Message-ID: <20080626071843.7078B1E4003@bag.python.org> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 26 10:59:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jun 2008 09:59:46 +0100 Subject: [Tutor] Invoking Python References: <947637.75540.qm@web59815.mail.ac4.yahoo.com> <1214459211.5721.23.camel@www.kinuthia.com> Message-ID: "kinuthiA muchanE" wrote >>From the forward slashes in the file path I assume you are > using a Linux based OS > you need to to start the terminal or the shell. In Ubuntu, go to > Main > Menu ==> Accessories and click on Terminal, you will now have a new > window open with something like this --- kinuthia at tchane:~$ . > > Enter the name "python" followed by the name of your file. Or more commonly add a first line like: #! /path/to/python/executable Then you can simply make the file executable and run it by typing its name $ threeplusfour.py or double clicking it in your favourite file manager GUI tool. See the topic "Add a Little style" in my tutorial, in the box Note for Unix users for more details. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From timmichelsen at gmx-topmail.de Thu Jun 26 13:11:21 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 26 Jun 2008 13:11:21 +0200 Subject: [Tutor] Python to exe--how much work? In-Reply-To: <378333.93132.qm@web54301.mail.re2.yahoo.com> References: <378333.93132.qm@web54301.mail.re2.yahoo.com> Message-ID: > I've had some success generati ng .exe files using pyinstaller for a few > simple python programs i've written (less than 100 lines of code, that > just use the os module). How much harder will this be for longer code > with more modules imported? you may also try GUI2exe http://xoomer.alice.it/infinity77/main/GUI2Exe.html which builds on top of py2exe but does assist in setting all options. From kent37 at tds.net Thu Jun 26 14:57:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jun 2008 08:57:57 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080626071843.7078B1E4003@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <20080626071843.7078B1E4003@bag.python.org> Message-ID: <1c2a2c590806260557l58882fedwfd7d199f8444c569@mail.gmail.com> On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores wrote: > I thought I'd use this to compare the 2 ways of string concatenation. Ever > since I began to learn Python I've been told that only one of these is the > proper and efficient one to use, and especially so if the string to be > stitched together is a very long one. String concatenation was optimized in Python 2.4. You might like to try this test in Python 2.3. See the last note here: http://www.python.org/doc/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000 Kent From danny_laya at yahoo.com Thu Jun 26 15:27:05 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Thu, 26 Jun 2008 06:27:05 -0700 (PDT) Subject: [Tutor] For Loop question Message-ID: <133166.21843.qm@web59811.mail.ac4.yahoo.com> Hi I'm learning FOR loop now, very easy too learn. But I get confused to understand this code : myList = [1,2,3,4] for index in range(len(myList)): myList[index] += 1 print myList And the response is: [2, 3, 4, 5] Can you explain me as a newbie, how that code works ?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From muchanek at gmail.com Thu Jun 26 15:37:01 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Thu, 26 Jun 2008 16:37:01 +0300 Subject: [Tutor] Invoking Python In-Reply-To: References: Message-ID: <1214487421.5805.3.camel@www.kinuthia.com> On Thu, 2008-06-26 at 12:00 +0200, tutor-request at python.org wrote: > Or more commonly add a first line like: > > #! /path/to/python/executable > > Then you can simply make the file executable and run it by typing its > name > > $ threeplusfour.py On my computer, running Linux Ubuntu, I always have to type ./threePlusFour.py to get it to run. Otherwise I get a not found command. > > or double clicking it in your favourite file manager GUI tool. > > See the topic "Add a Little style" in my tutorial, in the box > Note for Unix users > for more details. > From bhaaluu at gmail.com Thu Jun 26 15:45:12 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 26 Jun 2008 09:45:12 -0400 Subject: [Tutor] For Loop question In-Reply-To: <133166.21843.qm@web59811.mail.ac4.yahoo.com> References: <133166.21843.qm@web59811.mail.ac4.yahoo.com> Message-ID: On Thu, Jun 26, 2008 at 9:27 AM, Danny Laya wrote: > Hi I'm learning FOR loop now, very easy too learn. But I get confused to > understand this code : > > myList = [1,2,3,4] > for index in range(len(myList)): > myList[index] += 1 > print myList > > And the response is: > [2, 3, 4, 5] > > Can you explain me as a newbie, how that code works ?? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You define a list called myList with 4 integer elements. >>> type(myList[0]) You do a for loop on the four elements. >>> len(myList) 4 Inside the for loop, you increment each element by one (+= 1). += 1 is the same as (variable = variable + 1) So, just 'play computer' and step through the for loop: 1 + 1 = 2 2 + 1 = 3 3 + 1 = 4 4 + 1 = 5 Thus the output is (2, 3, 4, 5). Still four elements, each with one added to it. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From omer at no-log.org Thu Jun 26 15:49:02 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Thu, 26 Jun 2008 15:49:02 +0200 Subject: [Tutor] For Loop question In-Reply-To: <133166.21843.qm@web59811.mail.ac4.yahoo.com> References: <133166.21843.qm@web59811.mail.ac4.yahoo.com> Message-ID: <200806261549.02979.omer@no-log.org> Le Thursday 26 June 2008 15:27:05 Danny Laya, vous avez ?crit?: > Hi I'm learning FOR loop now, very easy too learn. But I get confused to > understand this code : myList = [1,2,3,4] > for index in range(len(myList)): > myList[index] += 1 > print myList > > And the response is: > [2, 3, 4, 5] > > Can you explain me as a newbie, how that code works ?? The 'for in' construct loops over the items of a sequence, and the range function creates a sequence (list) of integers. It is described here: http://docs.python.org/lib/built-in-funcs.html so your code is equivalent to: index = 0 while index < len(myList) : myList[index] += 1 index += 1 -- C?dric Lucantis From omer at no-log.org Thu Jun 26 15:53:17 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 26 Jun 2008 15:53:17 +0200 Subject: [Tutor] Invoking Python In-Reply-To: <1214487421.5805.3.camel@www.kinuthia.com> References: <1214487421.5805.3.camel@www.kinuthia.com> Message-ID: <200806261553.17983.omer@no-log.org> Le Thursday 26 June 2008 15:37:01 kinuthiA muchanE, vous avez ?crit?: > On Thu, 2008-06-26 at 12:00 +0200, tutor-request at python.org wrote: > > Or more commonly add a first line like: > > > > #! /path/to/python/executable > > > > Then you can simply make the file executable and run it by typing its > > name > > > > $ threeplusfour.py > > On my computer, running Linux Ubuntu, I always have to type > ./threePlusFour.py to get it to run. Otherwise I get a not found > command. This is because on unix the current directory (.) is not in the PATH environment variable by default. You can set it if you want but there are some security problems with this so it's not recommended. Typing the leading './' quickly becomes automatic for unix users. -- C?dric Lucantis From bhaaluu at gmail.com Thu Jun 26 15:57:41 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 26 Jun 2008 09:57:41 -0400 Subject: [Tutor] Invoking Python In-Reply-To: <1214487421.5805.3.camel@www.kinuthia.com> References: <1214487421.5805.3.camel@www.kinuthia.com> Message-ID: You can create a Python script on a *nix system and run it with: $ python threeplusfour.py You can place a shebang line as the first line of the script, which points to the python interpreter: #!/usr/bin/python print("Hello, world!\n") Save the file, then make it an executable with: $ chmod u+x threeplusfour.py Then execute it with: $ ./threeplusfour.py Why the dot-slash? Here is a good explanation: http://www.linfo.org/dot_slash.html You can also create a Python script and place it in a directory that is included in your PATH (echo $PATH). Once the executable script is in a directory in your PATH, you can execute it with: $ threeplusfour.py Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! On Thu, Jun 26, 2008 at 9:37 AM, kinuthiA muchanE wrote: > > On Thu, 2008-06-26 at 12:00 +0200, tutor-request at python.org wrote: >> Or more commonly add a first line like: >> >> #! /path/to/python/executable >> >> Then you can simply make the file executable and run it by typing its >> name >> >> $ threeplusfour.py > > On my computer, running Linux Ubuntu, I always have to type > ./threePlusFour.py to get it to run. Otherwise I get a not found > command. >> >> or double clicking it in your favourite file manager GUI tool. >> >> See the topic "Add a Little style" in my tutorial, in the box >> Note for Unix users >> for more details. >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bhaaluu at gmail.com Thu Jun 26 16:05:29 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 26 Jun 2008 10:05:29 -0400 Subject: [Tutor] Invoking Python In-Reply-To: <200806261553.17983.omer@no-log.org> References: <1214487421.5805.3.camel@www.kinuthia.com> <200806261553.17983.omer@no-log.org> Message-ID: On Thu, Jun 26, 2008 at 9:53 AM, C?dric Lucantis wrote: > Le Thursday 26 June 2008 15:37:01 kinuthiA muchanE, vous avez ?crit : >> On Thu, 2008-06-26 at 12:00 +0200, tutor-request at python.org wrote: >> > Or more commonly add a first line like: >> > >> > #! /path/to/python/executable >> > >> > Then you can simply make the file executable and run it by typing its >> > name >> > >> > $ threeplusfour.py >> >> On my computer, running Linux Ubuntu, I always have to type >> ./threePlusFour.py to get it to run. Otherwise I get a not found >> command. > > This is because on unix the current directory (.) is not in the PATH > environment variable by default. You can set it if you want but there are > some security problems with this so it's not recommended. Typing the > leading './' quickly becomes automatic for unix users. > > -- > C?dric Lucantis > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You can make a /home/user/bin directory and add it to your PATH by including this line in your .bash_profile # set PATH so it includes user's private bin if it exists PATH=~/bin:"${PATH}" Place your executable Python scripts in ~/bin Now you can execute them with the dot-slash in front of them because they are in the PATH. BTW, the tilde (~) is equivalent to "/home/user/". Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From georgeolivergo at yahoo.com Thu Jun 26 16:55:25 2008 From: georgeolivergo at yahoo.com (George Oliver) Date: Thu, 26 Jun 2008 07:55:25 -0700 (PDT) Subject: [Tutor] Hands-on beginner's project? Message-ID: <109363.20638.qm@web52007.mail.re2.yahoo.com> > Python Universe Builder (PUB) is an Interactive Fiction module for > Python. It provides a > programming environment similar to that of Inform or TADS but runs > under any Python > interpreter. > > http://py-universe.sourceforge.net/ There also is PAWS (Python adventure writing system): http://home.fuse.net/wolfonenet/PAWS.htm Just for reference, other slightly more complicated examples of separating the game logic and data can be found in the mud genre. I recently wrote up a list of all the Python mud frameworks I could find: http://www.mudconnect.com/discuss/discuss.cgi?mode=MSG&area=coders&message=25320 From lie.1296 at gmail.com Thu Jun 26 17:15:28 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Jun 2008 22:15:28 +0700 Subject: [Tutor] For Loop question Message-ID: <1214493328.6462.11.camel@lieryan-laptop> ?On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores wrote: >? Hi I'm learning FOR loop now, very easy too learn. But I get confused > to understand this code : > > myList = [1,2,3,4] > for index in range(len(myList)): > myList[index] += 1 > print myList > > And the response is: > [2, 3, 4, 5] > > Can you explain me as a newbie, how that code works ?? Ahhh... don't write it like that. It is not a pythonic way to use loop. For-loop in python can loop over sequence (list, tuple, dictionary, iterable, etc) directly (in Visual Basic, like For...Each loop), you very rarely would need to use range/xrange for the iterator, and you should never use len() to pass to range. The loop would be much more simpler, and understandable this way: myList = [1, 2, 3, 4] outList = [] for x in myList: outList.append(x + 1) print outList or in a more elegant way, using list comprehension: myList = [1, 2, 3, 4] print [(x + 1) for x in myList] From srilyk at gmail.com Thu Jun 26 17:22:32 2008 From: srilyk at gmail.com (W W) Date: Thu, 26 Jun 2008 10:22:32 -0500 Subject: [Tutor] closing a internet explorer com object In-Reply-To: <8e087c6d0806241325te6e86ebx4260c908c6d524ce@mail.gmail.com> References: <34379.73766.qm@web43131.mail.sp1.yahoo.com> <8e087c6d0806241325te6e86ebx4260c908c6d524ce@mail.gmail.com> Message-ID: <333efb450806260822u40fdeb02l56f2172b19eefeec@mail.gmail.com> On Tue, Jun 24, 2008 at 3:25 PM, John Chandler wrote: > Below is a bit of code that should work, you might want to change ieregex > because right now it will close anything that has "Microsoft Internet > Explorer" in the title bar. Have fun. The simplest way to do this is use whatever your "title" of the page is. For example, if in your HTML doc you had this: Some Random Doc then you could use this: winhandle = FindWindow(None, "Some Random Doc") and call the close on that winhandle. HTH, Wayne From muchanek at gmail.com Thu Jun 26 17:46:07 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Thu, 26 Jun 2008 18:46:07 +0300 Subject: [Tutor] Invoking Python In-Reply-To: References: <1214487421.5805.3.camel@www.kinuthia.com> Message-ID: <1214495167.5805.7.camel@www.kinuthia.com> On Thu, 2008-06-26 at 09:57 -0400, bhaaluu wrote: > You can create a Python script on a *nix system and run it with: > > $ python threeplusfour.py > > You can place a shebang line as the first line of the script, which points > to the python interpreter: > > #!/usr/bin/python > print("Hello, world!\n") > > Save the file, then make it an executable with: > > $ chmod u+x threeplusfour.py > > Then execute it with: > > $ ./threeplusfour.py > > Why the dot-slash? Here is a good explanation: > http://www.linfo.org/dot_slash.html > > You can also create a Python script and place it in a directory that is > included in your PATH (echo $PATH). Once the executable script is in > a directory in your PATH, you can execute it with: > > $ threeplusfour.py bhaluu, I was not having a problem with any of that, it was Danny Laya! :-) > > Happy Programming! From coreconcern at gmail.com Thu Jun 26 19:05:12 2008 From: coreconcern at gmail.com (Aaron Colichia) Date: Thu, 26 Jun 2008 12:05:12 -0500 Subject: [Tutor] COM & IE problems Message-ID: I've been using win32com.client to work with IE via COM, but recently had a need to start using comtypes.client because it provides a better wrapper for IE. However, when I want to grab an existing IE using comtypes.client.GetActiveObject() the result is always the same as illustrated below H:\devel\workspace\web\src>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import comtypes.client >>> ie = comtypes.client.CreateObject('InternetExplorer.Application') >>> ie.visible = True >>> ie.__clsid '{0002DF01-0000-0000-C000-000000000046}' >>> ie._iid_ GUID("{D30C1661-CDAF-11D0-8A3E-00C04FC9E26E}") >>> newie = comtypes.client.GetActiveObject('InternetExplorer.Application') Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\site-packages\comtypes\client\__init__.py", line 164, in GetActiveObject obj = comtypes.GetActiveObject(clsid, interface=interface) File "C:\Python25\Lib\site-packages\comtypes\__init__.py", line 990, in GetAct iveObject oledll.oleaut32.GetActiveObject(byref(clsid), None, byref(p)) File "\loewis\25\python\Modules\_ctypes\callproc.c", line 757, in GetResult WindowsError: [Error -2147221021] Operation unavailable >>> newie = comtypes.client.GetActiveObject(ie.__clsid) Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\site-packages\comtypes\client\__init__.py", line 164, in GetActiveObject obj = comtypes.GetActiveObject(clsid, interface=interface) File "C:\Python25\Lib\site-packages\comtypes\__init__.py", line 990, in GetAct iveObject oledll.oleaut32.GetActiveObject(byref(clsid), None, byref(p)) File "\loewis\25\python\Modules\_ctypes\callproc.c", line 757, in GetResult WindowsError: [Error -2147221021] Operation unavailable >>> Has anyone got any bright ideas on how to get this working properly? I really appreciate any help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From technorapture at gmail.com Thu Jun 26 22:25:59 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 26 Jun 2008 16:25:59 -0400 Subject: [Tutor] Object attributes surviving deletion Message-ID: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> I've been writing code where we have a class that does some basic ordering and packaging of data we send in its constructor. Let's call it Gen. At a particular point in our code we create an object: genObject = Gen( someInt, someInt, aDict, aList) genObject has a dictionary called dbase, which use later on. Once we are we destroy the object with del genObject At least that's what we want to do. This whole thing is inside a function. However, when we call that function again to create another Gen object, the new object seems to retain the dbase dictionary from the last time, even though we used del and then made a new object. Is there something about Python's object model that we're missing? Thanks for your help, Basu -- The ByteBaker : http://www.bytebaker.com From kent37 at tds.net Thu Jun 26 23:30:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jun 2008 17:30:24 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> Message-ID: <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> On Thu, Jun 26, 2008 at 4:25 PM, Shrutarshi Basu wrote: > At least that's what we want to do. This whole thing is inside a > function. However, when we call that function again to create another > Gen object, the new object seems to retain the dbase dictionary from > the last time, even though we used del and then made a new object. Is > there something about Python's object model that we're missing? > Thanks for your help, It's hard to tell without seeing some code but it sounds like some version of this: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Kent From technorapture at gmail.com Thu Jun 26 23:59:23 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 26 Jun 2008 17:59:23 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> Message-ID: <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> Here's the relevant function: def parse_display(self ): try: gram = Grammars(10, 10, self.pc_map, self.hard_rules) gram.database = {} for key, list in self.grammars.iteritems(): gram.addGram(key, list[0], list[1]) self.modules.append(DisplayModule(self.img_map, (self.xOrigin, self.yOrigin), self.rows, self.columns, gram, self.type)) del gram self.pc_map = {} self.hard_rules =[] self.grammars = {} self.img_map = {} except Exception, inst: print inst As you can see, not only do I delete gram, I also blank out everything that should be cleared. I have to manually clear gram.database because otherwise it keeps the data from previous calls to that function. I don't understand why this should be. DisplayModule is a class that packages and organizes the data into a convenient form. Thanks, -- The ByteBaker : http://www.bytebaker.com From alan.gauld at btinternet.com Fri Jun 27 00:22:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jun 2008 23:22:36 +0100 Subject: [Tutor] COM & IE problems References: Message-ID: "Aaron Colichia" wrote > need to start using comtypes.client because it provides a better > wrapper for No expert but looking at the error message... >>>> ie = comtypes.client.CreateObject('InternetExplorer.Application') >>>> ie.__clsid > '{0002DF01-0000-0000-C000-000000000046}' >>>> newie = >>>> comtypes.client.GetActiveObject('InternetExplorer.Application') > Traceback (most recent call last): > obj = comtypes.GetActiveObject(clsid, interface=interface) Note it says GetActiveObject takes a clsID as the parameter. Yopu are passing a name. try passing ie.__clsid as the first parameter and see if that works? Just a guess, Alan G. From alan.gauld at btinternet.com Fri Jun 27 00:30:58 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jun 2008 23:30:58 +0100 Subject: [Tutor] Object attributes surviving deletion References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com><1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> Message-ID: "Shrutarshi Basu" wrote > def parse_display(self ): > > try: > gram = Grammars(10, 10, self.pc_map, self.hard_rules) > gram.database = {} How is gram.database defined? Is it an instance attribue or a class attribute? If you have class Grammars: database = {} def __init__(....): .... instead of class Grammars: def __init__(....): self.database = {} .... Then database will be shared by all instances of Grammars BTW Its conventional to name classes in the singular unless it genuinely represents a collection of some sort. I can't tell if thats the case here, but it seems more likely that it represents a specific Grammar? > As you can see, not only do I delete gram, I also blank out > everything > that should be cleared. I have to manually clear gram.database > because > otherwise it keeps the data from previous calls to that function. I > don't understand why this should be. DisplayModule is a class that > packages and organizes the data into a convenient form. If its a class variable then deleting the instance will have no affect. About all I can think of without seeing more code. Alan G. From jeff at drinktomi.com Fri Jun 27 00:32:23 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Thu, 26 Jun 2008 15:32:23 -0700 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> Message-ID: <3940166E-3DE0-4532-ACEE-1E9EEDA9C7BC@drinktomi.com> On Jun 26, 2008, at 2:59 PM, Shrutarshi Basu wrote: > self.modules.append(DisplayModule(self.img_map, > (self.xOrigin, self.yOrigin), self.rows, self.columns, gram, > self.type)) ... > As you can see, not only do I delete gram, I also blank out everything > that should be cleared. I have to manually clear gram.database because > otherwise it keeps the data from previous calls to that function. I > don't understand why this should be. DisplayModule is a class that > packages and organizes the data into a convenient form. > Thanks, You've passed gram to DisplayModule, and you've added DisplayModule to a collection. My guess is that display module still holds a reference to gram, and gram won't be collected until DisplayModule clears that reference. As an additional aside python doesn't guarantee that objects will be released as soon as they are unreachable. They can hang around for a while until a garbage collection is triggered. > -jeff From kent37 at tds.net Fri Jun 27 00:57:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jun 2008 18:57:50 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <376fbdcf0806261455jd1e0dd1p292a323d975ec462@mail.gmail.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261455jd1e0dd1p292a323d975ec462@mail.gmail.com> Message-ID: <1c2a2c590806261557h305e8a3u1cdc30d3a7615dc1@mail.gmail.com> On Thu, Jun 26, 2008 at 5:55 PM, Shrutarshi Basu wrote: > Here's the relevant function: Which is the dict that is causing trouble? Kent From kent37 at tds.net Fri Jun 27 00:59:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jun 2008 18:59:37 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> Message-ID: <1c2a2c590806261559o26089ee0od9988075179210da@mail.gmail.com> On Thu, Jun 26, 2008 at 6:30 PM, Alan Gauld wrote: > > "Shrutarshi Basu" wrote > >> def parse_display(self ): >> >> try: >> gram = Grammars(10, 10, self.pc_map, self.hard_rules) >> gram.database = {} > > How is gram.database defined? Is it an instance attribue or > a class attribute? If you have > > class Grammars: > database = {} > def __init__(....): .... > > instead of > > class Grammars: > def __init__(....): > self.database = {} > .... > > Then database will be shared by all instances of Grammars No, the assignment gram.database = {} will always (at least absent any extra magic) create an instance attribute. Kent From technorapture at gmail.com Fri Jun 27 01:13:43 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 26 Jun 2008 19:13:43 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <3940166E-3DE0-4532-ACEE-1E9EEDA9C7BC@drinktomi.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> <3940166E-3DE0-4532-ACEE-1E9EEDA9C7BC@drinktomi.com> Message-ID: <376fbdcf0806261613v33abf8d5wa9879b246cc6faf9@mail.gmail.com> It turns out that Alan's catch of the instance vs class variables was right. database was declared in the class body, rather than in the __init__. Doing gram.database = {}, may have replaced it.. But I've changed the Grammars class to have the proper instance variables. Apparently my teammates and I were still thinking Java-style object models, rather than Pythonic. That's a lesson well learned. @Jeff: We thought of that the first time and so DisplayModule makes deepcopies of them instead of just references. @Alan: Thanks for the point about the naming convention. We're writing our system to be more flexible and object-oriented, so we'll be making a lot of these decisions. We've all realized that we have some rather bad naming conventions. Thanks again to all of you. -- The ByteBaker : http://www.bytebaker.com From john at fouhy.net Fri Jun 27 01:15:37 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 27 Jun 2008 11:15:37 +1200 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <1c2a2c590806261559o26089ee0od9988075179210da@mail.gmail.com> References: <376fbdcf0806261325t54ccdca0u2cd037cb0f99df89@mail.gmail.com> <1c2a2c590806261430g370ea58cx9dd42f8613d4b977@mail.gmail.com> <376fbdcf0806261459y61069028lf3ad12ef5a406a29@mail.gmail.com> <1c2a2c590806261559o26089ee0od9988075179210da@mail.gmail.com> Message-ID: <5e58f2e40806261615n653a706crc74b95722ec4c8f8@mail.gmail.com> On 27/06/2008, Kent Johnson wrote: > No, the assignment > gram.database = {} > will always (at least absent any extra magic) create an instance attribute. I think this is the OP's workaround. Quoting: "Shrutarshi Basu": > I have to manually clear gram.database because > otherwise it keeps the data from previous calls to that function. I think the OP is asking why this step is necessary. -- John. From alan.gauld at btinternet.com Fri Jun 27 01:18:36 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 26 Jun 2008 23:18:36 +0000 (GMT) Subject: [Tutor] Object attributes surviving deletion Message-ID: <970640.16534.qm@web86708.mail.ukl.yahoo.com> > > Then database will be shared by all instances of Grammars > > No, the assignment > gram.database = {} > will always (at least absent any extra magic) create an instance attribute. Ah yes, silly me. The assignment creates a new instance variable. If you were only reading gram.database it would use the shared class variable but as you say, assigning will create a new instance version. Oops! In that case the only thing I can think of is that there is some external reference to the dictionary somewhere and that is being assigned to the instance one each time somehow? Do you have any class or instance managers or Pool objects by any chance? Otherwise I'm stumped. Alan G. From technorapture at gmail.com Fri Jun 27 01:33:02 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 26 Jun 2008 19:33:02 -0400 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <970640.16534.qm@web86708.mail.ukl.yahoo.com> References: <970640.16534.qm@web86708.mail.ukl.yahoo.com> Message-ID: <376fbdcf0806261633u2984c7f7h7fb2635b189c7ac9@mail.gmail.com> Though I solved the problem by making database an instance variable, there's one thing I'm curious about. If I 'overwrite' a class variable with an instance one (as I did originally), is the class variable recoverable? Will objects created later have the class or the instance variable? Basu -- The ByteBaker : http://www.bytebaker.com From wescpy at gmail.com Fri Jun 27 02:29:02 2008 From: wescpy at gmail.com (wesley chun) Date: Thu, 26 Jun 2008 17:29:02 -0700 Subject: [Tutor] Object attributes surviving deletion In-Reply-To: <376fbdcf0806261633u2984c7f7h7fb2635b189c7ac9@mail.gmail.com> References: <970640.16534.qm@web86708.mail.ukl.yahoo.com> <376fbdcf0806261633u2984c7f7h7fb2635b189c7ac9@mail.gmail.com> Message-ID: <78b3a9580806261729o69a02e17k8039b5b8ec824dda@mail.gmail.com> > If I 'overwrite' a class variable > with an instance one (as I did originally), is the class variable > recoverable? Will objects created later have the class or the instance > variable? yes, but you need to access it with the class name: Grammars.database the other (uglier) alternative is to remove the instance attribute from the namespace, and then you are able to get access to it again. in other words, when you created the (dynamic) instance attribute you "shadowed" access to the class attribute. but by doing "del self.database", you've removed that shadow so that self.database is pointing at the class one again: >>> class C(object): ... data = 1 ... >>> >>> c = C() >>> >>> c.data # access class attr 1 >>> c.data += 1 # created new instance attr >>> c.data # look at new instance attr 2 >>> C.data # access class attr 1 >>> del c.data # remove new instance attr >>> c.data # access class attr again 1 granted, that it's "weird" to see code like the last 2 stmts adjacent to each other. hope this helps! -- 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 alan.gauld at btinternet.com Fri Jun 27 07:40:06 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 27 Jun 2008 05:40:06 +0000 (GMT) Subject: [Tutor] Object attributes surviving deletion Message-ID: <30576.22510.qm@web86705.mail.ukl.yahoo.com> > Though I solved the problem by making database an instance variable, > there's one thing I'm curious about. If I 'overwrite' a class variable > with an instance one (as I did originally), is the class variable > recoverable? Yes, you can always access the class version by using the class as the accessor class C: cv = 42 # class variable c = C() c.cv = 666 # create instance cv in c c2 = C() print c.cv # -> 666 print C.cv # -> 42 print c2.cv # -> 42, new instance so no instance variable exists > Will objects created later have the class or the instance > variable? The class one. The instance variable you create is purely in that one instance. You do not alter the class definition so new instamces do not pick it up. HTH, Alan G. From metolone+gmane at gmail.com Fri Jun 27 08:45:34 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 26 Jun 2008 23:45:34 -0700 Subject: [Tutor] For Loop question References: <1214493328.6462.11.camel@lieryan-laptop> Message-ID: "Lie Ryan" wrote in message news:1214493328.6462.11.camel at lieryan-laptop... > On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores wrote: >>? Hi I'm learning FOR loop now, very easy too learn. But I get confused >> to understand this code : >> >> myList = [1,2,3,4] >> for index in range(len(myList)): >> myList[index] += 1 >> print myList >> >> And the response is: >> [2, 3, 4, 5] >> >> Can you explain me as a newbie, how that code works ?? > > > Ahhh... don't write it like that. It is not a pythonic way to use loop. > > For-loop in python can loop over sequence (list, tuple, dictionary, > iterable, etc) directly (in Visual Basic, like For...Each loop), you > very rarely would need to use range/xrange for the iterator, and you > should never use len() to pass to range. > > The loop would be much more simpler, and understandable this way: > > myList = [1, 2, 3, 4] > outList = [] > for x in myList: > outList.append(x + 1) > print outList > > or in a more elegant way, using list comprehension: > > myList = [1, 2, 3, 4] > print [(x + 1) for x in myList] The above solutions create new lists. If a functional requirement is to modify the list in place, then the original is fine (on Python 2.6 and later) or should use xrange instead of range (on Python 2.5 or earlier, especially for large lists). Another option is: myList = [1,2,3,4] for index,value in enumerate(myList): myList[index] = value + 1 -Mark From rdm at rcblue.com Fri Jun 27 12:48:56 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 03:48:56 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806260557l58882fedwfd7d199f8444c569@mail.gmail.co m> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <20080626071843.7078B1E4003@bag.python.org> <1c2a2c590806260557l58882fedwfd7d199f8444c569@mail.gmail.com> Message-ID: <20080627104909.195491E4004@bag.python.org> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 27 13:22:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jun 2008 07:22:22 -0400 Subject: [Tutor] For Loop question In-Reply-To: References: <1214493328.6462.11.camel@lieryan-laptop> Message-ID: <1c2a2c590806270422v2c0da268o82197564917b86c@mail.gmail.com> On Fri, Jun 27, 2008 at 2:45 AM, Mark Tolonen wrote: > The above solutions create new lists. If a functional requirement is to > modify the list in place, then the original is fine (on Python 2.6 and > later) or should use xrange instead of range (on Python 2.5 or earlier, > especially for large lists). range() has not changed it Python 2.6, it still returns a list. 2.6 makes only backwards-compatible changes. The Python 2.6 docs say, "The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range's elements are never used (such as when the loop is usually terminated with break)." Kent From kent37 at tds.net Fri Jun 27 13:28:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jun 2008 07:28:53 -0400 Subject: [Tutor] Astonishing timing result In-Reply-To: <20080627104909.195491E4004@bag.python.org> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <20080626071843.7078B1E4003@bag.python.org> <1c2a2c590806260557l58882fedwfd7d199f8444c569@mail.gmail.com> <20080627104909.195491E4004@bag.python.org> Message-ID: <1c2a2c590806270428q1120fccaw7fa06338c7ac2b8e@mail.gmail.com> On Fri, Jun 27, 2008 at 6:48 AM, Dick Moores wrote: > Instead I've tried to find out if it's true what Alex Martelli writes on p. > 484 in the section, "Building up a string from pieces" in his _Python in a > Nutshell_, 2nd ed., which covers Python 2.4x. You might be interested in this, complete with a picture: http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e55 and this followup: http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e56 Kent From rdm at rcblue.com Fri Jun 27 13:52:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 04:52:35 -0700 Subject: [Tutor] Astonishing timing result In-Reply-To: <1c2a2c590806270428q1120fccaw7fa06338c7ac2b8e@mail.gmail.co m> References: <20080624174429.BF2F11E4009@bag.python.org> <1c2a2c590806241244j32bed1b3s8574c5d4620e2807@mail.gmail.com> <20080624204413.6A4E91E4009@bag.python.org> <20080624160635.4m87dwkmgoooskgg@webware.cc.umanitoba.ca> <20080624212032.7409C1E4010@bag.python.org> <1c2a2c590806241735r12b17420p85281b6a366f91c8@mail.gmail.com> <20080625005231.D03231E4009@bag.python.org> <20080626071843.7078B1E4003@bag.python.org> <1c2a2c590806260557l58882fedwfd7d199f8444c569@mail.gmail.com> <20080627104909.195491E4004@bag.python.org> <1c2a2c590806270428q1120fccaw7fa06338c7ac2b8e@mail.gmail.com> Message-ID: <20080627115248.33FFE1E4003@bag.python.org> At 04:28 AM 6/27/2008, Kent Johnson wrote: >On Fri, Jun 27, 2008 at 6:48 AM, Dick Moores wrote: > > > Instead I've tried to find out if it's true what Alex Martelli writes on p. > > 484 in the section, "Building up a string from pieces" in his _Python in a > > Nutshell_, 2nd ed., which covers Python 2.4x. > >You might be interested in this, complete with a picture: >http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e55 > >and this followup: >http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e56 Good stuff, Kent! Dick From rdm at rcblue.com Sat Jun 28 03:02:33 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 18:02:33 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? Message-ID: <20080628010246.9295E1E4003@bag.python.org> I'm very familiar with appending x to a list, s, using s.append(x), however, I've never understood what the docs mean by s.append(x) same as s[len(s):len(s)] = [x] (See ) Trying it, >>> s = [1,2,3] >>> x = 5 >>> s[len(s):len(s)] = [x] >>> s[len(s):len(s)] [] >>> I'm not enlightened. Just what do the docs mean? Thanks, Dick Moores From drumond.douglas at gmail.com Sat Jun 28 03:27:02 2008 From: drumond.douglas at gmail.com (Douglas Drumond) Date: Fri, 27 Jun 2008 22:27:02 -0300 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <20080628010246.9295E1E4003@bag.python.org> References: <20080628010246.9295E1E4003@bag.python.org> Message-ID: <197391a30806271827s7d5cd3b4lf56534b73dadd106@mail.gmail.com> > > >>> s = [1,2,3] > >>> x = 5 > >>> s[len(s):len(s)] = [x] # (1) > >>> s [1, 2, 3, 5] When you did s[len(s):len(s)] you got the slice begining at len(s) with end at len(s) - 1, ie, nothing. At step (1), len(s) = 3, so you did s[3:3] = [x]. It meant that the slice starting at index 3 (ie, just after s' end) is (now) the list [x]. When you did it again, you got slice s[4:4], which is empty. []'s Douglas -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Sat Jun 28 05:37:02 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 20:37:02 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <197391a30806271827s7d5cd3b4lf56534b73dadd106@mail.gmail.co m> References: <20080628010246.9295E1E4003@bag.python.org> <197391a30806271827s7d5cd3b4lf56534b73dadd106@mail.gmail.com> Message-ID: <20080628033715.38A8F1E4003@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Sat Jun 28 06:39:53 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 21:39:53 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" Message-ID: <20080628044037.B6EFC1E4003@bag.python.org> An HTML attachment was scrubbed... URL: From drumond.douglas at gmail.com Sat Jun 28 07:06:18 2008 From: drumond.douglas at gmail.com (Douglas Drumond) Date: Sat, 28 Jun 2008 02:06:18 -0300 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> Message-ID: <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> In a2() you do l1 += l2, ie, l1 = l1 + l2 But if you don't have l1 defined yet, you can't add to l2 It's like: def a2(): l1 = foo + l2 UnboundLocalError: local variable 'foo' referenced before assignment It's because l1 (and foo at above example) is a local variable. a1's l1 is different from a2's l1. On Sat, Jun 28, 2008 at 01:39, Dick Moores wrote: > I'm puzzled by the below error msg. If I change the line in a2() from > > l1 = [1,2,3]*100 > > to > > l1 = [1,2,3] > > There is no problem. > > Why? And why isn't that line a problem for a1()? > > ========================================= > def a1(): > return l1.extend(l2) > if __name__=='__main__': > l1 = [1,2,3]*100 > l2 = [4,5,6] > from timeit import Timer > t = Timer("a1()", "from __main__ import a1") > t1 = t.timeit(number=10) > > > def a2(): > l1 += l2 > if __name__=='__main__': > l1 = [1,2,3]*100 > l2 = [4,5,6] > from timeit import Timer > t = Timer("a2()", "from __main__ import a2") > t2 = t.timeit(number=10) > > print "t1:", t1 > print "t2:", t2 > print "t2/t1:", t2/t1 > > Error msg: > E:\PythonWork>timing_2_stupidsV2.py > Traceback (most recent call last): > File "E:\PythonWork\timing_2_stupidsV2.py", line 21, in > t2 = t.timeit(number=10) > File "E:\Python25\lib\timeit.py", line 161, in timeit > timing = self.inner(it, self.timer) > File "", line 6, in inner > File "E:\PythonWork\timing_2_stupidsV2.py", line 15, in a2 > l1 += l2 > UnboundLocalError: local variable 'l1' referenced before assignment > =================================================== > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Sat Jun 28 08:53:33 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jun 2008 23:53:33 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.co m> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> Message-ID: <20080628065345.0DD841E4003@bag.python.org> An HTML attachment was scrubbed... URL: From drumond.douglas at gmail.com Sat Jun 28 09:11:40 2008 From: drumond.douglas at gmail.com (Douglas Drumond) Date: Sat, 28 Jun 2008 04:11:40 -0300 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <20080628065345.0DD841E4003@bag.python.org> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> <20080628065345.0DD841E4003@bag.python.org> Message-ID: <197391a30806280011p1f4af0e8k32c0280c2820dd76@mail.gmail.com> > > But if you don't have l1 defined yet, you can't add to l2 > It's like: > def a2(): > l1 = foo + l2 > > UnboundLocalError: local variable 'foo' referenced before assignment > > It's because l1 (and foo at above example) is a local variable. > a1's l1 is different from a2's l1. > > > Sorry to be dense, but how, in what way, is a1's l1 different from a2's > l1"? Both are [1,2,3]*100 . > > Both contain same value, but are in different namespaces (so, different context and different memory areas). If you do a="spam" and b="spam", this doesn't make them same variable, they just have same value. So is in that code. But to make it more confusing, names were the same. Douglas -------------- next part -------------- An HTML attachment was scrubbed... URL: From danny_laya at yahoo.com Sat Jun 28 09:31:36 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Sat, 28 Jun 2008 00:31:36 -0700 (PDT) Subject: [Tutor] addressbook program Message-ID: <79642.8421.qm@web59816.mail.ac4.yahoo.com> Hi I am making an addressBook program now, and you know some problem, the program doesn't work. This is the code : # Loading the addressbook filename = "addbook.dat" def readBook(book) ??? import os ??? if os.path.exists(filename): ??? store = open(filename,'r') ??? for line in store: ??? ??? name = line.rstrip() ??? ??? entry = store.next().rstrip() ??? ??? book[name] = entry ??? store.close() # Saving the address book def saveBook(book): ??? store = open(filename,"w") ??? for name,entry in book.items(): ??? ??? store.write(name + '\n') ??? ??? store.write(entry + '\n') ??? store.close() # Getting User Input def getChoice(menu): ??? print menu ??? choice = int(raw_input("Select a choice(1-4): ")) ??? return choice # Adding an entry def addEntry(book): ??? name = raw_input("Enter a name: ") ??? entry = raw_input("Enter a street, town and phone number: ") ??? book[name] = entry # Removing an entry def removeEntry(book): ??? name = raw_input("Enter a name: ") ??? del(book[name]) #Finding an Entry def findEntry(book): ??? name = raw_input("Enter a name: ") ??? if name in book: ??? ??? print name, book[name] ??? else: print "Sorry, no entry for: ", name # Quitting the program def main(): ??? theMenu = ''' ??? 1) Add Entry ??? 2) Remove Entry ??? 3) Find Entry ??? 4) Quit and save ??? ''' ??? theBook = {} ??? readBook(theBook) ??? choice = getChoice(theMenu) ??? while choice != 4: ??? ??? if choice == 1: ??? ??? ??? addentry(theBook) ??? ??? elif choice == 2: ??? ??? ??? removeEntry(theBook) ??? ??? elif choice == 3: ??? ??? ??? findEntry(theBook) ??? ??? else: print "Invalid choice, try again" ??? ??? choice = getChoice(theMenu) ??? saveBook(theBook) # Call the main function if __name__ == "__main__": ??? main() Help me guy's .... Some enlightenment and explanation about the wrong and how this program works maybe ...... I got this code from Alan Gauld tutorial in Handling Files part. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Sat Jun 28 09:47:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 00:47:57 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" Message-ID: <20080628074810.686691E4003@bag.python.org> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 28 10:05:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jun 2008 09:05:34 +0100 Subject: [Tutor] "local variable 'l1' referenced before assignment" References: <20080628044037.B6EFC1E4003@bag.python.org> Message-ID: "Dick Moores" wrote > I'm puzzled by the below error msg. If I change the line in a2() > from > > l1 = [1,2,3]*100 This is not in a2() this is in the global namespace outside of a2. a2() consists of a single assignment statement. And assignment inside a function creates a local variable which in this case masks the global variable. But the local variable assignment uses the same variable which is not allowed so you get the error message. > Why? And why isn't that line a problem for a1()? In a1 you don't assign so you never create a local variable you use the global variable > ========================================= > def a1(): > return l1.extend(l2) No assignment, it returns the global value > if __name__=='__main__': > l1 = [1,2,3]*100 > t = Timer("a1()", "from __main__ import a1") > def a2(): > l1 += l2 new local variable "created" but erroneously. Change to def a2(): global I1 I1 += I2 return I1 See my tutor topic on namespaces for more on this theme. HTH, -- 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 28 10:12:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jun 2008 09:12:44 +0100 Subject: [Tutor] addressbook program References: <79642.8421.qm@web59816.mail.ac4.yahoo.com> Message-ID: "Danny Laya" wrote > Hi I am making an addressBook program now, > and you know some problem, the program doesn't > work. Always describe the error and, if possible, send the error text. Python error messages may seem cryptic to a beginner but they are actually very informative once you get used to them! But I'll take a guess... def readBook(book) import os if os.path.exists(filename): store = open(filename,'r') The lines under the if statement should be indented. It may just be email messing things up but since the rest were OK I'm guessing that this is the error. Like this: def readBook(book): import os if os.path.exists(filename): store = open(filename,'r') for line in store: name = line.rstrip() entry = store.next().rstrip() book[name] = entry store.close() Remember that indentation(spacing) is all important in Python, its how python knows how much or how little to do as a result of the if test or inside the for loop. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------------------------------------------------------------------------- From kf9150 at gmail.com Sat Jun 28 10:26:04 2008 From: kf9150 at gmail.com (Kelie) Date: Sat, 28 Jun 2008 08:26:04 +0000 (UTC) Subject: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing" in VB? Message-ID: Hello, Suppose var holds a reference to an objeect, my question is in the subject. Thanks! From wescpy at gmail.com Sat Jun 28 10:52:23 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 01:52:23 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <20080628065345.0DD841E4003@bag.python.org> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> <20080628065345.0DD841E4003@bag.python.org> Message-ID: <78b3a9580806280152i29809505ge83936f43b4faa02@mail.gmail.com> > Sorry to be dense, but how, in what way, is a1's l1 different from a2's > l1"? Both are [1,2,3]*100 . dick, alan and everyone else are correct, but let me just put it as simply as this: - in a1(), you're accessing l1 as a global variable - in a2(), you're making l1 a local variable but trying to get its value before you've assigned anything to it. i can see what you're trying to do however... a noble effort: answer the question of whether list contatenation is really slower than using the extend() method. anyway, if you make alan's tweak and slip "global l1" as the 1st line in a2(), it should work better and be a more equivalent comparison. best of 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 rdm at rcblue.com Sat Jun 28 11:03:32 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 02:03:32 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: References: <20080628044037.B6EFC1E4003@bag.python.org> Message-ID: <20080628090430.5F2CE1E4003@bag.python.org> At 01:05 AM 6/28/2008, Alan Gauld wrote: >"Dick Moores" wrote > > >>I'm puzzled by the below error msg. If I change the line in a2() from >> >>l1 = [1,2,3]*100 > >This is not in a2() this is in the global namespace outside of a2. >a2() consists of a single assignment statement. And assignment >inside a function creates a local variable which in this case >masks the global variable. But the local variable assignment >uses the same variable which is not allowed so you get the >error message. > >>Why? And why isn't that line a problem for a1()? > >In a1 you don't assign so you never create a local variable >you use the global variable > > >>========================================= >>def a1(): >> return l1.extend(l2) > >No assignment, it returns the global value > >>if __name__=='__main__': >> l1 = [1,2,3]*100 >> t = Timer("a1()", "from __main__ import a1") > > >>def a2(): >> l1 += l2 > >new local variable "created" but erroneously. Change to > >def a2(): > global I1 > I1 += I2 > return I1 > >See my tutor topic on namespaces for more on this theme. Thanks very much Alan. I think I've got it now, but I will study that section in your tutorial. And my thanks also to Douglas Drumond. >>> import this [snip] Namespaces are one honking great idea -- let's do more of those! >>> Dick From kf9150 at gmail.com Sat Jun 28 11:15:53 2008 From: kf9150 at gmail.com (Kelie) Date: Sat, 28 Jun 2008 09:15:53 +0000 (UTC) Subject: [Tutor] need help with a regular expression Message-ID: Hello, I'm trying to write a regular expression to filter strings that meet the following criteria: 1. Starts with 0-3 underscores; 2. Followed by one letter; 3. Then followed by 0 or more letters or digits or hyphens('-'), 4. Ends with one letter or digit; and 5. There should not be more than one continuous hyphens. This is what I have so far. I think it meets all the criteria except for the last one. Haven't figured out the answer yet. re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') Thank you. From mwalsh at groktech.org Sat Jun 28 11:22:09 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sat, 28 Jun 2008 04:22:09 -0500 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> Message-ID: <486602C1.9020403@groktech.org> Douglas Drumond wrote: > > In a2() you do l1 += l2, ie, l1 = l1 + l2 A subtle clarification is warranted I think. l1 += l2 is not the same as l1 = l1 + l2, when l1 and l2 are lists. l1 += l2 is an augmented assignment statement, and as such will perform the operation in place if possible, IIUC. Consider the following: In [1]: l1 = l2 = [1, 2, 3] In [2]: l1 is l2 Out[2]: True In [3]: l1 += [4, 5, 6] # in-place In [4]: l1 is l2 Out[4]: True In [5]: l1 = l1 + [7, 8, 9] # not In [6]: l1 is l2 Out[6]: False Perhaps there is a better reference, but this behavior is discussed briefly here: http://docs.python.org/ref/augassign.html > But if you don't have l1 defined yet, you can't add to l2 > It's like: > def a2(): > l1 = foo + l2 > > > UnboundLocalError: local variable 'foo' referenced before assignment > > It's because l1 (and foo at above example) is a local variable. > a1's l1 is different from a2's l1. Yes, but as Alan pointed out it's considered local because of the assignment attempt. Obligatory doc reference: http://www.python.org/doc/2.4/ref/naming.html snip = """\ If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations. """ HTH, Marty From alan.gauld at btinternet.com Sat Jun 28 11:28:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jun 2008 10:28:28 +0100 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? References: Message-ID: "Kelie" wrote > Suppose var holds a reference to an objeect, my question is in the > subject. Pretty much so, yes. There may be very subtle differences due to how Python and VB treat variables but the basic intent is the same Alan G From rdm at rcblue.com Sat Jun 28 12:07:20 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 03:07:20 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <486602C1.9020403@groktech.org> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> <486602C1.9020403@groktech.org> Message-ID: <20080628100732.EAB231E4003@bag.python.org> At 02:22 AM 6/28/2008, Martin Walsh wrote: >Douglas Drumond wrote: > > > > In a2() you do l1 += l2, ie, l1 = l1 + l2 > >A subtle clarification is warranted I think. l1 += l2 is not the same as >l1 = l1 + l2, when l1 and l2 are lists. And wow, can the times for each differ from each other! See, for example, Dick From danny_laya at yahoo.com Sat Jun 28 12:30:50 2008 From: danny_laya at yahoo.com (Danny Laya) Date: Sat, 28 Jun 2008 03:30:50 -0700 (PDT) Subject: [Tutor] addressbook program Message-ID: <584244.68484.qm@web59801.mail.ac4.yahoo.com> Hi I am making an addressBook program now, and you know ....... another error message , the program doesn't work. This is the code : # Loading the addressbook filename = "addbook.dat" def readBook(book) ??? import os ??? if os.path.exists(filename): ??? store = open(filename,'r') ??? for line in store: ??? ??? name = line.rstrip() ??? ??? entry = store.next().rstrip() ??? ??? book[name] = entry ??? store.close() # Saving the address book def saveBook(book): ??? store = open(filename,"w") ??? for name,entry in book.items(): ??? ??? store.write(name + '\n') ??? ??? store.write(entry + '\n') ??? store.close() # Getting User Input def getChoice(menu): ??? print menu ??? choice = int(raw_input("Select a choice(1-4): ")) ??? return choice # Adding an entry def addEntry(book): ??? name = raw_input("Enter a name: ") ??? entry = raw_input("Enter a street, town and phone number: ") ??? book[name] = entry # Removing an entry def removeEntry(book): ??? name = raw_input("Enter a name: ") ??? del(book[name]) #Finding an Entry def findEntry(book): ??? name = raw_input("Enter a name: ") ??? if name in book: ??? ??? print name, book[name] ??? else: print "Sorry, no entry for: ", name # Quitting the program def main(): ??? theMenu = ''' ??? 1) Add Entry ??? 2) Remove Entry ??? 3) Find Entry ??? 4) Quit and save ??? ''' ??? theBook = {} ??? readBook(theBook) ??? choice = getChoice(theMenu) ??? while choice != 4: ??? ??? if choice == 1: ??? ??? ??? addentry(theBook) ??? ??? elif choice == 2: ??? ??? ??? removeEntry(theBook) ??? ??? elif choice == 3: ??? ??? ??? findEntry(theBook) ??? ??? else: print "Invalid choice, try again" ??? ??? choice = getChoice(theMenu) ??? saveBook(theBook) # Call the main function if __name__ == "__main__": ??? main() Help me guy's .... Some enlightenment and explanation about the wrong and how this program works? ...... I got this code from Alan Gauld tutorial in Handling Files part. And o...yeah the error message is : ?File "addressbook.py", line 4 ??? def readBook(book) ???????????????????? ^ SyntaxError: invalid syntax -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Sat Jun 28 12:38:43 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 03:38:43 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <78b3a9580806280152i29809505ge83936f43b4faa02@mail.gmail.co m> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> <20080628065345.0DD841E4003@bag.python.org> <78b3a9580806280152i29809505ge83936f43b4faa02@mail.gmail.com> Message-ID: <20080628103857.DCCD51E4003@bag.python.org> At 01:52 AM 6/28/2008, wesley chun wrote: > > Sorry to be dense, but how, in what way, is a1's l1 different from a2's > > l1"? Both are [1,2,3]*100 . > >dick, > >alan and everyone else are correct, but let me just put it as simply as this: > >- in a1(), you're accessing l1 as a global variable >- in a2(), you're making l1 a local variable but trying to get its >value before you've assigned anything to it. > >i can see what you're trying to do however... a noble effort: answer >the question of whether list concatenation is really slower than using >the extend() method. And in fact, list concatenation seems a bit faster. >anyway, if you make alan's tweak and slip "global l1" as the 1st line >in a2(), it should work better and be a more equivalent comparison. It does work. BTW I see that your book has what seems to be a thorough discussion of namespaces and variable scopes in chapter 12. Thanks, Dick From rdmoores at gmail.com Sat Jun 28 13:44:49 2008 From: rdmoores at gmail.com (Dick Moores) Date: Sat, 28 Jun 2008 04:44:49 -0700 Subject: [Tutor] need help with a regular expression In-Reply-To: References: Message-ID: On Sat, Jun 28, 2008 at 2:15 AM, Kelie wrote: > Hello, > > I'm trying to write a regular expression to filter strings that meet the > following criteria: > > 1. Starts with 0-3 underscores; > 2. Followed by one letter; > 3. Then followed by 0 or more letters or digits or hyphens('-'), > 4. Ends with one letter or digit; and > 5. There should not be more than one continuous hyphens. Hi Kelie, I'm not sure of your 5th condition. Do you mean, "A hyphen should not be immediately followed by a hyphen"? Could you give examples of what you will permit, and will not permit? Dick Moores > This is what I have so far. I think it meets all the criteria except for the > last one. Haven't figured out the answer yet. > > re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') From bhaaluu at gmail.com Sat Jun 28 13:53:49 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 28 Jun 2008 07:53:49 -0400 Subject: [Tutor] addressbook program In-Reply-To: <79642.8421.qm@web59816.mail.ac4.yahoo.com> References: <79642.8421.qm@web59816.mail.ac4.yahoo.com> Message-ID: Hello Danny, Part of learning to program a computer is learning how to solve problems. I copy/pasted this code directly from the email, and tried to run it, as is. Error messages in Python are very informative. See below. On Sat, Jun 28, 2008 at 3:31 AM, Danny Laya wrote: > Hi I am making an addressBook program now, and you know some problem, the > program doesn't work. This is the code : > ________________________________ > # Loading the addressbook > filename = "addbook.dat" > > def readBook(book) > import os > if os.path.exists(filename): > store = open(filename,'r') > for line in store: > name = line.rstrip() > entry = store.next().rstrip() > book[name] = entry > store.close() The first error I got was: File "xyz.py", line 4 def readBook(book) ^ SyntaxError: invalid syntax shell returned 1 Press ENTER or type command to continue The error message pointed me to line 4 and the carot (^) pointed to the end of def readBook(book) Can you see the error? You forgot a colon (:) at the end of the def funcName(): Putting a colon there eliminates that error. One down, more to go.... > > # Saving the address book > def saveBook(book): > store = open(filename,"w") > for name,entry in book.items(): > store.write(name + '\n') > store.write(entry + '\n') > store.close() The next error I get is: File "xyz.py", line 7 store = open(filename,'r') ^ IndentationError: expected an indented block shell returned 1 Press ENTER or type command to continue What's the first thing I look at? Which line is the error on? The error message says it's on line 7. The carot points to store. The actual message says it is an indentation error. Fix the indentation. One more error eliminated....... and so on...... Fix them one at a time, until the program works. You must have some patience, put in some work, and maybe, with a little luck, you can learn to program your computer! Don't give up! Keep trying! You certainly know more than you did when you started! What other errors are you getting? > > # Getting User Input > def getChoice(menu): > print menu > choice = int(raw_input("Select a choice(1-4): ")) > return choice > > # Adding an entry > def addEntry(book): > name = raw_input("Enter a name: ") > entry = raw_input("Enter a street, town and phone number: ") > book[name] = entry > > # Removing an entry > def removeEntry(book): > name = raw_input("Enter a name: ") > del(book[name]) > > #Finding an Entry > def findEntry(book): > name = raw_input("Enter a name: ") > if name in book: > print name, book[name] > else: print "Sorry, no entry for: ", name > > # Quitting the program > def main(): > theMenu = ''' > 1) Add Entry > 2) Remove Entry > 3) Find Entry > 4) Quit and save > ''' > theBook = {} > readBook(theBook) > choice = getChoice(theMenu) > while choice != 4: > if choice == 1: > addentry(theBook) > elif choice == 2: > removeEntry(theBook) > elif choice == 3: > findEntry(theBook) > else: print "Invalid choice, try again" > choice = getChoice(theMenu) > saveBook(theBook) > > # Call the main function > if __name__ == "__main__": > main() > ________________________________ > Help me guy's .... Some enlightenment and explanation about the wrong and > how this program works maybe ...... I got this code from Alan Gauld tutorial > in Handling Files part. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From lie.1296 at gmail.com Sat Jun 28 14:21:50 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 28 Jun 2008 19:21:50 +0700 Subject: [Tutor] need help with a regular expression Message-ID: <1214655710.6459.8.camel@lieryan-laptop> Filter it. Use two re, one the one you've made, the other the double hyphen filter: pat2 = re.compile('.*?\-\-.*?') If the string matches this re, then the string is rejected, if it DOES NOT match (i.e. pat2.match('blah') returns None, i.e. if not pat2.match('blah')), then it is accepted. btw: You don't care about small letter? From rdm at rcblue.com Sat Jun 28 14:55:04 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 05:55:04 -0700 Subject: [Tutor] How to print numbers in scientific notation form? Message-ID: <20080628125552.8BBFD1E4003@bag.python.org> %.4g comes close to what I want, but no cigar. In the examples below, the first 2 are not scientific notation form. >>> print "%.4g" % 5.09879870978 5.099 >>> print "%.4g" % .0009874345 0.0009874 >>> print "%.4g" % .000009878 9.878e-006 >>> print "%.4g" % 187686876876238746 1.877e+017 How can I print all numbers in scientific notation form, and designate the number of significant digits? Thanks, Dick Moores From andreengels at gmail.com Sat Jun 28 14:58:38 2008 From: andreengels at gmail.com (Andre Engels) Date: Sat, 28 Jun 2008 14:58:38 +0200 Subject: [Tutor] need help with a regular expression In-Reply-To: References: Message-ID: <6faf39c90806280558h100fd804j9e863c8005d2ceb1@mail.gmail.com> On Sat, Jun 28, 2008 at 11:15 AM, Kelie wrote: > Hello, > > I'm trying to write a regular expression to filter strings that meet the > following criteria: > > 1. Starts with 0-3 underscores; > 2. Followed by one letter; > 3. Then followed by 0 or more letters or digits or hyphens('-'), > 4. Ends with one letter or digit; and > 5. There should not be more than one continuous hyphens. > > This is what I have so far. I think it meets all the criteria except for the > last one. Haven't figured out the answer yet. > > re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') I think _{0,3}[A-Z](\-?[A-Z0-9])+ will do what you are looking for. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From omer at no-log.org Sat Jun 28 15:17:03 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sat, 28 Jun 2008 15:17:03 +0200 Subject: [Tutor] How to print numbers in scientific notation form? In-Reply-To: <20080628125552.8BBFD1E4003@bag.python.org> References: <20080628125552.8BBFD1E4003@bag.python.org> Message-ID: <200806281517.03580.omer@no-log.org> Le Saturday 28 June 2008 14:55:04 Dick Moores, vous avez ?crit?: > %.4g comes close to what I want, but no cigar. In the examples below, > the first 2 are not scientific notation form. > > >>> print "%.4g" % 5.09879870978 > > 5.099 > > >>> print "%.4g" % .0009874345 > > 0.0009874 > > >>> print "%.4g" % .000009878 > > 9.878e-006 > > >>> print "%.4g" % 187686876876238746 > > 1.877e+017 > > How can I print all numbers in scientific notation form, and > designate the number of significant digits? %g automatically choose the more readable form. Use %e for that: >>>> '%e' % 1.0 '1.000000e+00' and to set the number of significant digits (it seems to only set the number of digits after the comma, so you have to subtract 1 from it) : >>> '%.3e' % 1.0 '1.000e+00' -- C?dric Lucantis From lie.1296 at gmail.com Sat Jun 28 15:21:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 28 Jun 2008 20:21:32 +0700 Subject: [Tutor] need help with a regular expression Message-ID: <1214659292.6459.18.camel@lieryan-laptop> >?> Hello, ?>> ?>> I'm trying to write a regular expression to filter strings that meet ?> the ?>> following criteria: ?>> ?>> 1. Starts with 0-3 underscores; ?>> 2. Followed by one letter; ?>> 3. Then followed by 0 or more letters or digits or hyphens('-'), ?>> 4. Ends with one letter or digit; and ?>> 5. There should not be more than one continuous hyphens. ?>> ?>> This is what I have so far. I think it meets all the criteria except ??> for the ?>> last one. Haven't figured out the answer yet. ?>> ?>> re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') ?> ?> I think ?> ?> _{0,3}[A-Z](\-?[A-Z0-9])+ ?> ?> will do what you are looking for. That, doesn't allow single hyphen, which his requirement allowed as long as it (the hypehn) is not as the first or last character. From rdm at rcblue.com Sat Jun 28 15:58:52 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jun 2008 06:58:52 -0700 Subject: [Tutor] How to print numbers in scientific notation form? In-Reply-To: <200806281517.03580.omer@no-log.org> References: <20080628125552.8BBFD1E4003@bag.python.org> <200806281517.03580.omer@no-log.org> Message-ID: <20080628135904.B2B091E4003@bag.python.org> At 06:17 AM 6/28/2008, C?dric Lucantis wrote: > >>>> '%e' % 1.0 >'1.000000e+00' > >and to set the number of significant digits (it seems to only set the number >of digits after the comma, so you have to subtract 1 from it) : > > >>> '%.3e' % 1.0 >'1.000e+00' Perfect! Thanks. Dick From kent37 at tds.net Sat Jun 28 16:34:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 Jun 2008 10:34:28 -0400 Subject: [Tutor] addressbook program In-Reply-To: <584244.68484.qm@web59801.mail.ac4.yahoo.com> References: <584244.68484.qm@web59801.mail.ac4.yahoo.com> Message-ID: <1c2a2c590806280734w3657e88m63ab3ca1dafda47a@mail.gmail.com> On Sat, Jun 28, 2008 at 6:30 AM, Danny Laya wrote: > > Hi I am making an addressBook program now, and you know ....... another > error message , the program doesn't work. This is the code : > ________________________________ > # Loading the addressbook > filename = "addbook.dat" > > def readBook(book) Missing a colon at the end of this line. Kent From alan.gauld at btinternet.com Sat Jun 28 17:04:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jun 2008 16:04:31 +0100 Subject: [Tutor] How to print numbers in scientific notation form? References: <20080628125552.8BBFD1E4003@bag.python.org> Message-ID: "Dick Moores" wrote > >>> print "%.4g" % 5.09879870978 > 5.099 > >>> print "%.4g" % .000009878 > 9.878e-006 > > How can I print all numbers in scientific notation form, and > designate the number of significant digits? use %e instead of %g Alan G From andreengels at gmail.com Sat Jun 28 17:40:14 2008 From: andreengels at gmail.com (Andre Engels) Date: Sat, 28 Jun 2008 17:40:14 +0200 Subject: [Tutor] need help with a regular expression In-Reply-To: <1214659292.6459.18.camel@lieryan-laptop> References: <1214659292.6459.18.camel@lieryan-laptop> Message-ID: <6faf39c90806280840n1ff539bdo17c2c6468f45158e@mail.gmail.com> On Sat, Jun 28, 2008 at 3:21 PM, Lie Ryan wrote: > ?> I think > ?> > ?> _{0,3}[A-Z](\-?[A-Z0-9])+ > ?> > ?> will do what you are looking for. > > That, doesn't allow single hyphen, which his requirement allowed as long > as it (the hypehn) is not as the first or last character. The \-? allows a hyphen, doesn't it? -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From lie.1296 at gmail.com Sat Jun 28 18:09:40 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 28 Jun 2008 23:09:40 +0700 Subject: [Tutor] need help with a regular expression In-Reply-To: <6faf39c90806280839u5b24e5c7rba721cb5a3822729@mail.gmail.com> References: <1214659292.6459.18.camel@lieryan-laptop> <6faf39c90806280839u5b24e5c7rba721cb5a3822729@mail.gmail.com> Message-ID: <1214669380.6459.28.camel@lieryan-laptop> On Sat, 2008-06-28 at 17:39 +0200, Andre Engels wrote: > On Sat, Jun 28, 2008 at 3:21 PM, Lie Ryan wrote: > > > ?> I think > > ?> > > ?> _{0,3}[A-Z](\-?[A-Z0-9])+ > > ?> > > ?> will do what you are looking for. > > > > That, doesn't allow single hyphen, which his requirement allowed as long > > as it (the hypehn) is not as the first or last character. > > The \-? allows a hyphen, doesn't it? > Oh, right... when I tested it, I was using small caps, which is why it doesn't match. But it do have a curious behavior with double dash, when it met double underscore it cuts the matched string: >>> s = '__ABC--DE' >>> pat.match(s).group() '__ABC' I think it's because __ABC do match the required pattern. And match's behavior is to check whether the beginning of the string matches the pattern, it doesn't care if there is extra character after that. From metolone+gmane at gmail.com Sat Jun 28 19:32:17 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 28 Jun 2008 10:32:17 -0700 Subject: [Tutor] need help with a regular expression References: Message-ID: "Kelie" wrote in message news:loom.20080628T091523-776 at post.gmane.org... > Hello, > > I'm trying to write a regular expression to filter strings that meet the > following criteria: > > 1. Starts with 0-3 underscores; > 2. Followed by one letter; > 3. Then followed by 0 or more letters or digits or hyphens('-'), > 4. Ends with one letter or digit; and > 5. There should not be more than one continuous hyphens. > > This is what I have so far. I think it meets all the criteria except for > the > last one. Haven't figured out the answer yet. > > re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') > In rule 4, does the string end with an *additional* letter or digit? The string 'A' would seem to fit the rules, but the example provided would fail. re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*[A-Z0-9]$') # if rule 4 is an additional letter or digit re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*(? Message-ID: <005e01c8d948$7a6289d0$0501a8c0@brucetower> Hi Danny, This is another version of that same sample. You will note that it also has a voice to it. Along with that keyboard commands are from the get input that is the Microsoft input prompt. I modified the raw_input command by by-passing it. I am using the built in Microsoft SAPI 5 engine if you have an XP or Vista machine. If no speech then download it. This will give you something else to play with while learning. Study this, for it uses lists to get the option and hitting enter. And uses a dictionary to make a command from a key hit using the extended keyboard commands. Now in the program you will also see if statements depending on the key you hit and at the moment it is just the options on the list, one letter, then hit enter, choose from the list by using the cursor keys and you can even adjust the voices by using the Ins...PgDn keys. Along with s,f, and m keys. This address book program does add a feature or 2 from the original example, play with it, study it, and do what you want with it. It is attached along with my speech module for probably the email will mess up the indents. Have fun. Bruce #Loading the Address Book using a global file name: import os, time #KEYBOARD COMMANDS! import msvcrt #ALT CURSOR UP, CURSOR LEFT, CURSOR RIGHT, CURSOR DOWN, SOL, EOL, PGUP, AND PGDN MKS0 = {chr(152): "NAVUD", chr(155): "NAVLD", chr(157): "NAVRD", chr(160): "NAVDD", chr(151): "CMAP", chr(163): "CPRB", chr(159): "CMRS", chr(161): "CLRS"} #ALT PAGE KEYS! #CTRL CURSOR UP, CURSOR LEFT, CURSOR RIGHT, CURSOR DOWN, SOL, EOL, PGUP, AND PGDN MKS224 = {chr(141): "NAVU4", chr(115): "NAVL4", chr(116): "NAVR4", chr(145): "NAVD4", "R":"R", "S":"S", "G": "G", "O": "O", "I": "I", "Q": "Q", "u": "u", "v": "CPHA", "w": "CMAP", chr(134): "CGAL", "H": "NAVU", "K": "NAVL", "M": "NAVR", "P": "NAVD"} import Sapi5 tts = Sapi5.Create() tts.Volume = 100 tts.Rate = 1 purge = tts._purge async = tts._async tts.Speak( 'This is the default voice!', async, purge) tts.Speak( 'The number of voices is: %d' % tts.getVoiceCount()) ctrl4V = {"vl":100, "rl":1, "pl":0, "v":"Sam"} #MAKE UP A NEW NAME FOR THE FIRST LOAD ADDRESS BOOK! FILE_NAME = "add_book.txt" OPTIONS = 7 def read_Book (book): if os.path.exists(FILE_NAME): store = open(FILE_NAME,'r') for line in store: name = line.rstrip() entry = store.next().rstrip() book[name] = entry store.close() #Notice the use of rstrip() to remove the new-line character from the end of the line. #Also notice the next() operation to fetch the next line from the file within the loop. #Finally #notice that we defined the filename as a module level variable so we #can use it both in #loading and saving the data. #Saving the Address Book def save_Book (book): store = open(FILE_NAME, 'w') for name,entry in book.items(): store.write(name + '\n') store.write(entry + '\n') store.close() print "%s File Saved and Closed!" % FILE_NAME #Notice we need to add a newline character ('\n') #when we write the data. #Copying the Address Book With New Name! def copy_Book (book): save = 1 file_name2 = text_Input(" Enter Name Of File To Save Address Book:") if file_name2 == "": print "No File Saved!" save = 0 if save == 1: try: store = open(file_name2, 'w') except: print "File Error! No File Saved!" save = 0 if save == 1: for name,entry in book.items(): store.write(name + '\n') store.write(entry + '\n') store.close() print "%s File Saved and Closed!" % file_name2 #Getting User Input def get_Choice( menu, msg=""): e=1 while e==1: e=0 try: choice = key_input(msg) except: choice=0 # choice = choice.lower() if choice not in "123456sfmHKMPqGOIQRSXXX": e=1 print "Bad Entry, %s not an option!" % choice msg = "Select a choice(1-%d, q): " % (len(menu)-1) return choice #DO TEXT INPUT WITH ENTRY ON NEXT LINE! def text_Input(prompt): print prompt return (raw_input(">> ")) #Adding an Entry def add_Entry (book): name = text_Input("Enter a name: ") if name != "": entry = text_Input("Enter Street, City/Town and Phone Number: ") if name != "" and entry != "": book[ name.capitalize()] = entry else: print "No entry saved!" #EDIT ENTRY! def edit_Entry (book): name = text_Input("Enter a name: ") if name in book: print "%s > %s" % (name, book[name]) entry = text_Input("Enter Street, City/Town and Phone Number: ") else: name = "" if name != "" and entry != "": book[name] = entry else: print "No edit!" #Removing an entry def remove_Entry (book, del_Book): name = text_Input("Enter a name: ") if name in book: print "%s Deleted!" % name del_Book[name] = book[name] del(book[name]) else: print "Sorry, no entry for: ", name #RESTORING A DELETED ENTRY! def restore_Entry (book, del_book): if len( del_book) == 0: print "Nothing To Restore!" else: for name,entry in del_book.items(): pass print "%s At: %s" % (name, entry) book[name] = entry del(del_book[name]) #Finding an entry def find_Entry (book): name = text_Input("Enter A Name: ") if name.capitalize() in book: print "%s > %s" % (name, book[name]) else: print "Sorry, no entry for: ", name.capitalize() def key_input( msg): "ENTER A KEY OR FUNCTION KEY, (ALT, CTRL, SHIFT...KEY)" # clear the keyboard buffer ch=""; ch1=""; sch="" while msvcrt.kbhit(): ch = msvcrt.getch() # PlaySound ("Federation_Scan.ogg", 2, -1) #PLAY ANY SOUND HERE! # print "| " # print "Hit Return Or Escape To Quit or Move Using Cursor Keys:" if msg != "": print msg, while ch != chr(27) and ch != chr(13) and ch1 != chr(0) and ch1 != chr(224): ch1 = msvcrt.getch() ch = ch1 if ch1 == chr(0) or ch1 == chr(224): ch = msvcrt.getch() sch = ch print if ch not in MKS0 and ch not in MKS224: print "ch=%d ch1=%d" % (ord(ch), ord(ch1)) else: # ch = ch.upper() ch = ch.lower() # if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": if ch in "abcdefghijklmnopqrstuvwxyz": msvcrt.putch(ch) sch=ch elif ch == chr(8) and len(sch)>0: msvcrt.putch(ch) sch = sch[:len(sch)-1] if ch == chr(27): i=len(sch) while i>0: i-=1 msvcrt.putch(chr(8)) sch="XXX" print sch print return (sch) def voiceControl( ctrl): "CONTROLS FOR VOICES!" if ctrl == "I": ctrl4V[ "vl"] += 5 if ctrl4V[ "vl"] > 100: ctrl4V[ "vl"] = 100 tts.setVolume( ctrl4V[ "vl"]) tts.Speak('Volume Maximum!', async, purge) else: tts.setVolume( ctrl4V[ "vl"]) tts.Speak('Volume Up!', async, purge) elif ctrl == "Q": ctrl4V[ "vl"] -= 5 if ctrl4V[ "vl"] <= 0: ctrl4V[ "vl"] = 0 tts.setVolume( 100) tts.Speak('Volume Minimum!', async, purge) time.sleep(.2) tts.setVolume( ctrl4V[ "vl"]) else: tts.setVolume( ctrl4V[ "vl"]) tts.Speak('Volume Down!', async, purge) elif ctrl == "G": ctrl4V[ "rl"] += 1 tts.setRate( ctrl4V[ "rl"]) tts.Speak('Rate Up!', async, purge) elif ctrl == "O": ctrl4V[ "rl"] -= 1 tts.setRate( ctrl4V[ "rl"]) tts.Speak('Rate down!', async, purge) #PITCH FUNCTION DOES NOT EXIST FOR THE MICROSOFT ENGINE NOR IN PYTTS BUT IN MINE AS AN XML COMMAND! elif ctrl == "R": ctrl4V[ "pl"] += 1 tts.setPitch( ctrl4V[ "pl"]) tts.Speak('Pitch Up!', async, purge) elif ctrl == "S": ctrl4V[ "pl"] -= 1 tts.setPitch( ctrl4V[ "pl"]) tts.Speak('Pitch down!', async, purge) elif ctrl == "f": tts.setVoiceByName('Mary') ctrl4V[ "v"] = 'Mary' tts.Speak('Mary!', async, purge) elif ctrl == "m": tts.setVoiceByName('Mike') ctrl4V[ "v"] = 'Mike' tts.Speak('Mike!', async, purge) elif ctrl == "s": tts.setVoiceByName('Sam') ctrl4V[ "v"] = 'Sam' tts.Speak('Sam!', async, purge) #MAKE ALL EDIT SELECTIONS A VERBALIZED LIST! def menuOptions(spk, limit=OPTIONS): "ENTER CHOICE FOR LEVEL NUMBER!" tts.Speak(" %s 1" % spk) choice=1 msg=str(choice) while True: event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() break elif event.type == pygame.KEYDOWN: key = event.key # keymod = event.mod if key==K_ESCAPE: sys.exit() break if key == K_UP: if choice>1: choice-=1 msg=str(choice) tts.Speak(" %s? " % msg, async, purge) elif key == K_DOWN: if choice=len( the_Menu): mc=len( the_Menu)-1 tts.Speak( the_Menu[mc], async, purge) print the_Menu[mc] elif choice not in "q XXX": print "Invalid choice, try again" if choice == "q": save_Book (the_Book) e = raw_input(" Hit Enter Key To Quit! ") else: tts.Speak( "Escaping!") print "Escaping!" #Now the only thing left to do is call the main() function when the program is run, #and to do that we use a bit of Python magic like this: if __name__ == "__main__": main() #This mysterious bit of code allows us to use any python file as a module by #importing it, or as a program by running it. The difference #is that when the program is imported, #the internal variable __name__ is set to the module name but # when the file is run, the value of __name__ is set to "__main__". #Sneaky, eh? #Now if you type all that code into a new text file #and save it as addressbook.py, #you should be able to run it from an OS prompt by typing: #c:\python25\ python25 address.py #If Your Path Has Been Set Just Type: #Address #NOTE: #python25 is assumed to be loaded onto your machine. #If you have told your computer to run .py using python25 path, then just click on the Address.py file from explorer -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Address.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Sapi5.py URL: From wescpy at gmail.com Sat Jun 28 21:57:08 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 12:57:08 -0700 Subject: [Tutor] "local variable 'l1' referenced before assignment" In-Reply-To: <20080628103857.DCCD51E4003@bag.python.org> References: <20080628044037.B6EFC1E4003@bag.python.org> <197391a30806272204j52d00951w1ab2057aa13900ea@mail.gmail.com> <197391a30806272206v27d97c62p42c3cb2890f6867b@mail.gmail.com> <20080628065345.0DD841E4003@bag.python.org> <78b3a9580806280152i29809505ge83936f43b4faa02@mail.gmail.com> <20080628103857.DCCD51E4003@bag.python.org> Message-ID: <78b3a9580806281257r2db6d6a7sb7cbf987460b2801@mail.gmail.com> > BTW I see that your book has what seems to be a thorough discussion of > namespaces and variable scopes in chapter 12. ah, that section (12.3) you're referring to is mostly about namespaces as it's in the Modules chapter. the real bit about variable scope that you're seeking is actually in the immediately preceding chapter on Functions in section 11.8, which does address some of the topics covered in this thread. the reason why scope is mentioned in that ch12 section is because i introduce namespaces there, and it's easy for those new to the language to get confused about the relationship b/w namespaces and variable scope. for example, and this is not recommended, of course, create a global variable named 'str', then create another one in a function, like this: str = 'foo' def func(): str = 'bar' so now the name 'str' lives in *3* different namespaces, local (to func), global, and built-in. *but* from any point in your code, you only have (legal) access to one of them -- that's scope. (side note: i think 'str' and 'list' are the 2 most popular variables that shadow/override built-in names.) one thing that i did learn from all you tutors is the behavior for augmented asst differing from that of the full asst syntax... i'll jot down to make sure it's covered in the next edition. :-) cheers, -- 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 wescpy at gmail.com Sat Jun 28 22:21:25 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 13:21:25 -0700 Subject: [Tutor] Using Python in Windows In-Reply-To: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> References: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> Message-ID: <78b3a9580806281321k34e31ab6w490571108182f76d@mail.gmail.com> > IDLE 1.2.2 > >>> from gasp import * > > Traceback (most recent call last): > File "", line 1, in > from gasp import * > ImportError: No module named gasp as brian mentioned, gasp doesn't come with Python. in fact, this very thread came up just last month, and here was one of my replies, but you can also check out the entire thread if you wish: http://mail.python.org/pipermail/tutor/2008-May/061975.html -- 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 alan.gauld at btinternet.com Sat Jun 28 23:28:33 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jun 2008 22:28:33 +0100 Subject: [Tutor] addressbook program References: <79642.8421.qm@web59816.mail.ac4.yahoo.com> <005e01c8d948$7a6289d0$0501a8c0@brucetower> Message-ID: "FT" wrote > #Copying the Address Book With New Name! > def copy_Book (book): > save = 1 > file_name2 = text_Input(" Enter Name Of File To Save Address > Book:") > if file_name2 == "": > print "No File Saved!" > save = 0 > if save == 1: > try: > store = open(file_name2, 'w') > except: > print "File Error! No File Saved!" > save = 0 > if save == 1: > for name,entry in book.items(): > store.write(name + '\n') > store.write(entry + '\n') > store.close() > print "%s File Saved and Closed!" % file_name2 This is unnecessarily complex. By rearranging the logic slightly we can write it as: def copy_Book (book): file_name2 = text_Input(" Enter Name Of File To Save Address Book:") if file_name2: try: store = open(file_name2, 'w') for name,entry in book.items(): store.write(name + '\n') store.write(entry + '\n') store.close() print "%s File Saved and Closed!" % file_name2 except: print "File Error! No File Saved!" return However, I'd prefer to pass the filename in as an argument since mixing processing and user interaction is usually a bad idea. Also in the tutorial I don't use try/except because I haven't covered them yet! > #Getting User Input > def get_Choice( menu, msg=""): > e=1 > while e==1: > e=0 > try: > choice = key_input(msg) > except: > choice=0 Again the use of the e flag is making the structure more complex than is necessary. In Python you can usually avoid the use of such flags by reworking the logic - often by reversing a boolean test as I did above. > #DO TEXT INPUT WITH ENTRY ON NEXT LINE! > def text_Input(prompt): > print prompt > return (raw_input(">> ")) Just use: raw_input(prompt + "\n>> " ) > def add_Entry (book): > name = text_Input("Enter a name: ") > if name != "": > entry = text_Input("Enter Street, City/Town and Phone > Number: ") > if name != "" and entry != "": > book[ name.capitalize()] = entry > else: > print "No entry saved!" Could be simplified to: def add_Entry (book): name = text_Input("Enter a name: ") entry = text_Input("Enter Street, City/Town and Phone Number: ") if name and entry: book[ name.capitalize()] = entry else: print "No entry saved!" > def key_input( msg): > "ENTER A KEY OR FUNCTION KEY, (ALT, CTRL, SHIFT...KEY)" > # clear the keyboard buffer > ch=""; ch1=""; sch="" > while msvcrt.kbhit(): > ch = msvcrt.getch() Given the OP was a novice I suspect this might be a tad advanced at this stage :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ben at pacificu.edu Sun Jun 29 02:02:12 2008 From: ben at pacificu.edu (Ben) Date: Sat, 28 Jun 2008 17:02:12 -0700 Subject: [Tutor] Using Python in Windows In-Reply-To: <78b3a9580806281321k34e31ab6w490571108182f76d@mail.gmail.com> References: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> <78b3a9580806281321k34e31ab6w490571108182f76d@mail.gmail.com> Message-ID: <85bc5e0a0806281702t13bb40f8i5511663dd67fdb6d@mail.gmail.com> Hmm. The instruction on adding something gaspthe library seems to be catered towards Linux. I've done a Google search and glanced at the Tutorial, the Windows FAQ ( http://www.python.org/doc/faq/windows/), ect. I don't see it in the global module index . Installing Python modules goes a little over my head... On Sat, Jun 28, 2008 at 1:21 PM, wesley chun wrote: >> IDLE 1.2.2 >> >>> from gasp import * >> >> Traceback (most recent call last): >> File "", line 1, in >> from gasp import * >> ImportError: No module named gasp > > > as brian mentioned, gasp doesn't come with Python. in fact, this very > thread came up just last month, and here was one of my replies, but > you can also check out the entire thread if you wish: > > http://mail.python.org/pipermail/tutor/2008-May/061975.html > > -- 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Sun Jun 29 02:11:03 2008 From: david at abbottdavid.com (David) Date: Sat, 28 Jun 2008 20:11:03 -0400 Subject: [Tutor] Create file and input text Message-ID: <4866D317.8000606@abbottdavid.com> Hi, I am very new to python and it is my first attempt at programing except for some basic bash scripts. I came up with this; #!/usr/bin/python import os filename = raw_input('Enter the filename: ') fobj = open(filename, 'w') yourname = raw_input('What is your name: ') fobj.write(yourname) fobj.close() It seems to work Ok, I was shocked! Is it OK? -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From chester_lab at fltg.net Sun Jun 29 02:49:18 2008 From: chester_lab at fltg.net (FT) Date: Sat, 28 Jun 2008 20:49:18 -0400 Subject: [Tutor] addressbook program References: <79642.8421.qm@web59816.mail.ac4.yahoo.com><005e01c8d948$7a6289d0$0501a8c0@brucetower> Message-ID: <000b01c8d982$0125a7c0$0501a8c0@brucetower> Hi Alan, You said: > #DO TEXT INPUT WITH ENTRY ON NEXT LINE! > def text_Input(prompt): > print prompt > return (raw_input(">> ")) Just use: raw_input(prompt + "\n>> " ) Yes, that is OK if you are sighted, for the screen reader program does not say the message in the prompt unless there is some kind of a change in the screen. I have to place it there for only a sightless programmer. Maybe once in a while it would say it, but that is if the key stroke is fast and the kill speech is quick. Like the purge command inside the example, when that is set for all key strokes in a screen reader, it can erase any saying of text displayed fast onto the screen, just a timing issue between keyboard and screen reader capture. So, my example is just accommodating that. The other examples are true, I sent it without making the needed changes. Probably too many try statements only because I wrote an input for my Trek program that entered values of a given type and kind of left it there if the wrong type is entered. Which brings up the other dictionary list of keys. Just left it there when sending the example to fast. Just like the last method which uses pygame, but it is never called and would fail since I did not import pygame. So, sending an outdated example is not good, but does lead to showing the correct sample in a tutorial when you point out errors or sloppy work. Thanks, Bruce From kf9150 at gmail.com Sun Jun 29 03:45:24 2008 From: kf9150 at gmail.com (Kelie) Date: Sun, 29 Jun 2008 01:45:24 +0000 (UTC) Subject: [Tutor] need help with a regular expression References: Message-ID: Dick Moores gmail.com> writes: > I'm not sure of your 5th condition. Do you mean, "A hyphen should not > be immediately followed by a hyphen"? Could you give examples of what > you will permit, and will not permit? Dick, your are correct. A hyphen should not be immediately followed by a hyphen. Actually I forgot another criteria that all letters should be uppercase. Here is the revised criteria: 1. Starts with 0-3 underscores; 2. Followed by one letter; 3. Then followed by 0 or more letters or digits or hyphens('-'), 4. There should not be more than one continuous hyphens; 5. The last character should be letter or digit; and 6. All letters should be uppercase. These are some examples: G-ANNO-SYMB is good; -G-ANNO-SYMB is bad; _G-ANNO-SYMB is good; _TEMP is good; ____TEMP is bad; (4 leading underscores); c-n-cen is bad; C-N-CEN is good; C-N-BLDG1 is good; C_N-BLDG1 is bad; C N BLDG is bad; 1 is bad; _1-TEXT is bad; _TEXT-1 is good. Thanks. From kf9150 at gmail.com Sun Jun 29 03:50:57 2008 From: kf9150 at gmail.com (Kelie) Date: Sun, 29 Jun 2008 01:50:57 +0000 (UTC) Subject: [Tutor] need help with a regular expression References: Message-ID: Mark Tolonen gmail.com> writes: > re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*[A-Z0-9]$') # if rule 4 is an > additional letter or digit > re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*(? single-letter strings are allowed > Mark, single-letter strings are allowed and your regular expression works as expected. Thank you! From deliberatus at verizon.net Sun Jun 29 03:53:44 2008 From: deliberatus at verizon.net (Kirk Z Bailey) Date: Sat, 28 Jun 2008 21:53:44 -0400 Subject: [Tutor] arrays in python Message-ID: <4866EB28.405@verizon.net> Just wondering, if I can find a way to do a 2 dimensional array in python. 1 dimension would be a list it would seem; for 2, I could use a list of lists? Strange how I can't think of ever needing one since I discovered snake charming, but so many languages do foo dimensional arrays, it would seem like there ought to be a way to do it in python. -- end Very Truly yours, - Kirk Bailey, Largo Florida kniht +-----+ | BOX | +-----+ think From michael.miesner at gmail.com Sun Jun 29 03:54:42 2008 From: michael.miesner at gmail.com (Michael Miesner) Date: Sat, 28 Jun 2008 20:54:42 -0500 Subject: [Tutor] need help; save web data Message-ID: <8f6846bb0806281854x59377081h86ccdc9cd959bd4@mail.gmail.com> Hi all- I am trying to save the output of a web search to a local file, using python. Im really new to this, but I want to be able to write a program that uses google scholar, but takes search results and saves them to a local file. I am perfectly fine with playing around wtih this until I get it, but I dont know how to begin to get python to grab the output of a given search on google scholar and save it to a file. Thanks for all your help. Michael -- Michael Miesner PHDC in Clinical Psychology East Tennessee State University -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sun Jun 29 04:49:35 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 19:49:35 -0700 Subject: [Tutor] Using Python in Windows In-Reply-To: <85bc5e0a0806281702t13bb40f8i5511663dd67fdb6d@mail.gmail.com> References: <85bc5e0a0806241827q74fbcb7cv8394bb34c1539664@mail.gmail.com> <78b3a9580806281321k34e31ab6w490571108182f76d@mail.gmail.com> <85bc5e0a0806281702t13bb40f8i5511663dd67fdb6d@mail.gmail.com> Message-ID: <78b3a9580806281949v17c233a7v479df137bcc0fb7@mail.gmail.com> > Hmm. The instruction on adding something gasp the library seems to be > catered towards Linux. hmmm, you are correct, and apparently, this is a popular question to the maintainers (note these links are circular): https://answers.launchpad.net/gasp-code/+question/36144 https://answers.launchpad.net/gasp-code/+question/17174 https://answers.launchpad.net/gasp-code/+faq/28 however, i *did* find out that GASP is in the cheeseshop: http://pypi.python.org/pypi/gasp/0.4.5 sooo, what does this mean? it means if you install EasyInstall... http://peak.telecommunity.com/DevCenter/EasyInstall http://peak.telecommunity.com/DevCenter/EasyInstall#windows-notes (NOTE!) ..., then installing GASP would be as easy as opening up a Command/DOS window and issuing: C:\> easy_install gasp you'll see some output like: Searching for gasp Reading http://pypi.python.org/simple/gasp/ Reading http://dc.ubuntu-us.org/bazaar/gasp Best match: gasp 0.4.5 Downloading http://pypi.python.org/packages/2.5/g/gasp/gasp-0.4.5-py2.5.egg Processing gasp-0.4.5-py2.5.egg creating c:\python25\lib\site-packages\gasp-0.4.5-py2.5.egg Extracting gasp-0.4.5-py2.5.egg to c:\python25\lib\site-packages : you'll find that EasyInstall is a great tool to have because you can continue to use it to install other Python related software moving forward, all in a similarly "easy" manner. good luck! -wesley From wescpy at gmail.com Sun Jun 29 04:56:35 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 19:56:35 -0700 Subject: [Tutor] Create file and input text In-Reply-To: <78b3a9580806281956gbf60bf3k17652c6dd7362079@mail.gmail.com> References: <4866D317.8000606@abbottdavid.com> <78b3a9580806281956gbf60bf3k17652c6dd7362079@mail.gmail.com> Message-ID: <78b3a9580806281956j5efce22tfb340501b8f8e82c@mail.gmail.com> > Hi, I am very new to python and [...] came up with this; > #!/usr/bin/python > > import os > filename = raw_input('Enter the filename: ') > fobj = open(filename, 'w') > yourname = raw_input('What is your name: ') > fobj.write(yourname) > fobj.close() > > It seems to work Ok, I was shocked! Is it OK? david, welcome to Python! ummmm, yes, it is ok. your syntax is perfect, and it should've done exactly what you wanted. and yes, Python is *that* intuitive and that easy. you're gonna *love* programming with it. :-) one suggestion i *do* have is that your code only writes a single line of text to the file. if you intend on creating a text file with multiple lines, be sure to add a NEWLINE (\n) at the end of each string, otherwise you'll be writing everything all to one single, really long line. another idea is that you may wish to write some code that does the opposite: open a text file for read, display its contents, close the file, just as a test to ensure that your original app works as advertised. cheers! -- 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 dyoo at cs.wpi.edu Sun Jun 29 05:18:33 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Sat, 28 Jun 2008 23:18:33 -0400 Subject: [Tutor] Create file and input text In-Reply-To: <78b3a9580806281956j5efce22tfb340501b8f8e82c@mail.gmail.com> References: <4866D317.8000606@abbottdavid.com> <78b3a9580806281956gbf60bf3k17652c6dd7362079@mail.gmail.com> <78b3a9580806281956j5efce22tfb340501b8f8e82c@mail.gmail.com> Message-ID: >> #!/usr/bin/python > > > > import os > > filename = raw_input('Enter the filename: ') > > fobj = open(filename, 'w') > > yourname = raw_input('What is your name: ') > > fobj.write(yourname) > > fobj.close() > > > > It seems to work Ok, I was shocked! Is it OK? Hi David, The first line, the import of the 'os' module, is superfluous: it's not being used. > welcome to Python! ummmm, yes, it is ok. your syntax is perfect, and > it should've done exactly what you wanted. and yes, Python is *that* > intuitive and that easy. you're gonna *love* programming with it. :-) Python won't let you break any laws of gravity. But there are a lot of good people here on Tutor who will be happy to be of assistance when the programs get harder to write. From wescpy at gmail.com Sun Jun 29 05:39:09 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Jun 2008 20:39:09 -0700 Subject: [Tutor] Create file and input text In-Reply-To: References: <4866D317.8000606@abbottdavid.com> <78b3a9580806281956gbf60bf3k17652c6dd7362079@mail.gmail.com> <78b3a9580806281956j5efce22tfb340501b8f8e82c@mail.gmail.com> Message-ID: <78b3a9580806282039m7edb57b4u2e9f2b5fa540f4bb@mail.gmail.com> > The first line, the import of the 'os' module, is superfluous: it's > not being used. oops, good catch danny... i didn't even see that. > Python won't let you break any laws of gravity. But there are a lot > of good people here on Tutor who will be happy to be of assistance > when the programs get harder to write. well, like with all functionality, you just have to import the right module: http://xkcd.com/353/ :-) -wesley From metolone+gmane at gmail.com Sun Jun 29 07:01:53 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 28 Jun 2008 22:01:53 -0700 Subject: [Tutor] arrays in python References: <4866EB28.405@verizon.net> Message-ID: "Kirk Z Bailey" wrote in message news:4866EB28.405 at verizon.net... > Just wondering, if I can find a way to do a 2 dimensional array in python. > 1 dimension would be a list it would seem; for 2, I could use a list of > lists? > > Strange how I can't think of ever needing one since I discovered snake > charming, but so many languages do foo dimensional arrays, it would seem > like there ought to be a way to do it in python. Yes, use lists of lists, but be careful constructing them: >>> L=[[0]*5]*5 >>> L [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> L[0][0]=1 >>> L [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] Oops, five references to the same list. Changing one changes all. >>> L=[[0]*5 for _ in range(5)] >>> L [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> L[0][0]=1 >>> L [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Use a list comprehension to construct five different lists. --Mark From kf9150 at gmail.com Sun Jun 29 09:23:22 2008 From: kf9150 at gmail.com (Kelie) Date: Sun, 29 Jun 2008 07:23:22 +0000 (UTC) Subject: [Tutor] =?utf-8?q?Is_=22var_=3D_None=22_in_Python_equivalent_to_?= =?utf-8?q?=22Set_var_=3D=09Nothing=22in_VB=3F?= References: Message-ID: Thanks Alan. From wescpy at gmail.com Sun Jun 29 10:20:16 2008 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Jun 2008 01:20:16 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? In-Reply-To: References: Message-ID: <78b3a9580806290120s60db94eby5f09229cac9e7f55@mail.gmail.com> > > Suppose var holds a reference to an objeect, my question is in the subject. > > Pretty much so, yes. > There may be very subtle differences due to how Python and VB > treat variables but the basic intent is the same one question i'd like to ask is, in what context is such a line part of your code? altho alan is correct in that syntactically, they're very similar, i'm wondering what you're using it for. the reason why i ask is because it's not standard practice i see people doing this with Python, so i'm trying to get a better understanding of what you're trying to do. thanks! -- 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 david at abbottdavid.com Sun Jun 29 10:26:00 2008 From: david at abbottdavid.com (David) Date: Sun, 29 Jun 2008 04:26:00 -0400 Subject: [Tutor] Create file and input text In-Reply-To: <78b3a9580806282039m7edb57b4u2e9f2b5fa540f4bb@mail.gmail.com> References: <4866D317.8000606@abbottdavid.com> <78b3a9580806281956gbf60bf3k17652c6dd7362079@mail.gmail.com> <78b3a9580806281956j5efce22tfb340501b8f8e82c@mail.gmail.com> <78b3a9580806282039m7edb57b4u2e9f2b5fa540f4bb@mail.gmail.com> Message-ID: <48674718.7000409@abbottdavid.com> wesley chun wrote: >> The first line, the import of the 'os' module, is superfluous: it's >> not being used. >> > > oops, good catch danny... i didn't even see that. > > > >> Python won't let you break any laws of gravity. But there are a lot >> of good people here on Tutor who will be happy to be of assistance >> when the programs get harder to write. >> > > well, like with all functionality, you just have to import the right module: > http://xkcd.com/353/ > > :-) > -wesley > > > Thanks for the warm welcome, this is fun, I am sure I will be back. :) david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From alan.gauld at btinternet.com Sun Jun 29 15:41:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Jun 2008 14:41:08 +0100 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var =Nothing"in VB? References: <78b3a9580806290120s60db94eby5f09229cac9e7f55@mail.gmail.com> Message-ID: "wesley chun" wrote > one question i'd like to ask is, in what context is such a line part > of your code? altho alan is correct in that syntactically, they're > very similar, i'm wondering what you're using it for. That's a very good point. The normal way to delete a reference to an object in Python would be to use del(objVar). Assigning to None tends only to be needed is if you are reusing the same variable to point to multiple (or optional) objects and don't want to recreate the variable each time. That is, as Wesley says, rather uncommon. The other use for v=None is in default parameter definitions, but in that case its usually quite different to the VB example! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sbjaved at gmail.com Sun Jun 29 17:13:34 2008 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 29 Jun 2008 21:13:34 +0600 Subject: [Tutor] Deleting specified files using a python program...help with code? Message-ID: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> I transfer files a lot between my windows and linux partitions...these folders sometimes contain *.db and *.ini files which are not recognized or used by linux. So i tried to write a program to crawl through my home dir and remove these files...I'm *very* new to programming and python so please be gentle. Here is the code: *import os list = ['*.ini', '*.db'] for root, dirs, files in os.walk('/home/saad'): **for list in files: **os.remove(os.path.join('root', 'list')) print 'done'* Unfortunately its a bit too efficient and nearly wiped my home dir before i manually killed it. Again...treat me like a super noob. Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 29 17:51:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Jun 2008 16:51:16 +0100 Subject: [Tutor] Deleting specified files using a python program...help withcode? References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: "Saad Javed" wrote > *import os Not sure what the asterisk at the front is for? The import should be aligned with the left margin. > list = ['*.ini', '*.db'] Its a bad idea to call things list since you hide the builtin list function for converting things to lists... > for root, dirs, files in os.walk('/home/saad'): > **for list in files: Assuming the asterisks indicate spaces the use of list here hides your list above. I suspect what you meant was something like for file in files: if file in list: os.remove(file) Except that won't work with wildcards. So you might need to do: for file in files: for ending in list: if file.endswith(ending): os.remove(file) Actually I suspect you would be better using glob.glob here rather than os.walk. Alternatively, using os.basename to split off the extension and comparing that might be better. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From omer at no-log.org Sun Jun 29 17:55:37 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Sun, 29 Jun 2008 17:55:37 +0200 Subject: [Tutor] Deleting specified files using a python program...help with code? In-Reply-To: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: <200806291755.38147.omer@no-log.org> Le Sunday 29 June 2008 17:13:34 Saad Javed, vous avez ?crit?: > I transfer files a lot between my windows and linux partitions...these > folders sometimes contain *.db and *.ini files which are not recognized or > used by linux. So i tried to write a program to crawl through my home dir > and remove these files...I'm *very* new to programming and python so please > be gentle. Here is the code: > > *import os > > list = ['*.ini', '*.db'] > > for root, dirs, files in os.walk('/home/saad'): > **for list in files: > **os.remove(os.path.join('root', 'list')) > print 'done'* > > Unfortunately its a bit too efficient and nearly wiped my home dir before i > manually killed it. Again...treat me like a super noob. > Hum, just a little tip first: create a dummy file hierarchy to test your program, and only run it on your home when you're sure it will work. Of course backing up your home dir might help too :) You're removing all files found by walk() without checking if they match the patterns in list, so your script just removes every files under /home/saad. I'd suggest something like this: import os import glob input_dir = '...' pattern_list = ['*.ini', '*.db'] for root, dirs, files in os.walk(input_dir) : for pattern in pattern_list : full_pattern = os.path.join(root, pattern) for filename in glob.glob(full_pattern) : os.remove(filename) or you can do something similar with the fnmatch module. See http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-fnmatch.html -- C?dric Lucantis From metolone+gmane at gmail.com Sun Jun 29 18:11:29 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 29 Jun 2008 09:11:29 -0700 Subject: [Tutor] Deleting specified files using a python program...help withcode? References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: "Saad Javed" wrote in message news:3c10cd400806290813s6cb74717u3e86a0196c86803d at mail.gmail.com... > I transfer files a lot between my windows and linux partitions...these > folders sometimes > contain *.db and *.ini files which are not recognized or used by linux. > So i tried to write a program to crawl through my home dir and remove > these files... > I'm *very* new to programming and python so please be gentle. Here is > > the code: > > import os > > list = ['*.ini', '*.db'] > > for root, dirs, files in os.walk('/home/saad'): > > for list in files: > > os.remove(os.path.join('root', 'list')) > print 'done' > > > Unfortunately its a bit too efficient and nearly wiped my home dir before > i manually killed it. Again...treat me like a super noob. It's a good idea to use "print" instead of a destructive command like "os.remove" until print displays the correct filenames :^) Also, "list" and "file" are Python built-ins, so avoid using those names in code. import os,fnmatch patterns = '*.ini *.db'.split() for root,dirs,files in os.walk('/home/saad'): for pattern in patterns: for file_ in fnmatch.filter(files,pattern): print os.path.join(root,file_) -Mark From sbjaved at gmail.com Sun Jun 29 20:13:23 2008 From: sbjaved at gmail.com (Saad Javed) Date: Mon, 30 Jun 2008 00:13:23 +0600 Subject: [Tutor] Deleting specified files using a python program...help with code? In-Reply-To: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: <3c10cd400806291113o2aa539d2qda18db9db0004371@mail.gmail.com> Thanks a lot for all the help! If there were a module named "common-sense" i could insert into my brain...I wouldn't have lost my /home. Thanks again Saad From muchanek at gmail.com Sun Jun 29 20:28:11 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Sun, 29 Jun 2008 21:28:11 +0300 Subject: [Tutor] Tutor Digest, Vol 52, Issue 87 In-Reply-To: References: Message-ID: <1214764091.6922.8.camel@www.kinuthia.com> On Sun, 2008-06-29 at 10:20 +0200, tutor-request at python.org wrote: > Message: 1 > Date: Sat, 28 Jun 2008 21:53:44 -0400 > From: Kirk Z Bailey > Subject: [Tutor] arrays in python > To: tutor at python.org > Message-ID: <4866EB28.405 at verizon.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Just wondering, if I can find a way to do a 2 dimensional array in > python. 1 dimension would be a list it would seem; for 2, I could use > a > list of lists? > > Strange how I can't think of ever needing one since I discovered > snake > charming, but so many languages do foo dimensional arrays, it would > seem > like there ought to be a way to do it in python. > > -- >>> from numpy import * # import the necessary module >>> arry = array((1,2,3,4)) # create a rank-one array >>> print arry [1 2 3 4] >>> print arry.shape (4,) # this means it is a rank 1 array with a length of 4 (the trailing comma means it is a tuple) To get to the first element in the array: >>> print arry[0] 1 To get to the last element: >>> print arry[-1] 4 >>> arry2 = array(([5,6,7,8],[9,10,11,12])) # create a a rank-two array, two-dimensional, if wish >>> print arry2 [[ 5 6 7 8] [ 9 10 11 12]] >>> print arry2.shape # > (2, 4) # this means that it is a rank 2 (ie 2-dimensional) array, with each axis having a length of 4 >>> To get to the first element in the first axis: >>> print arry2[0,0] 5 To get to the last element in the second axis: >>>> print arry2[1,-1] 12 You can slice it, reshape it, literally you can contort in way you want! Does this help? Kinuthia... From dkuhlman at rexx.com Sun Jun 29 21:18:31 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 29 Jun 2008 12:18:31 -0700 Subject: [Tutor] Create file and input text In-Reply-To: <4866D317.8000606@abbottdavid.com> References: <4866D317.8000606@abbottdavid.com> Message-ID: <20080629191830.GA78565@cutter.rexx.com> On Sat, Jun 28, 2008 at 08:11:03PM -0400, David wrote: > Hi, I am very new to python and it is my first attempt at programing > except for some basic bash scripts. I came up with this; > #!/usr/bin/python > > import os > filename = raw_input('Enter the filename: ') > fobj = open(filename, 'w') > yourname = raw_input('What is your name: ') > fobj.write(yourname) > fobj.close() > > It seems to work Ok, I was shocked! Is it OK? It looks like good code to me. But, one suggestion: It's dangerous code, unless you can trust your users. They can over-write files. In a real application, you might want to do some checking on the file before opening it. Consider using something like this: if os.path.exists(filename): print 'Warning. File %s exists.' % filename else: fobj = open( ... - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Sun Jun 29 21:28:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 Jun 2008 15:28:01 -0400 Subject: [Tutor] need help; save web data In-Reply-To: <8f6846bb0806281854x59377081h86ccdc9cd959bd4@mail.gmail.com> References: <8f6846bb0806281854x59377081h86ccdc9cd959bd4@mail.gmail.com> Message-ID: <1c2a2c590806291228y49f5ea60i912ffb3200105310@mail.gmail.com> On Sat, Jun 28, 2008 at 9:54 PM, Michael Miesner wrote: > Hi all- > I am trying to save the output of a web search to a local file, using > python. > Im really new to this, but I want to be able to write a program that uses > google scholar, but takes search results and saves them to a local file. > I am perfectly fine with playing around wtih this until I get it, but I dont > know how to begin to get python to grab the output of a given search on > google scholar and save it to a file. You can use urllib2 to post to a web server and get the result back, then use ordinary file save. I have some notes here: http://personalpages.tds.net/~kent37/kk/00010.html Note that this may be a violation of the Google Scholar terms of service; I know it is a violation to automatically collect normal Google search results, and IIRC Google takes some steps to make it difficult as well. Kent From kent37 at tds.net Sun Jun 29 21:33:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 Jun 2008 15:33:12 -0400 Subject: [Tutor] Deleting specified files using a python program...help with code? In-Reply-To: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: <1c2a2c590806291233v680560eued117fe8f45bc1bf@mail.gmail.com> On Sun, Jun 29, 2008 at 11:13 AM, Saad Javed wrote: > import os > > list = ['*.ini', '*.db'] > > for root, dirs, files in os.walk('/home/saad'): > for list in files: > os.remove(os.path.join('root', 'list')) > print 'done' > > Unfortunately its a bit too efficient and nearly wiped my home dir before i > manually killed it. Again...treat me like a super noob. Hmmm...with the quotes on 'root' and 'list' it would only delete /root/list. Please post the same code that you run! Kent From omer at no-log.org Sun Jun 29 21:35:00 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 29 Jun 2008 21:35:00 +0200 Subject: [Tutor] Create file and input text In-Reply-To: <20080629191830.GA78565@cutter.rexx.com> References: <4866D317.8000606@abbottdavid.com> <20080629191830.GA78565@cutter.rexx.com> Message-ID: <200806292135.00760.omer@no-log.org> Le Sunday 29 June 2008 21:18:31 Dave Kuhlman, vous avez ?crit?: > On Sat, Jun 28, 2008 at 08:11:03PM -0400, David wrote: > > Hi, I am very new to python and it is my first attempt at programing > > except for some basic bash scripts. I came up with this; > > #!/usr/bin/python > > > > import os > > filename = raw_input('Enter the filename: ') > > fobj = open(filename, 'w') > > yourname = raw_input('What is your name: ') > > fobj.write(yourname) > > fobj.close() > > > > It seems to work Ok, I was shocked! Is it OK? > > It looks like good code to me. But, one suggestion: It's dangerous > code, unless you can trust your users. They can over-write files. In > a real application, you might want to do some checking on the file > before opening it. Consider using something like this: > > if os.path.exists(filename): > print 'Warning. File %s exists.' % filename > else: > fobj = open( ... > If you really care about overwriting files, there is a race condition here (the file could be created between os.path.exists and the open call), so you should rather write it like this: try: fd = os.open(filename, os.O_WRONLY | os.O_EXCL | os.O_CREAT) except IOError, exc: if exc.errno != errno.EEXIST : raise print 'File %s already exists.' % filename fobj = os.fdopen(fd) (but I guess this doesn't work on all platforms) -- C?dric Lucantis From cappy2112 at gmail.com Sun Jun 29 21:47:34 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 29 Jun 2008 12:47:34 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var Message-ID: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> Message: 9 Date: Sun, 29 Jun 2008 01:20:16 -0700 From: "wesley chun" Subject: Re: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? To: kf9150 at gmail.com, "Alan Gauld" Cc: tutor at python.org >>the reason why i ask is because it's not standard practice i see >>people doing this with Python, Why? Since when is setting anything to None an outdated practice? Does this mean checking an object to None is also outdated? Setting it to None immediately puts the object in a state where the user knows they need to re-initialize it before using it again. del will only reclaim that var at a later time, when the gc kicks in. Of course, if that object won't be used again in the same scope, does it really matter ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Sun Jun 29 21:53:17 2008 From: david at abbottdavid.com (David) Date: Sun, 29 Jun 2008 15:53:17 -0400 Subject: [Tutor] Create file and input text In-Reply-To: <20080629191830.GA78565@cutter.rexx.com> References: <4866D317.8000606@abbottdavid.com> <20080629191830.GA78565@cutter.rexx.com> Message-ID: <4867E82D.40706@abbottdavid.com> Dave Kuhlman wrote: > On Sat, Jun 28, 2008 at 08:11:03PM -0400, David wrote: > >> Hi, I am very new to python and it is my first attempt at programing >> except for some basic bash scripts. I came up with this; >> #!/usr/bin/python >> >> import os >> filename = raw_input('Enter the filename: ') >> fobj = open(filename, 'w') >> yourname = raw_input('What is your name: ') >> fobj.write(yourname) >> fobj.close() >> >> It seems to work Ok, I was shocked! Is it OK? >> > > It looks like good code to me. But, one suggestion: It's dangerous > code, unless you can trust your users. They can over-write files. In > a real application, you might want to do some checking on the file > before opening it. Consider using something like this: > > if os.path.exists(filename): > print 'Warning. File %s exists.' % filename > else: > fobj = open( ... > > > - Dave > > > Thanks Dave, cool name :) here is what I came up with, seems to work as expected; #!/usr/bin/python import os filename = raw_input('Enter the filename: ') if os.path.exists(filename): print 'Warning. File %s exists. -1 to quit' % filename if (filename != -1): fobj = open(filename, 'w') yourname = raw_input('What is your name: ') fobj.write(yourname) fobj.close() -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From omer at no-log.org Sun Jun 29 22:09:38 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 29 Jun 2008 22:09:38 +0200 Subject: [Tutor] Create file and input text In-Reply-To: <4867E82D.40706@abbottdavid.com> References: <4866D317.8000606@abbottdavid.com> <20080629191830.GA78565@cutter.rexx.com> <4867E82D.40706@abbottdavid.com> Message-ID: <200806292209.38810.omer@no-log.org> Le Sunday 29 June 2008 21:53:17 David, vous avez ?crit?: > Dave Kuhlman wrote: > > On Sat, Jun 28, 2008 at 08:11:03PM -0400, David wrote: > >> Hi, I am very new to python and it is my first attempt at programing > >> except for some basic bash scripts. I came up with this; > >> #!/usr/bin/python > >> > >> import os > >> filename = raw_input('Enter the filename: ') > >> fobj = open(filename, 'w') > >> yourname = raw_input('What is your name: ') > >> fobj.write(yourname) > >> fobj.close() > >> > >> It seems to work Ok, I was shocked! Is it OK? > > > > It looks like good code to me. But, one suggestion: It's dangerous > > code, unless you can trust your users. They can over-write files. In > > a real application, you might want to do some checking on the file > > before opening it. Consider using something like this: > > > > if os.path.exists(filename): > > print 'Warning. File %s exists.' % filename > > else: > > fobj = open( ... > > > > > > - Dave > > Thanks Dave, cool name :) > here is what I came up with, seems to work as expected; > #!/usr/bin/python > > import os > filename = raw_input('Enter the filename: ') > if os.path.exists(filename): > print 'Warning. File %s exists. -1 to quit' % filename > if (filename != -1): > fobj = open(filename, 'w') > yourname = raw_input('What is your name: ') > fobj.write(yourname) > fobj.close() Well, you're asking the user to enter -1 after the raw_input, so if the file exists your script will just print 'File exists... -1 to quit' and open it anyway. See my previous post for a better way of handling it, but in your case you should at least do something like this: filename = raw_input('Enter the filename: ') if os.path.exists(filename): r = raw_input('Warning, file %s exists, overwrite it [y/n] ? ' % filename) if r != 'y' : sys.exit(0) fobj = open(...) -- C?dric Lucantis From david at abbottdavid.com Sun Jun 29 22:32:23 2008 From: david at abbottdavid.com (David) Date: Sun, 29 Jun 2008 16:32:23 -0400 Subject: [Tutor] Create file and input text In-Reply-To: <200806292209.38810.omer@no-log.org> References: <4866D317.8000606@abbottdavid.com> <20080629191830.GA78565@cutter.rexx.com> <4867E82D.40706@abbottdavid.com> <200806292209.38810.omer@no-log.org> Message-ID: <4867F157.2060309@abbottdavid.com> C?dric Lucantis wrote: > > Well, you're asking the user to enter -1 after the raw_input, so if the file > exists your script will just print 'File exists... -1 to quit' and open it > anyway. See my previous post for a better way of handling it, but in your > case you should at least do something like this: > > filename = raw_input('Enter the filename: ') > if os.path.exists(filename): > r = raw_input('Warning, file %s exists, overwrite it [y/n] ? ' % filename) > if r != 'y' : sys.exit(0) > fobj = open(...) > > Thanks C?dric Lucantis, I will have to study some more; os.open(filename, os.O_WRONLY | os.O_EXCL | os.O_CREAT) Is over my head at this time. With your suggestion I did come up with this; #!/usr/bin/python import os import sys filename = raw_input('Enter the filename: ') if os.path.exists(filename): r = raw_input( 'Warning, file %s exists, overwrite it [y/n] ? ' % filename) if r != 'y' : sys.exit(0) fobj = open(filename, 'w') yourname = raw_input('What is your name: ') fobj.write(yourname) fobj.close() -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From muchanek at gmail.com Sun Jun 29 22:34:33 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Sun, 29 Jun 2008 23:34:33 +0300 Subject: [Tutor] Problem Euler 26 Message-ID: <1214771673.6922.46.camel@www.kinuthia.com> Hi, I am trying to solve Problem Number 26 (http://projecteuler.net/index.php?section=problems&id=26) on project Euler but apparently the answer I am submitting is wrong. Here is the problem: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. I am giving the answer 38, because 1/38 = 0.0263157894. It seems I have misunderstood the question or I cant solve it! Here is the code that I came up with: def aux(num): import re pattern = re.compile(r"^0?1?2?3?4?5?6?7?8?9?$") frac ="%.9f"%(1.0/num) fracSlice = frac[2:] # get the decimal fractional part, ie remove '0.' fracList = list(fracSlice) #convert string to a list fracList.sort() # I need to sort , because I will be searching by increasing order testFrac = "".join(fracList) # convert list back to a string, phew! if re.match(pattern,testFrac): # if the pattern matches, the number is our candidate print (num,fracSlice) for b in xrange(1,1000): aux(b) Er... er, that does not exactly work as expected but it narrows the search to only 3 candidates because of the inclusion of the zero: (28, '035714286') (38, '026315789') (81, '012345679') For 28, the digit, in the fractional part, after 8 is 5, so 5 is repeated and as for, 81 the next digit after 7 is 0, so again 0 occurs twice. But for 38, the next digit after 9 is 4, and because it has NOT occurred before, I assume 38 is the correct answer... and I am wrong! I suspect I have completely misunderstood the question. Any ideas? Thanks! Kinuthia... From omer at no-log.org Sun Jun 29 22:53:12 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 29 Jun 2008 22:53:12 +0200 Subject: [Tutor] Create file and input text In-Reply-To: <4867F157.2060309@abbottdavid.com> References: <4866D317.8000606@abbottdavid.com> <200806292209.38810.omer@no-log.org> <4867F157.2060309@abbottdavid.com> Message-ID: <200806292253.12842.omer@no-log.org> Le Sunday 29 June 2008 22:32:23 David, vous avez ?crit?: > C?dric Lucantis wrote: > > Well, you're asking the user to enter -1 after the raw_input, so if the > > file exists your script will just print 'File exists... -1 to quit' and > > open it anyway. See my previous post for a better way of handling it, but > > in your case you should at least do something like this: > > > > filename = raw_input('Enter the filename: ') > > if os.path.exists(filename): > > r = raw_input('Warning, file %s exists, overwrite it [y/n] ? ' % > > filename) if r != 'y' : sys.exit(0) > > fobj = open(...) > > Thanks C?dric Lucantis, > I will have to study some more; > os.open(filename, os.O_WRONLY | os.O_EXCL | os.O_CREAT) > Is over my head at this time. > > With your suggestion I did come up with this; > > #!/usr/bin/python > > import os > import sys > filename = raw_input('Enter the filename: ') > if os.path.exists(filename): > r = raw_input( > 'Warning, file %s exists, overwrite it [y/n] ? ' % filename) > if r != 'y' : sys.exit(0) > fobj = open(filename, 'w') > yourname = raw_input('What is your name: ') > fobj.write(yourname) > fobj.close() > > -david Sounds good to me, it should be enough for your needs. Just remember that the file could be created by another process between the calls to os.path.exists() and open(), which is a real security problem in a 'serious' application. Read this if you want to know more (this is the libc documentation, but the os python module uses the same syntax and flags) : http://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html#Opening-and-Closing-Files http://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html#Open_002dtime-Flags -- C?dric Lucantis From wescpy at gmail.com Sun Jun 29 22:59:06 2008 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Jun 2008 13:59:06 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> Message-ID: <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> > >>the reason why i ask is because it's not standard practice i see > >>people doing this with Python, > > Why? i've been programming in Python continously/full-time for the past 11 yrs at 4+ companies, and i'll stand by my statement... i just don't see it in the code, nor do i do this myself. i cannot tell you *exactly* why, other than most of the time, people let objects go out-of-scope and are reclaimed "naturally" or more rarely, i see people calling del on an object to remove it from the namespace explicitly. now, what i *do* see a lot is where a variable is originally initialized to None. > Since when is setting anything to None an outdated practice? not sure what you mean here, but i never said anything like this in my reply, nor was there any reference to anything being outdated. > Does this mean checking an object to None is also outdated? again, i'm not sure what you mean here as my reply never inferred this. although i am curious... how *do* you check an object to None? (this is a completely tangential thread, but i'm curious if the beginners -- not the experts -- are familiar with the difference between "if obj == None" vs. "if obj is None".) > Setting it to None immediately puts the object in a state where the user > knows they need to re-initialize it before using it again. there is no more "object" since you replaced it with None. i'll assume you mean the variable. the only difference between this and using del is that you leave the name in the namespace (where it holds a reference to None). > del will only reclaim that var at a later time, when the gc kicks in. again, you said "var" but i'm assuming you mean object. the var is removed from the namespace and the object's reference count decremented. the gc won't claim if there are additional aliases or references to the object. > Of course, if that object won't be used again in the same scope, does it > really matter ? then just let it go out of scope. there's no need to set it to anything else if it won't be used again... you're just wasting CPU cycles and memory access then. cheers, -wesley From mwalsh at groktech.org Mon Jun 30 00:26:35 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 29 Jun 2008 17:26:35 -0500 Subject: [Tutor] Problem Euler 26 In-Reply-To: <1214771673.6922.46.camel@www.kinuthia.com> References: <1214771673.6922.46.camel@www.kinuthia.com> Message-ID: <48680C1B.6060208@groktech.org> kinuthiA muchanE wrote: > Hi, Hi Kinuthia, > I am trying to solve Problem Number 26 > (http://projecteuler.net/index.php?section=problems&id=26) on project > Euler but apparently the answer I am submitting is wrong. > I am a big fan of Project Euler also. Fun stuff. > I suspect I have completely misunderstood the question. You're probably right, but it's not clear from your description (to me anyway), what your understanding of the question is. > > Any ideas? > Thanks! Perhaps it would be helpful to look at the next few values of d, as defined by the question (note: the parens enclose the repeating pattern): """ 1.0/11 = 0.(09) 1.0/12 = 0.08(3) 1.0/13 = 0.(076923) 1.0/14 = 0.0(714285) 1.0/15 = 0.0(6) 1.0/16 = 0.0625 1.0/17 = 0.(0588235294117647) """ No spoilers there, hopefully :) Have fun! Marty From john at fouhy.net Mon Jun 30 00:39:58 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 30 Jun 2008 10:39:58 +1200 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <20080628010246.9295E1E4003@bag.python.org> References: <20080628010246.9295E1E4003@bag.python.org> Message-ID: <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> On 28/06/2008, Dick Moores wrote: > I'm very familiar with appending x to a list, s, using s.append(x), however, > I've never understood what the docs mean by > > s.append(x) same as s[len(s):len(s)] = [x] In addition to Douglas's comment, do you understand how assignment with slices works? e.g. can you predict the result of the following operations without trying it? a = [1, 2, 3, 4] a[1:3] = [7, 8] print a -- John. From mwalsh at groktech.org Mon Jun 30 00:47:31 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 29 Jun 2008 17:47:31 -0500 Subject: [Tutor] Problem Euler 26 In-Reply-To: <1214771673.6922.46.camel@www.kinuthia.com> References: <1214771673.6922.46.camel@www.kinuthia.com> Message-ID: <48681103.7080903@groktech.org> kinuthiA muchanE wrote: > > (28, '035714286') > (38, '026315789') > (81, '012345679') > > For 28, the digit, in the fractional part, after 8 is 5, so 5 is > repeated and as for, 81 the next digit after 7 is 0, so again 0 occurs > twice. But for 38, the next digit after 9 is 4, and because it has NOT > occurred before, I assume 38 is the correct answer... and I am wrong! > Ah, sorry -- I didn't parse this properly the first time through. You should also be aware of the limitations of representing a decimal fractions as a float. I'll defer to the docs, instead of trying (and failing) to explain this myself: http://docs.python.org/tut/node16.html Also, have a look in the standard library, there was a module added in 2.4 which will provide additional assistance. HTH, Marty From cappy2112 at gmail.com Mon Jun 30 00:53:05 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 29 Jun 2008 15:53:05 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> Message-ID: <8249c4ac0806291553q5706e46ex5b6f2c2b5ff74900@mail.gmail.com> Wes, is this not your reply? "the reason why i ask is because it's not standard practice i see people doing this with Python, so i'm trying to get a better understanding of what you're trying to do. thanks! -- wesley" > *exactly* why, other than most of the time, people let objects go > out-of-scope and are reclaimed "naturally" or more rarely, i see > people calling del on an object to remove it from the namespace > explicitly. now, what i *do* see a lot is where a variable is > originally initialized to None. > > > > Since when is setting anything to None an outdated practice? > > >>not sure what you mean here, but i never said anything like this in my > >>reply, nor was there any reference to anything being outdated. The original author asked about the similarity between VB setting an object to Nothing, and Python vars being set to None Your answer implies that this is an outdate practice (or not preferred) in Python > > > Does this mean checking an object to None is also outdated? > > >>again, i'm not sure what you mean here as my reply never inferred > >>this. although i am curious... how *do* you check an object to None? > This was my own question, If you don't set an object to None- explicitly, > then to you ever check to see if an object is None? > >>you mean the variable. the only difference between this and using del >>again, you said "var" but i'm assuming you mean object. The original post referred to var, but a var is aon object- so I wasn't consistant..... -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Jun 30 01:19:56 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 30 Jun 2008 11:19:56 +1200 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> Message-ID: <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> On 30/06/2008, wesley chun wrote: > (this is a completely tangential thread, but i'm curious if the > beginners -- not the experts -- are familiar with the difference > between "if obj == None" vs. "if obj is None".) As I understand it there are no cases where obj==None and obj is None will give different results (which is not true for == vs is in general), so is there any practical difference? Maybe you save a handful of cycles? -- John. From dyoo at cs.wpi.edu Mon Jun 30 01:28:58 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Sun, 29 Jun 2008 19:28:58 -0400 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> Message-ID: > As I understand it there are no cases where obj==None and obj is None > will give different results I hate going off track, but: ###################################### class CounterExample: def __eq__(self, other): return True print "is?", CounterExample() is None print "==", CounterExample() == None ###################################### That being said, this is an evil and perverse example. In any case, setting something to None might not be such a bad thing. 'del someVariable', on the other hand, is almost always a bad code smell. It's much too low level; it's evidence that the code is not taking advantage of simple mechanisms like functions or local variables. From rdm at rcblue.com Mon Jun 30 04:12:07 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 29 Jun 2008 19:12:07 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com > References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> Message-ID: <20080630021219.230F11E4006@bag.python.org> At 03:39 PM 6/29/2008, John Fouhy wrote: >On 28/06/2008, Dick Moores wrote: > > I'm very familiar with appending x to a list, s, using > s.append(x), however, > > I've never understood what the docs mean by > > > > s.append(x) same as s[len(s):len(s)] = [x] > >In addition to Douglas's comment, do you understand how assignment >with slices works? > >e.g. can you predict the result of the following operations without trying it? > >a = [1, 2, 3, 4] >a[1:3] = [7, 8] >print a I can't make much more of a fool of myself than I already have on this list, so here goes: [1, 7, 8, 4] But it's tough to hit that Send button.. Dick From rdm at rcblue.com Mon Jun 30 04:16:52 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 29 Jun 2008 19:16:52 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com > References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> Message-ID: <20080630021704.414791E4006@bag.python.org> At 03:39 PM 6/29/2008, John Fouhy wrote: >On 28/06/2008, Dick Moores wrote: > > I'm very familiar with appending x to a list, s, using > s.append(x), however, > > I've never understood what the docs mean by > > > > s.append(x) same as s[len(s):len(s)] = [x] > >In addition to Douglas's comment, do you understand how assignment >with slices works? > >e.g. can you predict the result of the following operations without trying it? > >a = [1, 2, 3, 4] >a[1:3] = [7, 8] >print a [1, 7, 8, 4] Whew! (I really wasn't positive that it shouldn't be [1, [7, 8], 4] !) Dick From wescpy at gmail.com Mon Jun 30 06:49:44 2008 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Jun 2008 21:49:44 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <8249c4ac0806291553q5706e46ex5b6f2c2b5ff74900@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> <8249c4ac0806291553q5706e46ex5b6f2c2b5ff74900@mail.gmail.com> Message-ID: <78b3a9580806292149q23e1b055leb747c4fd99d4c7f@mail.gmail.com> > The original author asked about the similarity between VB setting an object > to Nothing, and Python vars being set to None > > Your answer implies that this is an outdate practice (or not preferred) in Python nope, i just said it doesn't appear to be standard practice. i don't see it much in code that i've been around in the past decade+ nor do i do it much myself. neither of those things indicate an "outdated" practice because as far as i know, it was never the norm AFAIK. i mean, it *may* have been before i learned Python (1.4), but i just can't say for sure. > > This was my own question, If you don't set an object to None- explicitly, > then to you ever check to see if an object is None? only in the right circumstances, i.e., i get a return value from some call. -wesley From wescpy at gmail.com Mon Jun 30 06:53:31 2008 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Jun 2008 21:53:31 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> Message-ID: <78b3a9580806292153j4a1c74b3led8d517bbf0825b0@mail.gmail.com> > As I understand it there are no cases where obj==None and obj is None > will give different results (which is not true for == vs is in > general), so is there any practical difference? Maybe you save a > handful of cycles? as far as i know, that's it. but if this comparison happens a *lot* in your code, it starts to add up. for the newbies, just remember that "==" is an object *value* comparison vs. 'is' which is an object *identity* comparison. the former requires pulling out the values of both objects and doing a comparison while the latter is just checking the references to see if both are looking at exactly the same object (IDs match) so there's no need to fetch their values. -wesley ps. danny's example is pretty scary tho... From wescpy at gmail.com Mon Jun 30 08:01:04 2008 From: wescpy at gmail.com (wesley chun) Date: Sun, 29 Jun 2008 23:01:04 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <20080630021704.414791E4006@bag.python.org> References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> <20080630021704.414791E4006@bag.python.org> Message-ID: <78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.com> > > e.g. can you predict the result of the following operations without trying it? > > > > a = [1, 2, 3, 4] > > a[1:3] = [7, 8] > > print a > > [1, 7, 8, 4] Whew! > (I really wasn't positive that it shouldn't be [1, [7, 8], 4] !) good job dick! of course, you *know* i'm going to ask this... how *do* you get it to be [1, [7, 8], 4] given the original 'a'? :-) cheers, -- 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 kf9150 at gmail.com Mon Jun 30 11:26:29 2008 From: kf9150 at gmail.com (Kelie) Date: Mon, 30 Jun 2008 09:26:29 +0000 (UTC) Subject: [Tutor] =?utf-8?q?Is_=22var_=3D_None=22_in_Python_equivalent_to_?= =?utf-8?q?=22Set_var_=3D=09Nothing=22in_VB=3F?= References: <78b3a9580806290120s60db94eby5f09229cac9e7f55@mail.gmail.com> Message-ID: wesley chun gmail.com> writes: > one question i'd like to ask is, in what context is such a line part > of your code? altho alan is correct in that syntactically, they're > very similar, i'm wondering what you're using it for. Wesley, Thanks for your reply (also thanks to others who replied). I was trying to translate a VBA sample in this page http://tinyurl.com/3hvj3j to python. The VBA sample has a line "Set objDbx = Nothing". Btw, I bought your book "Core Python Programming, 2nd Edition" and really enjoy reading it. Thanks. From wescpy at gmail.com Mon Jun 30 11:34:50 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 30 Jun 2008 02:34:50 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? In-Reply-To: References: <78b3a9580806290120s60db94eby5f09229cac9e7f55@mail.gmail.com> Message-ID: <78b3a9580806300234w179a6ea4jc958ffa992e32902@mail.gmail.com> > Thanks for your reply (also thanks to others who replied). I was trying to > translate a VBA sample in this page http://tinyurl.com/3hvj3j to python. The VBA > sample has a line "Set objDbx = Nothing". kelie, thanks for your reply... it helps clear things up -- i didn't think i was going to extend your thread too much further beyond your original question! anyhow, based on the piece of code that you were trying to translate, i believe the Python version of the code will not require setting that variable to None. the reason is that the for-loop will automatically change it to refer to another object. > Btw, I bought your book "Core Python Programming, 2nd Edition" and really enjoy reading it. Thanks. thanks for the kudos kelie! i'm glad that you're getting something out of it! pls be sure to visit the book's website to download the Errata. most of the issues are minor but there are definitely more critical ones to take note of as you're going thru it. send us any more questions as they come up! cheers, -- 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 andreengels at gmail.com Mon Jun 30 11:49:59 2008 From: andreengels at gmail.com (Andre Engels) Date: Mon, 30 Jun 2008 11:49:59 +0200 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? In-Reply-To: References: <78b3a9580806290120s60db94eby5f09229cac9e7f55@mail.gmail.com> Message-ID: <6faf39c90806300249k493e233o9d72fff3841e0c29@mail.gmail.com> On Mon, Jun 30, 2008 at 11:26 AM, Kelie wrote: > wesley chun gmail.com> writes: >> one question i'd like to ask is, in what context is such a line part >> of your code? altho alan is correct in that syntactically, they're >> very similar, i'm wondering what you're using it for. > > Wesley, > > Thanks for your reply (also thanks to others who replied). I was trying to > translate a VBA sample in this page http://tinyurl.com/3hvj3j to python. The VBA > sample has a line "Set objDbx = Nothing". I don't know about Visual Basic, but in Python these statements are unnecessary. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From kent37 at tds.net Mon Jun 30 12:46:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jun 2008 06:46:19 -0400 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var In-Reply-To: <78b3a9580806292153j4a1c74b3led8d517bbf0825b0@mail.gmail.com> References: <8249c4ac0806291247s5c24febera02944468e6dd2f1@mail.gmail.com> <78b3a9580806291359v142cb49dq782eb23401d3b63@mail.gmail.com> <5e58f2e40806291619i166d27feh4c9b7995e2868040@mail.gmail.com> <78b3a9580806292153j4a1c74b3led8d517bbf0825b0@mail.gmail.com> Message-ID: <1c2a2c590806300346u5ac285bcqa8c70d671e3bb08e@mail.gmail.com> On Mon, Jun 30, 2008 at 12:53 AM, wesley chun wrote: >> As I understand it there are no cases where obj==None and obj is None >> will give different results (which is not true for == vs is in >> general), so is there any practical difference? Maybe you save a >> handful of cycles? > > > as far as i know, that's it. but if this comparison happens a *lot* in > your code, it starts to add up. I tend to use "is None" because I think it is more readable and explicit, but I would say using it for performance is premature optimization. kent $ python -m timeit -s "a=3" "a==None" 10000000 loops, best of 3: 0.117 usec per loop kent $ python -m timeit -s "a=3" "a is None" 10000000 loops, best of 3: 0.0608 usec per loop You would have to be doing quite a few comparisons for .06 usec to make a difference. Kent From jmorcombe at westnet.com.au Mon Jun 30 14:47:39 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Mon, 30 Jun 2008 20:47:39 +0800 Subject: [Tutor] destroying windows Message-ID: <4868D5EB.1030204@westnet.com.au> I want to have a program that uses Tkinter to display a window. If the user selects an option, then I want to destroy that window and then display a second window. In turn, the user can select an option to change back to the first window and I want to destroy that window and then display the first again. I have pasted my code below. The window is successfully created. However, I can't figure out the correct way to destroy it. In my first attempt, "window1" is not defined when I go to destroy it and I am not sure how to make "window1" global or what. The error is displayed at the bottom of the program listing. Jim ------------------------------------------------------------------------------------------ from Tkinter import * class display_Colour_Selector_window(): def __init__(self): window1 = Tk() window1.title("Colour Selector") menubar = Menu(window1) # create pulldown menus editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Colour Selector", command=change_to_Colour_Selector) editmenu.add_command(label="Colour Picker", command=change_to_Colour_Picker) menubar.add_cascade(label="Edit", menu=editmenu) # display the menu window1.config(menu=menubar) class display_Colour_Picker_window(): def __init__(self): # The second window will be used for the "Colour Picker" which # allows the User to pick colours from a colour map. window2 = Tk() window2.title("Colour Picker") menubar = Menu(window2) # create pulldown menus editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Colour Selector", command=change_to_Colour_Selector) editmenu.add_command(label="Colour Picker", command=change_to_Colour_Picker) menubar.add_cascade(label="Edit", menu=editmenu) # display the menu window2.config(menu=menubar) def change_to_Colour_Selector(): display_Colour_Picker_window.window2.destroy display_Colour_Selector_window() def change_to_Colour_Picker(): display_Colour_Selector_window.window1.destroy display_Colour_Picker_window() def hello(): print "hello!" #--------------------------------------------------------------------# # The program starts here # #--------------------------------------------------------------------# display_Colour_Selector_window() # To run this from IDLE, I will just comment out the mainloop() # because IDLE is written in Tkinter and actually has its own mainloop() # running, which thoroughly confuses my own program. # mainloop() ----------------------------------------------------------------------------------------------- The error: IDLE 1.2.1 ==== No Subprocess ==== >>> >>> Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "D:/ComputerScienceProgramming/test.py", line 53, in change_to_Colour_Picker display_Colour_Selector_window.window1.destroy AttributeError: class display_Colour_Selector_window has no attribute 'window1' From sbjaved at gmail.com Mon Jun 30 16:17:45 2008 From: sbjaved at gmail.com (Saad Javed) Date: Mon, 30 Jun 2008 20:17:45 +0600 Subject: [Tutor] Deleting specified files using a python program...help with code? In-Reply-To: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> Message-ID: <3c10cd400806300717j862c158pca2697932a37a13c@mail.gmail.com> Here's the working code for my problem. But i tried it to post 'No files found' in case no specified files are found. It doesn't do that. Just simply exits. dir_input = raw_input('Enter dir: ') win_trace = ['*.ini', '*.db'] for root, dirs, files in os.walk(dir_input): for trace in win_trace: win_trace_path = os.path.join(root, trace) for filename in glob.glob(win_trace_path): if os.path.exists(filename): print filename else: print 'No files found' confirmation = raw_input('Confirm removal: ') if confirmation == 'y': os.remove(filename) print 'done' elif confirmation == 'n': pass else: sys.exit() On Sun, Jun 29, 2008 at 9:13 PM, Saad Javed wrote: > I transfer files a lot between my windows and linux partitions...these > folders sometimes contain *.db and *.ini files which are not recognized or > used by linux. So i tried to write a program to crawl through my home dir > and remove these files...I'm *very* new to programming and python so please > be gentle. Here is the code: > > import os > > list = ['*.ini', '*.db'] > > for root, dirs, files in os.walk('/home/saad'): > for list in files: > os.remove(os.path.join('root', 'list')) > print 'done' > > Unfortunately its a bit too efficient and nearly wiped my home dir before i > manually killed it. Again...treat me like a super noob. > > Saad > From omer at no-log.org Mon Jun 30 16:50:09 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 16:50:09 +0200 Subject: [Tutor] Deleting specified files using a python program...help with code? In-Reply-To: <3c10cd400806300717j862c158pca2697932a37a13c@mail.gmail.com> References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com> <3c10cd400806300717j862c158pca2697932a37a13c@mail.gmail.com> Message-ID: <200806301650.09167.omer@no-log.org> Le Monday 30 June 2008 16:17:45 Saad Javed, vous avez ?crit?: > Here's the working code for my problem. But i tried it to post 'No > files found' in case no specified files are found. It doesn't do that. > Just simply exits. > > dir_input = raw_input('Enter dir: ') > > win_trace = ['*.ini', '*.db'] > > for root, dirs, files in os.walk(dir_input): > for trace in win_trace: > win_trace_path = os.path.join(root, trace) > for filename in glob.glob(win_trace_path): > if os.path.exists(filename): > print filename > else: > print 'No files found' glob() will of course always return existing files only, so this part of the test will never be reached, unless the file is removed by another process between glob() and exists() which is very unlikely to happen. > confirmation = raw_input('Confirm removal: ') > if confirmation == 'y': > os.remove(filename) > print 'done' just printing 'done' for each file won't help the user, this would be better: print "removing '%s'" % filename os.remove(filename) (a confirmation after the remove() is not really necessary, as python will raise an exception and abort the program if an error occurs) > elif confirmation == 'n': > pass > else: > sys.exit() maybe an error message would help the user here too. sys.exit() accepts a string argument for that: sys.exit('invalid answer'). It will just print the message on stderr and exit with an error code. Finally, if what you want is to print a message at the end when no file has been processed, you can do this: removed_files = 0 for root, dir, file in ... : ... if confirmation == 'y' : os.remove(filename) removed_files += 1 ... if removed_files : print '%d files removed' % files_removed else : print 'No files found' -- C?dric Lucantis From srilyk at gmail.com Mon Jun 30 16:54:06 2008 From: srilyk at gmail.com (W W) Date: Mon, 30 Jun 2008 09:54:06 -0500 Subject: [Tutor] need help; save web data In-Reply-To: <1c2a2c590806291228y49f5ea60i912ffb3200105310@mail.gmail.com> References: <8f6846bb0806281854x59377081h86ccdc9cd959bd4@mail.gmail.com> <1c2a2c590806291228y49f5ea60i912ffb3200105310@mail.gmail.com> Message-ID: <333efb450806300754k3ba014few15727c56bf7290bd@mail.gmail.com> On Sun, Jun 29, 2008 at 2:28 PM, Kent Johnson wrote: > Note that this may be a violation of the Google Scholar terms of > service; I know it is a violation to automatically collect normal > Google search results, and IIRC Google takes some steps to make it > difficult as well. Specifically, you *can't* use urllib/urllib2 on it's own. If you have some type of google coder id, you're allowed to use that with your post. Otherwise it will just send you back to the google homepage. I know, cause I tried before I knew it was a no no :P Although if you're *that* serious, and don't care about fallout, you can use a proxy so it doesn't read that the request is coming from urllib via a python script. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From omer at no-log.org Mon Jun 30 17:56:08 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 17:56:08 +0200 Subject: [Tutor] destroying windows In-Reply-To: <4868D5EB.1030204@westnet.com.au> References: <4868D5EB.1030204@westnet.com.au> Message-ID: <200806301756.08533.omer@no-log.org> Le Monday 30 June 2008 14:47:39 Jim Morcombe, vous avez ?crit?: > I want to have a program that uses Tkinter to display a window. > If the user selects an option, then I want to destroy that window and > then display a second window. > In turn, the user can select an option to change back to the first > window and I want to destroy that window and then display the first again. > > I have pasted my code below. The window is successfully created. > However, I can't figure out the correct way to destroy it. > In my first attempt, "window1" is not defined when I go to destroy it > and I am not sure how to make "window1" global or what. > Using global variables may help for simple scripts, but is not a good practice in general. Anyway you could it like this: # this in the global scope window1 = None class display_Colour_Selector_window(): def __init__(self): global window1 window1 = Tk() ... def change_to_Colour_Picker(): window1.destroy (note that the global statement is only required when you set the variable, not when you only read it) But a better design would be to use instance attributes and methods for your callbacks instead, so the whole stuff is 'packed' inside your class: class display_Colour_Selector_window(): def __init__(self): self.window1 = Tk() self.window1.title("Colour Selector") menubar = Menu(self.window1) # create pulldown menus editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Colour Picker", command=self.change_to_Colour_Picker) menubar.add_cascade(label="Edit", menu=editmenu) # display the menu self.window1.config(menu=menubar) def change_to_Colour_Picker (self) : self.window1.destroy() display_Colour_Picker_window() -- C?dric Lucantis From cappy2112 at gmail.com Mon Jun 30 20:43:22 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 30 Jun 2008 11:43:22 -0700 Subject: [Tutor] Is "var = None" in Python equivalent to "Set var Message-ID: <8249c4ac0806301143q353276c0m1e5b8a9153ee8bed@mail.gmail.com> Message: 5 Date: Mon, 30 Jun 2008 11:49:59 +0200 From: "Andre Engels" Subject: Re: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB? To: Kelie Cc: tutor at python.org Message-ID: <6faf39c90806300249k493e233o9d72fff3841e0c29 at mail.gmail.com> Content-Type: text/plain; charset=UTF-8 >>I don't know about Visual Basic, In VB6 ( I have not worked with VB.NET), objects are set to Nothing when they go out of scope, yet there is a fair amount lot of code out there where objects are explicitly set to Nothing. This is a pretty common practice in VB land. >>but in Python these statements are unnecessary. What happened to "Explicit is better than implicit"? -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Mon Jun 30 20:55:36 2008 From: norman at khine.net (Norman Khine) Date: Mon, 30 Jun 2008 20:55:36 +0200 Subject: [Tutor] list objects are unhashable Message-ID: <48692C28.2050804@khine.net> Hello, I would like to count list items but am not 100% sure how to do it. Here is what I have so far: for brain in brains: x = getattr(brain, horizontal) y = getattr(brain, vertical) if x and y and (x, y) in table: table[(x, y)] += 1 table[(x, '')] += 1 table[('', y)] += 1 table[('', '')] += 1 but when I run this, I get the following error on the line: if x and y and (x, y) in table: TypeError: list objects are unhashable where: x = ['airlines-scheduled', 'airport-car-parking'] I am basically looping through files within each file, I have an entity, for example: file1 airlines-scheduled airport-car-parking file2 airport-car-parking etc... So the above code counts all occurrences of 'airport-car-parking' and sums it up. All works well if, I change the code to: for brain in brains: x = getattr(brain, horizontal) x = string.join(x, '' ) y = getattr(brain, vertical) y = string.join(y, '' ) if x and y and (x, y) in table: table[(x, y)] += 1 table[(x, '')] += 1 table[('', y)] += 1 table[('', '')] += 1 So now my list becomes a string, which is not really good for me, as this fails when there is more then one item. Is there a better way to loop through this and sum up all occurrences of each entry ie 'airport-car-parking' Cheers Norman From omer at no-log.org Mon Jun 30 21:09:28 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 21:09:28 +0200 Subject: [Tutor] list objects are unhashable In-Reply-To: <48692C28.2050804@khine.net> References: <48692C28.2050804@khine.net> Message-ID: <200806302109.28330.omer@no-log.org> Le Monday 30 June 2008 20:55:36 Norman Khine, vous avez ?crit?: > Hello, > > I would like to count list items but am not 100% sure how to do it. > > Here is what I have so far: > > for brain in brains: > x = getattr(brain, horizontal) > y = getattr(brain, vertical) > if x and y and (x, y) in table: > table[(x, y)] += 1 > table[(x, '')] += 1 > table[('', y)] += 1 > table[('', '')] += 1 > > but when I run this, I get the following error on the line: > > if x and y and (x, y) in table: > > TypeError: list objects are unhashable > > where: > > x = ['airlines-scheduled', 'airport-car-parking'] > lists are not hashable because hashing a mutable type would be dangerous, but tuples are if all their items are hashable too. Just replace x by tuple(x). -- C?dric Lucantis From norman at khine.net Mon Jun 30 21:31:35 2008 From: norman at khine.net (Norman Khine) Date: Mon, 30 Jun 2008 21:31:35 +0200 Subject: [Tutor] list objects are unhashable In-Reply-To: <200806302109.28330.omer@no-log.org> References: <48692C28.2050804@khine.net> <200806302109.28330.omer@no-log.org> Message-ID: <48693497.5090702@khine.net> Thanks, but where do i replace the x with tuple(x) Norman C?dric Lucantis wrote: > Le Monday 30 June 2008 20:55:36 Norman Khine, vous avez ?crit : >> Hello, >> >> I would like to count list items but am not 100% sure how to do it. >> >> Here is what I have so far: >> >> for brain in brains: >> x = getattr(brain, horizontal) >> y = getattr(brain, vertical) >> if x and y and (x, y) in table: >> table[(x, y)] += 1 >> table[(x, '')] += 1 >> table[('', y)] += 1 >> table[('', '')] += 1 >> >> but when I run this, I get the following error on the line: >> >> if x and y and (x, y) in table: >> >> TypeError: list objects are unhashable >> >> where: >> >> x = ['airlines-scheduled', 'airport-car-parking'] >> > > lists are not hashable because hashing a mutable type would be dangerous, but > tuples are if all their items are hashable too. Just replace x by tuple(x). > From omer at no-log.org Mon Jun 30 21:52:40 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 21:52:40 +0200 Subject: [Tutor] list objects are unhashable In-Reply-To: <48693497.5090702@khine.net> References: <48692C28.2050804@khine.net> <200806302109.28330.omer@no-log.org> <48693497.5090702@khine.net> Message-ID: <200806302152.40199.omer@no-log.org> Le Monday 30 June 2008 21:31:35, vous avez ?crit?: > Thanks, > but where do i replace the x with tuple(x) > Whenever x is hashed, ie used as a key in a dictionary. You said you have: > >> table[(x, y)] += 1 > >> where: > >> > >> x = ['airlines-scheduled', 'airport-car-parking'] so you should rather write this (if y is a list too): table[(tuple(x), tuple(y))] += 1 but of course you can also use tuples directly if your lists don't have to be modified: x = ('airlines-scheduled', 'airport-car-parking') y = (...) table[(x, y)] += 1 -- C?dric Lucantis From alan.gauld at btinternet.com Mon Jun 30 22:18:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jun 2008 21:18:08 +0100 Subject: [Tutor] destroying windows References: <4868D5EB.1030204@westnet.com.au> Message-ID: "Jim Morcombe" wrote > If the user selects an option, then I want to destroy that window > and then display a second window. > In turn, the user can select an option to change back to the first > window and I want to destroy that window and then display the first > again. You probably don't want to destroy the windows but merely hide them. That way you can keep the state alive and its also less resource hungry and more performant. There should be hide and show (or draw/paint?) methods for Tkinter windows I believe. However, I will say that that style of GUI is very disconcerting to the user and goes against every published UI style guide I've ever seen. It's more normal to have a parent window and display dialogs. That way the basic window remains as a kind of terms of reference for the user. It will also play better with things like the Windows Task bar and MacOS Dock. You can then put the control logic in the parent window so that it knows which dialog is being displayed and can show the next one (and there could be many more than 2 to choose from!) depending on the return value from the active dialog. The window need not be big (eg xman) but it just provides a continuity of interface to the user. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jun 30 22:24:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jun 2008 21:24:36 +0100 Subject: [Tutor] list objects are unhashable References: <48692C28.2050804@khine.net> Message-ID: "Norman Khine" wrote > but when I run this, I get the following error on the line: > > if x and y and (x, y) in table: > > TypeError: list objects are unhashable Please post the entire error. The tiny bit you posted was not overly helpful, usually the stacjk trace contains the actual cause of the problem or a strong clue. However, in this case... > x = ['airlines-scheduled', 'airport-car-parking'] You cannot use a list to access a dictionary because dictionary keys must be immutable, and lists aren't. When you use the 'in' operation on a dictionary it basically searches the keys. > I am basically looping through files within each file, I have an > entity, for example: > > file1 > airlines-scheduled airport-car-parking > > file2 > airport-car-parking > > etc... > > So the above code counts all occurrences of 'airport-car-parking' > and sums it up. > > All works well if, I change the code to: > > for brain in brains: > x = getattr(brain, horizontal) > x = string.join(x, '' ) > y = getattr(brain, vertical) > y = string.join(y, '' ) > if x and y and (x, y) in table: > table[(x, y)] += 1 > table[(x, '')] += 1 > table[('', y)] += 1 > table[('', '')] += 1 > > So now my list becomes a string, which is not really good for me, as > this fails when there is more then one item. Use a tuple instead of a list. t = tuple(L) You can use a tuple as an index to a dictionary. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From norman at khine.net Mon Jun 30 22:41:02 2008 From: norman at khine.net (Norman Khine) Date: Mon, 30 Jun 2008 22:41:02 +0200 Subject: [Tutor] list objects are unhashable In-Reply-To: <200806302152.40199.omer@no-log.org> References: <48692C28.2050804@khine.net> <200806302109.28330.omer@no-log.org> <48693497.5090702@khine.net> <200806302152.40199.omer@no-log.org> Message-ID: <486944DE.1040703@khine.net> Hi, Sorry, but this did not work. I have done this, which returns the values I want (sort of) for brain in brains: x = getattr(brain, horizontal) if isinstance(x, list): for item in x: x = item else: x y = getattr(brain, vertical) if isinstance(y, list): for item in y: y = item else: y if x and y and (x, y) in table: table[(x, y)] += 1 table[(x, '')] += 1 table[('', y)] += 1 table[('', '')] += 1 The only think is that, the totals are correct, but when there is an item that is in both, it is counted only once. C?dric Lucantis wrote: > Le Monday 30 June 2008 21:31:35, vous avez ?crit : >> Thanks, >> but where do i replace the x with tuple(x) >> > > Whenever x is hashed, ie used as a key in a dictionary. You said you have: > >>>> table[(x, y)] += 1 >>>> where: >>>> >>>> x = ['airlines-scheduled', 'airport-car-parking'] > > so you should rather write this (if y is a list too): > > table[(tuple(x), tuple(y))] += 1 > > but of course you can also use tuples directly if your lists don't have to be > modified: > > x = ('airlines-scheduled', 'airport-car-parking') > y = (...) > table[(x, y)] += 1 > From rdm at rcblue.com Mon Jun 30 22:39:51 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 30 Jun 2008 13:39:51 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.co m> References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> <20080630021704.414791E4006@bag.python.org> <78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.com> Message-ID: <20080630204007.2F3CD1E400C@bag.python.org> An HTML attachment was scrubbed... URL: From rdm at rcblue.com Mon Jun 30 22:47:53 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 30 Jun 2008 13:47:53 -0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <20080630204007.2F3CD1E400C@bag.python.org> References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> <20080630021704.414791E4006@bag.python.org> <78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.com> <20080630204007.2F3CD1E400C@bag.python.org> Message-ID: <20080630204807.82D611E4009@bag.python.org> An HTML attachment was scrubbed... URL: From david at abbottdavid.com Mon Jun 30 22:54:33 2008 From: david at abbottdavid.com (David) Date: Mon, 30 Jun 2008 16:54:33 -0400 Subject: [Tutor] Deleting specified files using a python program...help with code?] Message-ID: <48694809.7000901@abbottdavid.com> I am learning python from books and this mailing list. I used the suggestions to come up with this; #!/usr/bin/python # Filename : new_remove-file.py import os import sys import glob dir_input = raw_input('Enter dir: ') win_trace = ['*.ini', '*.db'] files_removed = 0 for root, dirs, files in os.walk(dir_input): for trace in win_trace: win_trace_path = os.path.join(root, trace) for filename in glob.glob(win_trace_path): if os.path.exists(filename): print filename else: print 'No files found' confirmation = raw_input('Confirm removal: ') if confirmation == 'y': print "removing '%s'" % filename os.remove(filename) files_removed += 1 elif confirmation == 'n': pass else: sys.exit() if files_removed : print '%d files removed' % files_removed else : print 'No files found' Here is the output; david at opteron ~ $ ./new_remove_file.py Enter dir: test test/test.ini test/test.db Confirm removal: y removing 'test/test.db' 1 files removed Please point me in the direction as to why only one file is removed. thanks -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From malaclypse2 at gmail.com Mon Jun 30 22:59:53 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 30 Jun 2008 16:59:53 -0400 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <20080630204807.82D611E4009@bag.python.org> References: <20080628010246.9295E1E4003@bag.python.org> <5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com> <20080630021704.414791E4006@bag.python.org> <78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.com> <20080630204007.2F3CD1E400C@bag.python.org> <20080630204807.82D611E4009@bag.python.org> Message-ID: <16651e80806301359n2e7bfae6kd255e274b0228ea8@mail.gmail.com> On Mon, Jun 30, 2008 at 4:47 PM, Dick Moores wrote: > Show me a better way? You can do it with slice assignment too: >>> a = [1, 2, 3, 4] >>> a[1:3] = [[7, 8]] >>> a [1, [7, 8], 4] Now, which way is better? The answer depends on context. The best way to write it is in the manner that it makes the most sense to someone reading your program (including you, several years later)! If, conceptually, you are removing two elements from a list, then adding a new element which is itself a list, then doing it with remove and insert is probably best. On the other hand, if you are picking two elements out of the list (a slice) and replacing it with a new sublist, then the slice assignment may make more sense to the reader. -- Jerry From lie.1296 at gmail.com Mon Jun 30 23:33:42 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 01 Jul 2008 04:33:42 +0700 Subject: [Tutor] s[len(s):len(s)] = [x] ?? Message-ID: <1214861622.6453.20.camel@lieryan-laptop> ?> You can do it with slice assignment too: > >>> a = [1, 2, 3, 4] > >>> a[1:3] = [[7, 8]] > >>> a > [1, [7, 8], 4] > ? > Now, which way is better? The answer depends on context. The best > way to write it is in the manner that it makes the most sense to > someone reading your program (including you, several years later)! I think that the current behavior in python makes sense according to python's slicing model: which is cursor-like behavior. List slice (and indexing) in python is done on the model of a cursor: 0 1 2 3 +---+---+---+---+ | A | B | C | D | +---+---+---+---+ -4 -3 -2 -1 0 Cursor-like behavior of list in python is similar to the "typing cursor", if you, for example, highlights letter B and C (i.e. taking slice [1:3]) then pasted another string of letters, the result would be the pasted string replaced the highlighted object (i.e. the slice is gone and the inserted list become a sublist that replaced the sliced one). If the pasted list have been inserted instead, it wouldn't fit the cursor model. On an aside, I'm interested in seeing how this would be parsed by python l = [1, 2, 3, 4, 5, 6, 7, 8, 9] l[2:8:2] = [...] It turns out that assigning to extended slice notation require that you to have the same length sequence on both sides, just as expected, python doesn't do some voodoo magic for this since: "In the face of ambiguity, refuse the temptation to guess" and "There should be one -- and preferably only one -- obvious way to do it" [import this]. . From drumond.douglas at gmail.com Mon Jun 30 23:39:34 2008 From: drumond.douglas at gmail.com (Douglas Drumond) Date: Mon, 30 Jun 2008 18:39:34 -0300 Subject: [Tutor] s[len(s):len(s)] = [x] ?? In-Reply-To: <1214861622.6453.20.camel@lieryan-laptop> References: <1214861622.6453.20.camel@lieryan-laptop> Message-ID: <197391a30806301439x4e1a1f9fqc4fcea2aa14ec5ef@mail.gmail.com> Thanks, Ryan, for detailed explanation; I'm learning Python now, too, so I don't know exactly how stuff works. []'s Douglas On Mon, Jun 30, 2008 at 18:33, Lie Ryan wrote: >> You can do it with slice assignment too: >> >>> a = [1, 2, 3, 4] >> >>> a[1:3] = [[7, 8]] >> >>> a >> [1, [7, 8], 4] >> ? >> Now, which way is better? The answer depends on context. The best >> way to write it is in the manner that it makes the most sense to >> someone reading your program (including you, several years later)! > > I think that the current behavior in python makes sense according to > python's slicing model: which is cursor-like behavior. List slice (and > indexing) in python is done on the model of a cursor: > > 0 1 2 3 > +---+---+---+---+ > | A | B | C | D | > +---+---+---+---+ > -4 -3 -2 -1 0 > > Cursor-like behavior of list in python is similar to the "typing > cursor", if you, for example, highlights letter B and C (i.e. taking > slice [1:3]) then pasted another string of letters, the result would be > the pasted string replaced the highlighted object (i.e. the slice is > gone and the inserted list become a sublist that replaced the sliced > one). If the pasted list have been inserted instead, it wouldn't fit the > cursor model. > > On an aside, I'm interested in seeing how this would be parsed by python > l = [1, 2, 3, 4, 5, 6, 7, 8, 9] > l[2:8:2] = [...] > > It turns out that assigning to extended slice notation require that you > to have the same length sequence on both sides, just as expected, python > doesn't do some voodoo magic for this since: "In the face of ambiguity, > refuse the temptation to guess" and "There should be one -- and > preferably only one -- obvious way to do it" [import this]. > . > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor >