From rabidpoobear at gmail.com Mon Aug 1 00:04:53 2005 From: rabidpoobear at gmail.com (luke) Date: Sun, 31 Jul 2005 17:04:53 -0500 Subject: [Tutor] Help with file I/O. References: Message-ID: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> Nathan, I saw in your previous example that you called #quote file = raw_input("File name please: ") f = file(file, "r") for line in f.readlines(): print line f.close() #endquote the reason you were getting an error is that you made a variable named "file" on line one, which then overwrote the builtin method "file" in your namespace. therefore, the compiler throws a "string not callable error" because it's trying to call "File name please: "(file, "r") which of course doesn't work. What you want to do is make __sure__ that you never name a variable the same thing as a function unless you're sure that's what you want to do. I believe some poeple recommend that you use nouns for variables (because they're things) and verbs for functions (because it's an action) but in this case, just make sure not to use "file" or "open" or "str" or "int" or anything as variable names. as for your other question, > Okay I understand how to open and read to a file, but how do I write to a > file, e.g. a list. you should really read the tutorial and try to figure it out before asking us. I am going to give you the answer but don't keep reading if you want to figure it out yourself. def WriteToFile(listoflines,filename="default.txt"): f = file(filename, "w") f.writelines(listoflines) f.close() def main(args): text = ["hello\r\n","Good Morning nathan.\r\n"] filename = "" for arg in args: if arg == "-f" or arg == "--filename": grab_next_arg = 1 continue if grab_next_arg: filename = arg break if filename != "": WriteToFile(text,filename) else: WriteToFile(text) hope that helps. -Luke > ----- Original Message ----- > From: "Nathan Pinno" > To: "Nathan Pinno" ; "Danny Yoo" > > Cc: > Sent: Sunday, July 31, 2005 2:46 PM > Subject: Re: [Tutor] Help with file I/O. > > > > Here's the improved version. > > file = raw_input("File name please: ") > > f = open(file) > > for line in f.readlines(): > > print line > > f.close() > > > > ----- Original Message ----- > > From: "Nathan Pinno" > > To: "Danny Yoo" > > Cc: > > Sent: Sunday, July 31, 2005 2:29 PM > > Subject: Re: [Tutor] Help with file I/O. > > > > > >> Here's my work. I call it filewriter. > >> The code: > >> file = raw_input("File name please: ") > >> f = file(file, "r") > >> for line in f.readlines(): > >> print line > >> f.close() > >> > >> Will it do the trick? > >> > >> Nathan > >> ----- Original Message ----- > >> From: "Danny Yoo" > >> To: "Nathan Pinno" > >> Cc: > >> Sent: Sunday, July 31, 2005 12:22 AM > >> Subject: Re: [Tutor] Help with file I/O. > >> > >> > >>> > >>> > >>> On Sun, 31 Jul 2005, Nathan Pinno wrote: > >>> > >>>> Well, you saw my password program. That was my first attempt at using > >>>> file I/O. Thought I'd try it big time. You saw where that went. > >>> > >>> Ok, let's take a look. It was from this message, right? > >>> > >>> http://mail.python.org/pipermail/tutor/2005-July/039478.html > >>> > >>> That was such a while back that I think you probably learned a lot since > >>> then, and I think a few of the issues there were less about I/O and more > >>> about just general programming. > >>> > >>> Let's try a few things, just to see why you're getting stuck. Can you > >>> write a program that reads in a file, and just prints all of its lines > >>> out > >>> to screen? > >>> > >>> > >> _______________________________________________ > >> 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 alan.gauld at freenet.co.uk Mon Aug 1 00:07:01 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 31 Jul 2005 23:07:01 +0100 Subject: [Tutor] substitute function References: <20050731185857.84165.qmail@web53504.mail.yahoo.com> Message-ID: <02f501c5961c$2ddf3260$8eaa8651@xp> > Is there a 'substitute' function in python. Assuming we are dealing with strings then there are two. The string objects provide a replace() method and the regulatr expression module re provides substitute. > I want to substitute A with T and G with C and vice > versa > > A -> T > G -> C > T -> A > c -> G But the vice-versa creates an awkward sequencing problem. Whichever one you do first messes you up for the reverse mapping. Youi need to do multiple swaps at once. ISTR a module being highlighted in the Python challenge thing that was muxch discussed a few weeks ago that might help here, otherwise I'd create a map table and just brute force scan each character and replace where the character is in the table. --------- untested pseudo code -------- swaps = {'A':'T', 'G':'C',...} chars = list(longstring) for index in len(chars): if chars[index] in swaps: chars[index] = swaps[chars[index]] longstring = ''.join(chars) Not very fast but it would do it. If the strings are very long then I might try some clever regex stuff, or look up the old thread to find that clever module.. HTH, Alan G. From alan.gauld at freenet.co.uk Mon Aug 1 00:08:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 31 Jul 2005 23:08:24 +0100 Subject: [Tutor] substitute function References: <20050731185857.84165.qmail@web53504.mail.yahoo.com> <42ED2A79.5000806@tds.net> Message-ID: <02fb01c5961c$5f60fe90$8eaa8651@xp> >> Is there a 'substitute' function in python. > You can do this with the translate() method of a string. That was the clever stuff I was trying to remember, not a module after all, a method! Thanks Kent, Alan G. From alan.gauld at freenet.co.uk Mon Aug 1 00:11:57 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 31 Jul 2005 23:11:57 +0100 Subject: [Tutor] Help with file I/O. References: Message-ID: <030301c5961c$de699800$8eaa8651@xp> > file = raw_input("File name please: ") > f = file(file, "r") The problem is you used 'file' as a name. But file() is the function to open a file. So in the second line you call your filename as if it was a function! Try using 'filename' for your variable instead. It's never a good idea to use a python built-in name as a variable. You could just use open() instead of file() of course but thats probably not such a good solution! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Mon Aug 1 00:27:13 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 16:27:13 -0600 Subject: [Tutor] Thanks to all! References: Message-ID: The Giant Calculator is perfect also! ----- Original Message ----- From: Nathan Pinno To: tutor at python.org Sent: Sunday, July 31, 2005 3:34 PM Subject: [Tutor] Thanks to all! Thank you to all. All my calculators run perfect. I can now make a perfect Giant Calculator as well. Thanks again, Nathan ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050731/5c8df27b/attachment-0001.htm From python-tutor at toddmaynard.com Mon Aug 1 00:32:50 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Sun, 31 Jul 2005 18:32:50 -0400 Subject: [Tutor] Thanks to all! In-Reply-To: References: Message-ID: <200507311832.50393.python-tutor@toddmaynard.com> Congratulations! So what are you going to try next? --Todd On Sunday 31 July 2005 06:27 pm, Nathan Pinno wrote: > The Giant Calculator is perfect also! > ----- Original Message ----- > From: Nathan Pinno > To: tutor at python.org > Sent: Sunday, July 31, 2005 3:34 PM > Subject: [Tutor] Thanks to all! > > > Thank you to all. All my calculators run perfect. I can now make a > perfect Giant Calculator as well. > > Thanks again, > Nathan > > > --------------------------------------------------------------------------- >--- > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From falcon3166 at hotmail.com Mon Aug 1 00:36:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 16:36:36 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> Message-ID: I fixed it. Here is the latest code: filename = raw_input("File name please: ") f = file(filename, "r") for line in f.readlines(): print line f.close() Thanks for taking the time to explain the writing part, that was really baffling me. Now I'm first going to write the main part of a password program, then when that's solid, I'll add the file I/O. Maybe I'll try the exercise where I have to add file I/O to a grades program, in the Non-Programmer's Tutorial for Python. ----- Original Message ----- From: "luke" To: "Nathan Pinno" ; "Danny Yoo" Cc: Sent: Sunday, July 31, 2005 4:04 PM Subject: Re: [Tutor] Help with file I/O. > Nathan, > > I saw in your previous example that you called > #quote > file = raw_input("File name please: ") > f = file(file, "r") > for line in f.readlines(): > print line > f.close() > #endquote > > the reason you were getting an error is that > you made a variable named "file" on line one, > which then overwrote the builtin method > "file" in your namespace. > therefore, the compiler throws a > "string not callable error" > because it's trying to call "File name please: "(file, "r") > which of course doesn't work. > > What you want to do is make __sure__ > that you never name a variable the same thing as a function > unless you're sure that's what you want to do. > I believe some poeple recommend that you use > nouns for variables (because they're things) > and verbs for functions (because it's an action) > but in this case, > just make sure not to use "file" > or "open" or "str" or "int" or anything as variable names. > > as for your other question, > >> Okay I understand how to open and read to a file, but how do I write to a >> file, e.g. a list. > > you should really read the tutorial and try to figure it out before asking > us. > I am going to give you the answer but don't keep reading if you want to > figure it out yourself. > > def WriteToFile(listoflines,filename="default.txt"): > f = file(filename, "w") > f.writelines(listoflines) > f.close() > > def main(args): > text = ["hello\r\n","Good Morning nathan.\r\n"] > filename = "" > for arg in args: > if arg == "-f" or arg == "--filename": > grab_next_arg = 1 > continue > if grab_next_arg: > filename = arg > break > > if filename != "": > WriteToFile(text,filename) > else: > WriteToFile(text) > > hope that helps. > -Luke > >> ----- Original Message ----- >> From: "Nathan Pinno" >> To: "Nathan Pinno" ; "Danny Yoo" >> >> Cc: >> Sent: Sunday, July 31, 2005 2:46 PM >> Subject: Re: [Tutor] Help with file I/O. >> >> >> > Here's the improved version. >> > file = raw_input("File name please: ") >> > f = open(file) >> > for line in f.readlines(): >> > print line >> > f.close() >> > >> > ----- Original Message ----- >> > From: "Nathan Pinno" >> > To: "Danny Yoo" >> > Cc: >> > Sent: Sunday, July 31, 2005 2:29 PM >> > Subject: Re: [Tutor] Help with file I/O. >> > >> > >> >> Here's my work. I call it filewriter. >> >> The code: >> >> file = raw_input("File name please: ") >> >> f = file(file, "r") >> >> for line in f.readlines(): >> >> print line >> >> f.close() >> >> >> >> Will it do the trick? >> >> >> >> Nathan >> >> ----- Original Message ----- >> >> From: "Danny Yoo" >> >> To: "Nathan Pinno" >> >> Cc: >> >> Sent: Sunday, July 31, 2005 12:22 AM >> >> Subject: Re: [Tutor] Help with file I/O. >> >> >> >> >> >>> >> >>> >> >>> On Sun, 31 Jul 2005, Nathan Pinno wrote: >> >>> >> >>>> Well, you saw my password program. That was my first attempt at >> >>>> using >> >>>> file I/O. Thought I'd try it big time. You saw where that went. >> >>> >> >>> Ok, let's take a look. It was from this message, right? >> >>> >> >>> http://mail.python.org/pipermail/tutor/2005-July/039478.html >> >>> >> >>> That was such a while back that I think you probably learned a lot > since >> >>> then, and I think a few of the issues there were less about I/O and > more >> >>> about just general programming. >> >>> >> >>> Let's try a few things, just to see why you're getting stuck. Can >> >>> you >> >>> write a program that reads in a file, and just prints all of its >> >>> lines >> >>> out >> >>> to screen? >> >>> >> >>> >> >> _______________________________________________ >> >> 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 falcon3166 at hotmail.com Mon Aug 1 00:50:53 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 16:50:53 -0600 Subject: [Tutor] Thanks to all! References: <200507311832.50393.python-tutor@toddmaynard.com> Message-ID: I am going to try and tackle the file I/O exercise in Non-Programmers Tutorial For Python found at http://www.honors.montana.edu/~jjc/easytyt/easytut/easytut.html. Should be a fun task. ----- Original Message ----- From: To: Sent: Sunday, July 31, 2005 4:32 PM Subject: Re: [Tutor] Thanks to all! > > Congratulations! So what are you going to try next? > > --Todd > > On Sunday 31 July 2005 06:27 pm, Nathan Pinno wrote: >> The Giant Calculator is perfect also! >> ----- Original Message ----- >> From: Nathan Pinno >> To: tutor at python.org >> Sent: Sunday, July 31, 2005 3:34 PM >> Subject: [Tutor] Thanks to all! >> >> >> Thank you to all. All my calculators run perfect. I can now make a >> perfect Giant Calculator as well. >> >> Thanks again, >> Nathan >> >> >> --------------------------------------------------------------------------- >>--- >> >> >> _______________________________________________ >> 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 falcon3166 at hotmail.com Mon Aug 1 01:38:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 17:38:33 -0600 Subject: [Tutor] What's the invaild syntax? Error message and relative code supplied. Message-ID: What the invalid syntax? Here is the error message: SyntaxError: invalid syntax File "D:/Python22/grades.py", line 66 which = which-1 ^ SyntaxError: invalid syntax Here is the code: max_points = [25,25,50,25,100] assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] students = {'#Max':max_points} def print_menu(): print "1. Add student" print "2. Remove student" print "3. Print grades" print "4. Record grade" print "9. Exit" def print_all_grades(): print '\t', for i in range(len(assignments)): print assignments[1],'\t', print keys = students.keys() keys.sort() for x in keys: print x,'\t', grades = students[x] print_grades(grades) def print_grades(grades): for i in range(len(grades)): print grades[i],'\t\t', print def choice(): return int(raw_input("Menu Choice: ")) def school(): return raw_input("Student: ") while 1: print_menu() menu_choice = choice() if menu_choice == 1: print "Add student" name = school() students[name] = [0]*len(max_points) elif menu_choice == 2: print "Remove student" name = school() if students.has_key(name): del students[name] else: print "Student: ",name," not found." elif menu_choice == 3: print_all_grades() elif menu_choice == 4: print "Record Grade" name = school() if students.has_key(name): grades = students[name] print "Type in the number of the grade to record" print "Type in a 0 (zero) to exit" for i in range(len(assignments)): print i+1,' ',assignments[i],'\t', print print_grades(grades) which = 1234 while which != -1: which = int(raw_input("Change which Grade: ") which = which-1 if 0 <= which < len(grades): grade = int(raw_input("Grade: ") grades[which] = grade elif which != -1: print "Invalid Grade Number" else: print "Student not found" elif menu_choice == 9: break else: print "That's not a choice!" print "Goodbye." Thanks for the help in advance! Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050731/af137cd2/attachment.htm From alan.gauld at freenet.co.uk Mon Aug 1 01:45:23 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 00:45:23 +0100 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> Message-ID: <030701c59629$ebd35b90$8eaa8651@xp> > baffling me. Now I'm first going to write the main part of a > password You might find the getpass module useful for that... It provides a raw_input style prompt that doesn't display what the user types... HTH, Alan G. From jorge at bcs.org.uk Mon Aug 1 01:47:01 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Mon, 1 Aug 2005 00:47:01 +0100 Subject: [Tutor] single executable Message-ID: Hi all, I wrote a few small applications, couple hundred of lines each and one of them playing around with tkinter. Now py2exe leaves 10 or so files of all sorts and one executable to "distribute", and cx freeze isn't much better. Furthermore, my 15KB code becomes a whopping 8Meg distributable folder! Sure I can cut that in half by zipping but I still think that is an unappealing trade. Isn't it possible to create a single, reasonably sized, bundled windows executable? Python rocks regardless, and it's been a long time since I last felt like this for a programming language -I've been having a blast with Python in the past few weeks, and learning a lot from this very helpful mailing lists. chrs j. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/22c37bf2/attachment.htm From jorge at bcs.org.uk Mon Aug 1 01:47:07 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Mon, 1 Aug 2005 00:47:07 +0100 Subject: [Tutor] single executable Message-ID: Hi all, I wrote a few small applications, couple hundred of lines each and one of them playing around with tkinter. Now py2exe leaves 10 or so files of all sorts and one executable to "distribute", and cx freeze isn't much better. Furthermore, my 15KB code becomes a whopping 8Meg distributable folder! Sure I can cut that in half by zipping but I still think that is an unappealing trade. Isn't it possible to create a single, reasonably sized, bundled windows executable? Python rocks regardless, and it's been a long time since I last felt like this for a programming language -I've been having a blast with Python in the past few weeks, and learning a lot from this very helpful mailing lists. chrs j. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/0898e8eb/attachment.htm From rabidpoobear at gmail.com Mon Aug 1 01:50:46 2005 From: rabidpoobear at gmail.com (luke) Date: Sun, 31 Jul 2005 18:50:46 -0500 Subject: [Tutor] What's the invaild syntax? Error message and relative codesupplied. References: Message-ID: <002001c5962a$ac6bb5a0$aa0ca8c0@luke> NATHAN! you have had this exact same problem yesterday! cmon man. If you see an invalid syntax error, look on the preceeding line. it's usually caused by not enough parenthesis for your function call. so we scroll down to lines 64-66... > which = 1234 > while which != -1: > which = int(raw_input("Change which Grade: ") tada there's our error. you forgot an extra parenthesis. however many (( you have on a line you need ot have the same number of )) on the line. which = int(raw_input("Change which Grade: ") becomes which = int(raw_input("Change which Grade: ")) HTH, -Luke From python-tutor at toddmaynard.com Mon Aug 1 01:56:20 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Sun, 31 Jul 2005 19:56:20 -0400 Subject: [Tutor] What's the invaild syntax? Error message and relative code supplied. In-Reply-To: References: Message-ID: <200507311956.20712.python-tutor@toddmaynard.com> Remember this problem from yesterday? Take a look at the line before the one you are getting the error on. And count the ('s and the )'s. --Todd On Sunday 31 July 2005 07:38 pm, Nathan Pinno wrote: > What the invalid syntax? Here is the error message: > SyntaxError: invalid syntax > File "D:/Python22/grades.py", line 66 > which = which-1 > ^ > SyntaxError: invalid syntax > > Here is the code: > > max_points = [25,25,50,25,100] > assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] > students = {'#Max':max_points} > > def print_menu(): > print "1. Add student" > print "2. Remove student" > print "3. Print grades" > print "4. Record grade" > print "9. Exit" > > def print_all_grades(): > print '\t', > for i in range(len(assignments)): > print assignments[1],'\t', > print > keys = students.keys() > keys.sort() > for x in keys: > print x,'\t', > grades = students[x] > print_grades(grades) > > def print_grades(grades): > for i in range(len(grades)): > print grades[i],'\t\t', > print > > def choice(): > return int(raw_input("Menu Choice: ")) > > def school(): > return raw_input("Student: ") > > while 1: > print_menu() > menu_choice = choice() > if menu_choice == 1: > print "Add student" > name = school() > students[name] = [0]*len(max_points) > elif menu_choice == 2: > print "Remove student" > name = school() > if students.has_key(name): > del students[name] > else: > print "Student: ",name," not found." > elif menu_choice == 3: > print_all_grades() > > elif menu_choice == 4: > print "Record Grade" > name = school() > if students.has_key(name): > grades = students[name] > print "Type in the number of the grade to record" > print "Type in a 0 (zero) to exit" > for i in range(len(assignments)): > print i+1,' ',assignments[i],'\t', > print > print_grades(grades) > which = 1234 > while which != -1: > which = int(raw_input("Change which Grade: ") > which = which-1 > if 0 <= which < len(grades): > grade = int(raw_input("Grade: ") > grades[which] = grade > elif which != -1: > print "Invalid Grade Number" > else: > print "Student not found" > elif menu_choice == 9: > break > else: > print "That's not a choice!" > print "Goodbye." > > Thanks for the help in advance! > Nathan -------------- next part -------------- An embedded message was scrubbed... From: "Nathan Pinno" Subject: [Tutor] What's the invalid synax? Error message and code supplied. Date: Sat, 30 Jul 2005 16:19:30 -0600 Size: 9677 Url: http://mail.python.org/pipermail/tutor/attachments/20050731/c17ad132/attachment.eml From jfouhy at paradise.net.nz Mon Aug 1 01:55:05 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 01 Aug 2005 11:55:05 +1200 (NZST) Subject: [Tutor] single executable In-Reply-To: References: Message-ID: <1122854105.42ed64d927333@www.paradise.net.nz> Quoting Jorge Louis De Castro : > Hi all, > I wrote a few small applications, couple hundred of lines each and one > of them playing around with tkinter. Now py2exe leaves 10 or so files of > all sorts and one executable to "distribute", and cx freeze isn't much > better. Furthermore, my 15KB code becomes a whopping 8Meg distributable > folder! Sure I can cut that in half by zipping but I still think that is > an unappealing trade. > Isn't it possible to create a single, reasonably sized, bundled windows > executable? Remember that your 15KB code is pulling in all kinds of libraries --- this is why you can do so much with only a short script. If your program doesn't use Tkinter, you can shave a few megabytes off your distribution by removing the Tk DLLs. I think the py2exe wiki has more details here. Also, I have heard that the next version of py2exe will wrap everything up into a single executable. I don't know when it will be out, though. -- John. From falcon3166 at hotmail.com Mon Aug 1 02:04:08 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 18:04:08 -0600 Subject: [Tutor] What's the invaild syntax? Error message and relativecode supplied. References: <200507311956.20712.python-tutor@toddmaynard.com> Message-ID: Thanks Todd. Another one saved by you. ----- Original Message ----- From: To: Sent: Sunday, July 31, 2005 5:56 PM Subject: Re: [Tutor] What's the invaild syntax? Error message and relativecode supplied. > > Remember this problem from yesterday? > > Take a look at the line before the one you are getting the error on. > And count the ('s and the )'s. > > --Todd > > > > On Sunday 31 July 2005 07:38 pm, Nathan Pinno wrote: >> What the invalid syntax? Here is the error message: >> SyntaxError: invalid syntax >> File "D:/Python22/grades.py", line 66 >> which = which-1 >> ^ >> SyntaxError: invalid syntax >> >> Here is the code: >> >> max_points = [25,25,50,25,100] >> assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] >> students = {'#Max':max_points} >> >> def print_menu(): >> print "1. Add student" >> print "2. Remove student" >> print "3. Print grades" >> print "4. Record grade" >> print "9. Exit" >> >> def print_all_grades(): >> print '\t', >> for i in range(len(assignments)): >> print assignments[1],'\t', >> print >> keys = students.keys() >> keys.sort() >> for x in keys: >> print x,'\t', >> grades = students[x] >> print_grades(grades) >> >> def print_grades(grades): >> for i in range(len(grades)): >> print grades[i],'\t\t', >> print >> >> def choice(): >> return int(raw_input("Menu Choice: ")) >> >> def school(): >> return raw_input("Student: ") >> >> while 1: >> print_menu() >> menu_choice = choice() >> if menu_choice == 1: >> print "Add student" >> name = school() >> students[name] = [0]*len(max_points) >> elif menu_choice == 2: >> print "Remove student" >> name = school() >> if students.has_key(name): >> del students[name] >> else: >> print "Student: ",name," not found." >> elif menu_choice == 3: >> print_all_grades() >> >> elif menu_choice == 4: >> print "Record Grade" >> name = school() >> if students.has_key(name): >> grades = students[name] >> print "Type in the number of the grade to record" >> print "Type in a 0 (zero) to exit" >> for i in range(len(assignments)): >> print i+1,' ',assignments[i],'\t', >> print >> print_grades(grades) >> which = 1234 >> while which != -1: >> which = int(raw_input("Change which Grade: ") >> which = which-1 >> if 0 <= which < len(grades): >> grade = int(raw_input("Grade: ") >> grades[which] = grade >> elif which != -1: >> print "Invalid Grade Number" >> else: >> print "Student not found" >> elif menu_choice == 9: >> break >> else: >> print "That's not a choice!" >> print "Goodbye." >> >> Thanks for the help in advance! >> Nathan > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Mon Aug 1 02:04:45 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 18:04:45 -0600 Subject: [Tutor] What's the invaild syntax? Error message and relative codesupplied. References: <002001c5962a$ac6bb5a0$aa0ca8c0@luke> Message-ID: Thanks again Luke. ----- Original Message ----- From: "luke" To: "Nathan Pinno" ; Sent: Sunday, July 31, 2005 5:50 PM Subject: Re: [Tutor] What's the invaild syntax? Error message and relative codesupplied. > NATHAN! > you have had this exact same problem yesterday! > cmon man. > If you see an invalid syntax error, > look on the preceeding line. > it's usually caused by not enough parenthesis for your function call. > so we scroll down to lines 64-66... > >> which = 1234 >> while which != -1: >> which = int(raw_input("Change which Grade: ") > tada there's our error. > you forgot an extra parenthesis. > however many (( you have on a line you need ot have the same number of )) > on > the line. > which = int(raw_input("Change which Grade: ") > becomes > which = int(raw_input("Change which Grade: ")) > > HTH, > -Luke > > From falcon3166 at hotmail.com Mon Aug 1 02:05:41 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 18:05:41 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> Message-ID: Does it display stars instead? ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Alberto Troiano" ; "Danny Yoo" ; "luke" Cc: Sent: Sunday, July 31, 2005 5:45 PM Subject: Re: [Tutor] Help with file I/O. >> baffling me. Now I'm first going to write the main part of a password > > You might find the getpass module useful for that... > It provides a raw_input style prompt that doesn't > display what the user types... > > HTH, > > Alan G. > > From alan.gauld at freenet.co.uk Mon Aug 1 02:19:48 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 01:19:48 +0100 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> Message-ID: <033601c5962e$ba308090$8eaa8651@xp> >> You might find the getpass module useful for that... >> It provides a raw_input style prompt that doesn't >> display what the user types... > Does it display stars instead? No, its more secure than that, it doesn't display anything. But like anything in Python the esiest way to find out is just to try it at the >>> prompt. >>> import getpass >>> pw = getpass.getpass('Password: ') Password: >>> print pw mysecret >>> HTH Alan G From alan.gauld at freenet.co.uk Mon Aug 1 02:24:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 01:24:24 +0100 Subject: [Tutor] What's the invaild syntax? Error message and relative codesupplied. References: Message-ID: <035201c5962f$5f15a310$8eaa8651@xp> > What the invalid syntax? Here is the error message: > File "D:/Python22/grades.py", line 66 > which = which-1 > ^ >SyntaxError: invalid syntax OK, so it tells you the syntax is wrong and the line it detected the error. Try looking at a line or two before it. > while which != -1: > which = int(raw_input("Change which Grade: ") > which = which-1 Oh look, you've messed up the parens again, same as last time... Try checking your past mistakes Nathan, everyone tends to do the same things wrong over and over. For me its missing the colon at the end of an except statement... Alan G. From falcon3166 at hotmail.com Mon Aug 1 02:26:34 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 18:26:34 -0600 Subject: [Tutor] What's the invaild syntax? Error message and relative codesupplied. References: <035201c5962f$5f15a310$8eaa8651@xp> Message-ID: Hey, looks like this is my problem. ) I'll just have to be more careful in the future. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; Sent: Sunday, July 31, 2005 6:24 PM Subject: Re: [Tutor] What's the invaild syntax? Error message and relative codesupplied. >> What the invalid syntax? Here is the error message: >> File "D:/Python22/grades.py", line 66 >> which = which-1 >> ^ >>SyntaxError: invalid syntax > > OK, so it tells you the syntax is wrong and the line it detected the > error. Try looking at a line or two before it. > >> while which != -1: >> which = int(raw_input("Change which Grade: ") >> which = which-1 > > Oh look, you've messed up the parens again, same as last time... > > Try checking your past mistakes Nathan, everyone tends to do the same > things wrong over and over. For me its missing the colon at the end of an > except statement... > > Alan G. > From falcon3166 at hotmail.com Mon Aug 1 03:48:29 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 19:48:29 -0600 Subject: [Tutor] Is input a Python function or command? Message-ID: Is input a Python function or command? I need to know because I'm planning to use it as a variable, and don't want to get an error. Thanks, Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050731/06c5d21a/attachment.htm From falcon3166 at hotmail.com Mon Aug 1 04:05:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 31 Jul 2005 20:05:33 -0600 Subject: [Tutor] Is input a Python function or command? References: Message-ID: Thanks Luke. Saved me quite a headache. I will use in_file instead. Makes more sense anyway. ----- Original Message ----- From: "luke p" To: "Nathan Pinno" Sent: Sunday, July 31, 2005 7:59 PM Subject: Re: [Tutor] Is input a Python function or command? why do you want to use input as a variable? did you try testing it on the interactive prompt? >>> input (built-in function input) >>>hello = "test" >>>input() hello "test" so yep it's a builtin function. try to come up with more explanatory names. or just name all your variables "tmp" and "temp" and "x". or you can just overwrite the input function n the namespace. I'm sure some people would consider these approaches evil, however, so you probably shouldn't do it unless your code is for your use only. HTH, Luke On 7/31/05, Nathan Pinno wrote: > Is input a Python function or command? I need to know because I'm planning > to use it as a variable, and don't want to get an error. > > Thanks, > Nathan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From jobauk at hotmail.com Mon Aug 1 04:48:07 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Mon, 01 Aug 2005 02:48:07 +0000 Subject: [Tutor] single executable In-Reply-To: <1122854105.42ed64d927333@www.paradise.net.nz> Message-ID: Hi, Thanks for your reply. I have been googling this issue and found this article: http://starship.python.net/crew/theller/moin.cgi/SingleFileExecutable that seems to indicate what I want is possible and it is available. I downloaded NSIS and compiled (did not choose the option to create an installer) the .nsi script as prescribed on the article above. However, I do get errors because my resulting executable is not including the Tcl folders on the py2exe distribution folder (so the error msg goes). I've tried several combinations to make this work bu it always fails saying that it was unable to install Tcl. By looking at the NSIS logs I *think* this might have to do with the fact that the tcl/tkinter data is on separate folders under the py2exe dist folder. NSIS doesn't seem to be picking on those properly but I'm not sure (I don't see their content being listed on the script processing panel). If anyone has dealt with this before, help will be appreciated. The script I'm using follows, though is just a copy of the one on the article adjusted to my environment. chrs !define py2exeOutputDirectory 'dist' !define exe 'analyzer.exe' ; Comment out the "SetCompress Off" line and uncomment ; the next line to enable compression. Startup times ; will be a little slower but the executable will be ; quite a bit smaller ;SetCompress Off SetCompressor lzma Name 'Analyzer' OutFile ${exe} SilentInstall silent ;Icon 'icon.ico' Section InitPluginsDir SetOutPath '$PLUGINSDIR' File '${py2exeOutputDirectory}\*.*' GetTempFileName $0 DetailPrint $0 Delete $0 StrCpy $0 '$0.bat' FileOpen $1 $0 'w' FileWrite $1 '@echo off$\r$\n' StrCpy $2 $TEMP 2 FileWrite $1 '$2$\r$\n' FileWrite $1 'cd $PLUGINSDIR$\r$\n' FileWrite $1 '${exe}$\r$\n' FileClose $1 nsExec::Exec $0 Delete $0 SectionEnd >From: jfouhy at paradise.net.nz >To: "tutor at python.org" >Subject: Re: [Tutor] single executable >Date: Mon, 01 Aug 2005 11:55:05 +1200 (NZST) > >Quoting Jorge Louis De Castro : > > > Hi all, > > I wrote a few small applications, couple hundred of lines each and one > > of them playing around with tkinter. Now py2exe leaves 10 or so files of > > all sorts and one executable to "distribute", and cx freeze isn't much > > better. Furthermore, my 15KB code becomes a whopping 8Meg distributable > > folder! Sure I can cut that in half by zipping but I still think that is > > an unappealing trade. > > Isn't it possible to create a single, reasonably sized, bundled windows > > executable? > >Remember that your 15KB code is pulling in all kinds of libraries --- this >is >why you can do so much with only a short script. > >If your program doesn't use Tkinter, you can shave a few megabytes off your >distribution by removing the Tk DLLs. I think the py2exe wiki has more >details >here. > >Also, I have heard that the next version of py2exe will wrap everything up >into >a single executable. I don't know when it will be out, though. > >-- >John. From tegmine at gmail.com Mon Aug 1 08:35:28 2005 From: tegmine at gmail.com (Luis N) Date: Sun, 31 Jul 2005 23:35:28 -0700 Subject: [Tutor] single executable In-Reply-To: References: <1122854105.42ed64d927333@www.paradise.net.nz> Message-ID: <77bfa81a05073123353515a330@mail.gmail.com> On 7/31/05, Jorge Louis de Castro wrote: > > Hi, > > Thanks for your reply. I have been googling this issue and found this > article: > > http://starship.python.net/crew/theller/moin.cgi/SingleFileExecutable > > that seems to indicate what I want is possible and it is available. Hi, I looked at this, and took the time to try out the approach some time ago, you should be aware: The startup time of a wxPython app with lzma compression becomes very long (1+ minute) on a machinne with 64MB RAM and a Pentium 200MHz, but it's usable on faster machines that are common today ;-) The startup time is rather long, and this sould be considered as a serious drawback of this approach. Luis. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050731/1c655d03/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Aug 1 08:45:29 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 07:45:29 +0100 Subject: [Tutor] cant get started References: <142.4a63d61d.301ee131@aol.com> Message-ID: <039001c59664$9b39ce40$8eaa8651@xp> I'm cc'ing this back to the tutor list because others may spot things I miss. >K something must be wrong cause I typed python and it said "python is >not > defined" so any ideas That means one of two things. Eother python is not installed yet, or you have installed it but the path to Python is not set. Can you tell me how you installed Python? Specifically: 1) What operating system are you using? 2) Where did you download Python from? 3) What did you do with the downloaded file(es) to install them. Once we know that we can take it from there... Alan G. From alan.gauld at freenet.co.uk Mon Aug 1 08:55:02 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 07:55:02 +0100 Subject: [Tutor] Is input a Python function or command? References: Message-ID: <03b301c59665$f0cc6ec0$8eaa8651@xp> > Is input a Python function or command? Its a function. You can tell because you need to use parens. print, by contrast, is a command and doesn't need parens... > I need to know because I'm planning to use it as > a variable, and don't want to get an error. Even if you don't want to use input() in your code masking it with a variable name is still a bad idea. Why? Because anyone else reading your code who sees 'input' will automatically tend to assume the builtin name not your variable. Its much better to use safe variable names. A Thesaurus can help here, for example the online one at: http://thesaurus.reference.com Which suggests these as alternatives to input: abstracts, brass tacks, circumstances, compilations, conclusions, details, documents, dope, dossier, evidence, experiments, facts, figures, goods, info, input, knowledge, materials, measurements, memorandums, notes, picture, poop, poop sheet, proof, reports, results, scoop, score, statistics, testimony, whole story Also some abbreviation skills can be used, for example: iput, ipt, in. Finally augmenting the name with some context information will help, such as file_input, numeric_input, menu_input etc... Personally I prefer the first and last techniques, abbreviations can become obscure very quickly. HTH, Alan G. From alan.gauld at freenet.co.uk Mon Aug 1 09:05:31 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 08:05:31 +0100 Subject: [Tutor] single executable References: Message-ID: <03c501c59667$683d68a0$8eaa8651@xp> > http://starship.python.net/crew/theller/moin.cgi/SingleFileExecutable > > that seems to indicate what I want is possible and it is available. While it is possible to build single exe programs its questionable whether the effort involved is worthwhile. Only the very smallest programs can ever be built that way because any significant application needs support files - config and data files etc. Many applications actually have multiple executables(client/server apps for example) None of these can be bundled as a single file exe. They must be packaged with an installer. There are also significant snags with single exes. For example if you (or even seveal other folks) distribute many such Python programs you are installing puthon multiple times on the users computers. There will also be duplication of wxPython if you use that, Tcl DLLs if you use Tkinter etc etc. Now disk space is cheap so thats not a huge issue but these big combined files are also slow to start and tend to consume lots of memory when running. Thats why most commercial apps come as an exe and lots of DLLs (several hundred for MS Word!), its much more efficient to run. So although a single exe seems like a good idea its worth remembering that there is a downside too. Alan G From falcon3166 at hotmail.com Mon Aug 1 08:25:45 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 00:25:45 -0600 Subject: [Tutor] Is input a Python function or command? References: Message-ID: Just remembered that input is for integers! Oops! Shouldn't have asked! And in_file makes more sense because I'm loading a file with it. ----- Original Message ----- From: "Nathan Pinno" To: "Luke P" Cc: "Tutor mailing list" Sent: Sunday, July 31, 2005 8:05 PM Subject: Re: [Tutor] Is input a Python function or command? > Thanks Luke. Saved me quite a headache. I will use in_file instead. Makes > more sense anyway. > ----- Original Message ----- > From: "luke p" > To: "Nathan Pinno" > Sent: Sunday, July 31, 2005 7:59 PM > Subject: Re: [Tutor] Is input a Python function or command? > > > why do you want to use input as a variable? > > did you try testing it on the interactive prompt? >>>> input > (built-in function input) >>>>hello = "test" >>>>input() > hello > "test" > > so yep it's a builtin function. > > try to come up with more explanatory names. > or just name all your variables "tmp" and "temp" and "x". > > or you can just overwrite the input function n the namespace. > > I'm sure some people would consider these approaches evil, however, so > you probably shouldn't do it unless your code is for your use only. > > HTH, > Luke > > > On 7/31/05, Nathan Pinno wrote: >> Is input a Python function or command? I need to know because I'm >> planning >> to use it as a variable, and don't want to get an error. >> >> Thanks, >> Nathan >> _______________________________________________ >> 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 matthew.williams at cancer.org.uk Mon Aug 1 09:46:18 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon, 01 Aug 2005 08:46:18 +0100 Subject: [Tutor] Python FTP GUI - Possible project ? Message-ID: <1122882378.4337.2.camel@localhost.localdomain> Dear List, Does anyone know of a Python FTP GUI tool ? Preferably based around pyGTK+ ? I've had a look (Google, vaults of Parnassus, etc.) but haven't found one. If there isn't one, then would people consider it a useful project for newbie programmers (like myself). There have often been questions along the lines of "Where can I find projects to get involved in", and I thought this might help. Thanks, Matt From cyresse at gmail.com Mon Aug 1 10:24:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 1 Aug 2005 20:24:37 +1200 Subject: [Tutor] Python FTP GUI - Possible project ? In-Reply-To: <1122882378.4337.2.camel@localhost.localdomain> References: <1122882378.4337.2.camel@localhost.localdomain> Message-ID: Hi Matt, If you're au fait with pyGTK+, that combined with the ftplib module syou should be able to build a decent GUI based FTP programme somewhat easily, although I can guarantee that if you don't know pyGTK+ too well, you'll end up having several screen-smashing moments, followed by a zen like realisation or two... Shouldn't be overly hard, not that I'm familiar with pyGTK+. I would recommend learning ftplib thoroughly, and perhaps go through a free FTP client and log what it does, so you can replicate the behaviour in your programme. Some FTP programmes automatically request directory listings, some don't, etc. etc. One of my first projects with a GUI involved using the IMAP email protocol, good stuff to play with. Regards, Liam Clarke On 8/1/05, Matt Williams wrote: > > Dear List, > > Does anyone know of a Python FTP GUI tool ? Preferably based around > pyGTK+ ? > > I've had a look (Google, vaults of Parnassus, etc.) but haven't found > one. > > If there isn't one, then would people consider it a useful project for > newbie programmers (like myself). There have often been questions along > the lines of "Where can I find projects to get involved in", and I > thought this might help. > > Thanks, > > Matt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/bc764687/attachment.htm From kristian at zimmer428.net Mon Aug 1 10:28:25 2005 From: kristian at zimmer428.net (Kristian Rink) Date: Mon, 01 Aug 2005 10:28:25 +0200 Subject: [Tutor] Python FTP GUI - Possible project ? In-Reply-To: <1122882378.4337.2.camel@localhost.localdomain> References: <1122882378.4337.2.camel@localhost.localdomain> Message-ID: <42EDDD29.3000002@zimmer428.net> Matt Williams schrieb: > Dear List, > > Does anyone know of a Python FTP GUI tool ? Preferably based around > pyGTK+ ? Though just loosely related to the original post, if you're not completely familiar with pyGTK+, you might want to think about using pythoncard as GUI framework instead. IIRC it is built around wxwidgets (which itself uses GTK+ atop X11), so it should seamlessly integrate in any GTK+ environment, but it is amazingly easy to get started with. Cheers, Kris -- Kristian Rink * http://www.fotolog.net/kawazu * http://zimmer428.net icq: 48874445 * jab: kawazu at jabber.ccc.de * fon: ++49 176 2447 2771 "Sei Du selbst die Ver?nderung, die Du in der Welt w?nschst." (Gandhi) From cyresse at gmail.com Mon Aug 1 10:32:29 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 1 Aug 2005 20:32:29 +1200 Subject: [Tutor] Python FTP GUI - Possible project ? In-Reply-To: <42EDDD29.3000002@zimmer428.net> References: <1122882378.4337.2.camel@localhost.localdomain> <42EDDD29.3000002@zimmer428.net> Message-ID: May I second the vote for Pythoncard. Although I'm not sure how easily you could represent directories... On 8/1/05, Kristian Rink wrote: > > Matt Williams schrieb: > > Dear List, > > > > Does anyone know of a Python FTP GUI tool ? Preferably based around > > pyGTK+ ? > > Though just loosely related to the original post, if you're not > completely familiar with pyGTK+, you might want to think about using > pythoncard as GUI framework instead. IIRC it is built around wxwidgets > (which itself uses GTK+ atop X11), so it should seamlessly integrate in > any GTK+ environment, but it is amazingly easy to get started with. > > Cheers, > Kris > > -- > Kristian Rink * http://www.fotolog.net/kawazu * http://zimmer428.net > icq: 48874445 * jab: kawazu at jabber.ccc.de * fon: ++49 176 2447 2771 > "Sei Du selbst die Ver?nderung, die Du in der Welt w?nschst." (Gandhi) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/2d1ae9a5/attachment.htm From jorge at bcs.org.uk Mon Aug 1 13:17:12 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Mon, 1 Aug 2005 12:17:12 +0100 Subject: [Tutor] Send attachment References: Message-ID: Thanks for the reply I did try your approach at first but then, Martin Walsh on this mailing list hinted at something way simpler and elegant, a solution that actually adjusts itself to the default mail client of the user. It consists of creating an .eml file with all the blurb that goes with it (save an email message as a draft and open it to see what needs to go there). Then it is a simple matter of calling os.startfile() and the OS will open the file with whatever program is associated with those extensions, typically the default mail client. > import os > os.startfile('foo.eml') I think it's neat, it does what I want in an elegant way, and it keeps me from mixing languages and all that jazz. chrs j. ----- Original Message ----- From: Liam Clarke To: Jorge Louis De Castro Cc: tutor at python.org Sent: Friday, July 22, 2005 12:45 AM Subject: Re: [Tutor] Send attachment If it's Outlook, you can use the win32python library to control it via ActiveX/COM+ http://starship.python.net/crew/mhammond/ Here's an example using VB to control Outlook - http://support.microsoft.com/?kbid=220595 The language differs, but the basic principle remains the same. Create an Application.Outlook object, and then use it's methods. I know there's a way to use the default mail client ( as in Excel VBA's - application.showdialog(xlDialogs.SendMail) ) but blowed if I can figure it out. The above VBA bit automatically attaches the open spreadsheet, so unsure if you can hijack it. Good luck, and if you google how to use the default email client, let me know! Liam Clarke On 7/22/05, Jorge Louis De Castro wrote: Hello, Any ideas how I can use Python and the Windows API to open a PC's mail client and send an attachment? The idea is saving some data onto a file and then invoke the email client (OE or Outlook or whatever is the default on the machine) with the recipient's address filled in and the file ready to be sent as an attachment. Kinda like when we right-click on a file and select the "send to mail recipient" behavior. Been reading docs, trying out samples, and googling this for a few days to no avail. Cheers jorge _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/734bea4e/attachment.htm From andreas at kostyrka.org Mon Aug 1 13:39:40 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 01 Aug 2005 13:39:40 +0200 Subject: [Tutor] Python FTP GUI - Possible project ? In-Reply-To: References: <1122882378.4337.2.camel@localhost.localdomain> Message-ID: <1122896381.5051.21.camel@andi-lap> Am Montag, den 01.08.2005, 20:24 +1200 schrieb Liam Clarke: > Hi Matt, > > If you're au fait with pyGTK+, that combined with the ftplib module > syou should be able to build a decent GUI based FTP programme somewhat > easily, although I can guarantee that if you don't know pyGTK+ too > well, you'll end up having several screen-smashing moments, followed > by a zen like realisation or two... > > Shouldn't be overly hard, not that I'm familiar with pyGTK+. I would > recommend learning ftplib thoroughly, and perhaps go through a free > FTP client and log what it does, so you can replicate the behaviour in Well, for a really useful client, he should probably consider either PyCurl or Twisted. Or be ready to do some thread hacking ;) Andreas > your programme. Some FTP programmes automatically request directory > listings, some don't, etc. etc. > > One of my first projects with a GUI involved using the IMAP email > protocol, good stuff to play with. > > Regards, > > Liam Clarke > > On 8/1/05, Matt Williams wrote: > Dear List, > > Does anyone know of a Python FTP GUI tool ? Preferably based > around > pyGTK+ ? > > I've had a look (Google, vaults of Parnassus, etc.) but > haven't found > one. > > If there isn't one, then would people consider it a useful > project for > newbie programmers (like myself). There have often been > questions along > the lines of "Where can I find projects to get involved in", > and I > thought this might help. > > Thanks, > > Matt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- > 'There is only one basic human right, and that is to do as you damn > well please. > And with it comes the only basic human duty, to take the > consequences.' > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20050801/f08b85c7/attachment.pgp From kent37 at tds.net Mon Aug 1 14:49:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Aug 2005 08:49:13 -0400 Subject: [Tutor] Python FTP GUI - Possible project ? In-Reply-To: <1122882378.4337.2.camel@localhost.localdomain> References: <1122882378.4337.2.camel@localhost.localdomain> Message-ID: <42EE1A49.90701@tds.net> Matt Williams wrote: > Dear List, > > Does anyone know of a Python FTP GUI tool ? Preferably based around > pyGTK+ ? > > I've had a look (Google, vaults of Parnassus, etc.) but haven't found > one. Googling 'python ftp client' gives http://ftpcube.sourceforge.net/ as well as several resources that might be useful if you decide to write your own. Kent From adam.jtm30 at gmail.com Mon Aug 1 17:04:59 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 1 Aug 2005 16:04:59 +0100 Subject: [Tutor] Socket Programming In-Reply-To: <42ED3C3D.5060200@gmail.com> References: <42ED3C3D.5060200@gmail.com> Message-ID: You have to put in how many bytes of data you want to recieve in clientsocket.recv() eg. clientsocket.recv(1024) for 1kB. On 7/31/05, Joseph Quigley wrote: > > Hi Dan, > > Danny Yoo wrote: > > >###### > >clientsocket.recv() > >###### > > > >should work better. > > > > > Ok well I tried your examples but they didn't work. I still get: > TypeError: recv() takes at least 1 argument (0 given) > > How can I fix this? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/cc3541ec/attachment.htm From cpu.crazy at gmail.com Mon Aug 1 16:25:00 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 01 Aug 2005 08:25:00 -0600 Subject: [Tutor] Re; Socket Programming In-Reply-To: References: Message-ID: <42EE30BC.1050504@gmail.com> Hi Kent, I have Python in a nutshell but I haven't read much. Thanks for tellling me. From cpu.crazy at gmail.com Mon Aug 1 16:59:40 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 01 Aug 2005 08:59:40 -0600 Subject: [Tutor] Socket Programming In-Reply-To: <1122887659.4621.24.camel@KMA.accesstel> References: <42EC4896.2050403@gmail.com> <1122887659.4621.24.camel@KMA.accesstel> Message-ID: <42EE38DC.1080601@gmail.com> Hi Johan, Johan Geldenhuys wrote: > I have more advanced examples if you want them, but start here and > look at the socket lib and you can start using select if you want to > wait for stuff from the server or client. > > Johan I'd love to see your examples. Could you send them directly to me as an attachment? I've got a question... how can I add more clients? I'm trying to make a type of bot. Thanks for your help. Your example worked perfectly! Joe From wpmxy at sbcglobal.net Mon Aug 1 17:46:41 2005 From: wpmxy at sbcglobal.net (Xiangyi Meng) Date: Mon, 1 Aug 2005 08:46:41 -0700 (PDT) Subject: [Tutor] question on numarray across platforms Message-ID: <20050801154641.10114.qmail@web80709.mail.yahoo.com> Hi there, I ran across this error when running a few lines of code in debian python, but this runs perfectly in windows python. Basically I created a dummy matrix called "gamma" (using kroneckerproduct in numarray) and printed out its mean. Here is the code: gamma = kroneckerproduct(ones((N, 1)),identity(T)) print gamma.mean() and Here is the error message: Traceback (most recent call last): File "vul_prov.py", line 149, in ? VLs = mv_prov(hhc, idyrisk, provid, 1) File "/home/meng/China/Extent/Data/Urban2002/Empirics/tmp/vulnerability.py", line 605, in mv_prov print gamma.mean() File "/usr/lib/python2.4/site-packages/numarray/numarraycore.py", line 1137, in mean return self.sum()/(self.nelements()*1.0) File "/usr/lib/python2.4/site-packages/numarray/numarraycore.py", line 1133, in sum return ufunc.add.reduce(ufunc.add.areduce(self, type=type).flat, type=type) IndexError: too many indices. Thank you for helping on this! Oh, btw, the version for python in both platforms is 2.4.1 Xiangyi From m.moghimi at gmail.com Mon Aug 1 17:57:49 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Mon, 1 Aug 2005 20:27:49 +0430 Subject: [Tutor] mailman Message-ID: I want to install mailman. when I try to configure it I got this error message: checking for --with-python... no checking for python... /usr/bin/python checking Python interpreter... /usr/bin/python checking Python version... 2.4 checking that Python has a working distutils... configure: error: ***** Distutils is not available or is incomplete for /usr/bin/python ***** If you installed Python from RPM (or other package manager) ***** be sure to install the -devel package, or install Python ***** from source. See README.LINUX for details I downloaded Distutil from python.org http://www.python.org/sigs/distutils-sig/download/Distutils-1.0.2.tar.gz I wanted to install this one but I got another error message in running python setup.py install Traceback (most recent call last): File "setup.py", line 30, in ? packages = ['distutils', 'distutils.command'], File "/home/soccer/mohammad/python/Distutils-1.0.2/distutils/core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "/home/soccer/mohammad/python/Distutils-1.0.2/distutils/dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' How can I solve this problem?! -- Mohammad do you Python?!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/b3fc3863/attachment.htm From genietdev0 at iol.ie Mon Aug 1 18:41:12 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Mon, 01 Aug 2005 17:41:12 +0100 Subject: [Tutor] visibility of variables Message-ID: <42EE50A8.3030803@iol.ie> Hello all of you, I have problems with the visibility of variables in python. I am used to the idea of Javascript and other languages where one can define global variables if they are defined outside a function. It seems Python is not doing that, but how can I make it work? I think it needs some twist in my mind to get used to it, but I still don't grasp it. Can you help? I have attached a program that is not functioning as I would like to have it functioning. It seems that the 'gementenkleur' in funct1 and funct2 are the value of gemetenkleur at the start of the program, but they don't chance after the definition of gemetenkleur=bmifrao1.bmp I 'know' this is something particular to Python, by how can I work around this? I could add gemetenkleur in the argument list of the funct1 and funct2 functions, but in my case I don't want this (funct1 will be a function to be used in scipy.fmin, and I have the idea that only the simplex can be as an argument). Is there a good page on the web that described this visibility issue (or does it have a different name?) of Python? The delveintopython.pdf does not help me and also a tutorial of hetland.org (Instant python: instant-python.php.htm ) seems not to speak the right language for me;-). Hope someone can help me. I have the idea this is essential to understand before continuing more in Python. All the best, Victor -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: visibility.py Url: http://mail.python.org/pipermail/tutor/attachments/20050801/480fbe19/visibility.diff From kent37 at tds.net Mon Aug 1 18:53:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Aug 2005 12:53:35 -0400 Subject: [Tutor] visibility of variables In-Reply-To: <42EE50A8.3030803@iol.ie> References: <42EE50A8.3030803@iol.ie> Message-ID: <42EE538F.7030707@tds.net> Victor Reijs wrote: > Hello all of you, > > I have problems with the visibility of variables in python. I am > used to the idea of Javascript and other languages where one can define > global variables if they are defined outside a function. It seems Python > is not doing that, but how can I make it work? > > I think it needs some twist in my mind to get used to it, but I still > don't grasp it. Can you help? In function Do() you must add the declaration global gemetenkleur See http://www.python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function and the entry that follows it for some explanation. Kent > > I have attached a program that is not functioning as I would like to > have it functioning. > It seems that the 'gementenkleur' in funct1 and funct2 are the value of > gemetenkleur at the start of the program, but they don't chance after > the definition of gemetenkleur=bmifrao1.bmp > > I 'know' this is something particular to Python, by how can I work > around this? I could add gemetenkleur in the argument list of the funct1 > and funct2 functions, but in my case I don't want this (funct1 will be a > function to be used in scipy.fmin, and I have the idea that only the > simplex can be as an argument). > > Is there a good page on the web that described this visibility issue (or > does it have a different name?) of Python? The delveintopython.pdf does > not help me and also a tutorial of hetland.org (Instant python: > instant-python.php.htm ) seems not to speak the right language for me;-). > > Hope someone can help me. I have the idea this is essential to > understand before continuing more in Python. > > > All the best, > > > Victor > > > > > > > > ------------------------------------------------------------------------ > > bmifrao1bmp=[(41, 37, 33), (63, 56, 53), (107, 97, 92), (228, 226, 222), (81, 64, 107), (107, 131, 82), (236, 207, 71), (158, 58, 42)] > print 'original bmifrao1bmp ',bmifrao1bmp > #gemetenkleur=[(41, 37, 33), (63, 56, 53), (107, 97, 92), (228, 226, 222), (81, 64, 107), (107, 131, 82), (236, 207, 71), (158, 58, 42)] > gemetenkleur=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]] > endkleur=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]] > > > def funct1(): > print 'gemetenkleur in func1: ',gemetenkleur > a=funct2(gemetenkleur) > > def funct2(kleuren): > print 'kleuren in funct2 (should be same as gemetenkleur): ',kleuren > return 1 > > def Do(): > gemetenkleur=bmifrao1bmp[:] > print 'gemetenkleur has to be from now bmifrao1bmp: ',gemetenkleur > funct1() > > Do() > > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From genietdev0 at iol.ie Mon Aug 1 18:58:13 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Mon, 01 Aug 2005 17:58:13 +0100 Subject: [Tutor] visibility of variables In-Reply-To: <42EE538F.7030707@tds.net> References: <42EE50A8.3030803@iol.ie> <42EE538F.7030707@tds.net> Message-ID: <42EE54A5.8030505@iol.ie> THANKS Kent. It seems I used the wrong keywords to find answer to my question. This page is very very helpfull! I now works indeed. THANKS for your fast help. All the best, Victor Kent Johnson wrote: >>I have problems with the visibility of variables in python. I am >>used to the idea of Javascript and other languages where one can define >>global variables if they are defined outside a function. It seems Python >>is not doing that, but how can I make it work? >> >>I think it needs some twist in my mind to get used to it, but I still >>don't grasp it. Can you help? > > In function Do() you must add the declaration > global gemetenkleur > > See http://www.python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function and the entry that follows it for some explanation. From gtsang at lnxw.com Mon Aug 1 19:42:08 2005 From: gtsang at lnxw.com (Gilbert Tsang) Date: Mon, 01 Aug 2005 10:42:08 -0700 Subject: [Tutor] question on string In-Reply-To: <20050718165526.GC32754@alexis.mi.celestial.com> References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> Message-ID: <42EE5EF0.5060409@lynuxworks.com> Hi there, I would like to construct some string objects using the cprintf-style format: command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) Of course it is illegal in python but I couldn't figure out a way to construct strings with that kind of formatting and substitution. I have been looking and couldn't discover string constructor such as command_string = string( "diff -u %s %s > %s.patch" % ( src, dst, file ) ) From the documentation on docs.python.org, the closest is string Template (but my python installation doesn't come with this module). Any insights on initializing string in this manner? Thanks, Gilbert. From kent37 at tds.net Mon Aug 1 20:06:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Aug 2005 14:06:00 -0400 Subject: [Tutor] question on string In-Reply-To: <42EE5EF0.5060409@lynuxworks.com> References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> <42EE5EF0.5060409@lynuxworks.com> Message-ID: <42EE6488.5050905@tds.net> Gilbert Tsang wrote: > Hi there, > > I would like to construct some string objects using the cprintf-style > format: > > command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) > > Of course it is illegal in python but I couldn't figure out a way to > construct strings with that kind of formatting and substitution. Actually that is correct as written! (though 'file' is a poor choice of variable name as it shadows the built-in file() function...) >>> src = 'mySource' >>> dst = 'myNewSource' >>> file = 'diff.out' >>> command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) >>> command_string 'diff -u mySource myNewSource > diff.out.patch' See http://docs.python.org/lib/typesseq-strings.html for details on string formatting. Kent From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 20:21:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 11:21:23 -0700 (PDT) Subject: [Tutor] Is input a Python function or command? In-Reply-To: Message-ID: > Thanks Luke. Saved me quite a headache. I will use in_file instead. > Makes more sense anyway. Hi Nathan, Just wanted to chime in here: you may have fewer issues with name conflicts if you use more functions. For example: ###### >>> def test(): ... input = 42 ... print input ... >>> test() 42 >>> input ###### What this tries to so is that functions offer a little bit of isolation: within a function, you can usually just use names with abandon, because it won't affect the outside world. We'd say here that test() uses 'input' as a "local" variable. Of course, if we try to do something like: ###### >>> def test(): ... input = 42 ... s = input("hi, what's your age? ") ... >>> test() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in test TypeError: 'int' object is not callable ###### we should expect to see trouble within the function, since we've overwritten 'input'. However, outside the function, we're still good: ###### >>> input("hello: ") hello: 42 42 ###### So that's one benefit of doing work in functions: we can box things in so that, if we make a mistake, our mistake is isolated to the function, and not to the outside world. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 20:22:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 11:22:52 -0700 (PDT) Subject: [Tutor] cant get started In-Reply-To: <039001c59664$9b39ce40$8eaa8651@xp> Message-ID: On Mon, 1 Aug 2005, Alan G wrote: > I'm cc'ing this back to the tutor list because others may spot things > I miss. > > >K something must be wrong cause I typed python and it said "python is > >not > > defined" so any ideas Hi Alan, Are you sure that F22AceRaptor isn't trying to type 'python' at the interactive interpreter? ###### >>> python Traceback (most recent call last): File "", line 1, in ? NameError: name 'python' is not defined ###### I think that F22AceRaptor is already in Python and may simply not realise it. *grin* From zamb at saudi.net.sa Mon Aug 1 20:39:45 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Mon, 01 Aug 2005 21:39:45 +0300 Subject: [Tutor] question on string In-Reply-To: <42EE5EF0.5060409@lynuxworks.com> References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> <42EE5EF0.5060409@lynuxworks.com> Message-ID: <1122921585.16017.5.camel@localhost.localdomain> On Mon, 2005-08-01 at 10:42 -0700, Gilbert Tsang wrote: > Hi there, > > I would like to construct some string objects using the cprintf-style > format: > > command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) > > Of course it is illegal in python but I couldn't figure out a way to > construct strings with that kind of formatting and substitution. > > I have been looking and couldn't discover string constructor such as > > command_string = string( "diff -u %s %s > %s.patch" % ( src, dst, file ) ) > > From the documentation on docs.python.org, the closest is string > Template (but my python installation doesn't come with this module). Any > insights on initializing string in this manner? > > > Thanks, Gilbert. "file" is a reserved word! This is why it's not working for you! Change "file" to something else, like "result" for example. Here: >>> src = 'file1.c' >>> dst = 'file2.c' >>> result = "result" >>> command_string = "diff -u %s %s > %s.patch" % (src, dst, result) >>> command_string 'diff -u file1.c file2.c > result.patch' Is this what you want? Ziyad. From cpu.crazy at gmail.com Mon Aug 1 17:41:42 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 01 Aug 2005 09:41:42 -0600 Subject: [Tutor] Socket Programming In-Reply-To: References: <42ED3C3D.5060200@gmail.com> Message-ID: <42EE42B6.7010604@gmail.com> Hi, Ok. But what if I wanted to send a 1 mb message? Could I leave .recv(10000) in and send 'Hi!' as well or would I have to change it? Thanks, JQ Adam Bark wrote: > You have to put in how many bytes of data you want to recieve in > clientsocket.recv() eg. clientsocket.recv(1024) for 1kB. From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 21:32:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 12:32:57 -0700 (PDT) Subject: [Tutor] question on numarray across platforms In-Reply-To: <20050801154641.10114.qmail@web80709.mail.yahoo.com> Message-ID: On Mon, 1 Aug 2005, Xiangyi Meng wrote: > > I ran across this error when running a few lines of code in debian > python, but this runs perfectly in windows python. Hi Xiangyi, This seems a bit specific to numarray; you may want to ask the Numeric discussion group: http://sourceforge.net/mailarchive/forum.php?forum_id=4890 Offhand, I can't see anything wrong here, and it sounds bizarre that you're getting different results between Windows and Debian Linux --- that sounds like a severe bug. When you ask the Numeric discussion group, also show what the numarray.__version__ variable looks like. For reference, here's the version of numarray on my system: ###### >>> import numarray >>> numarray.__version__ '1.3.1' ###### Do this for both your Windows environment and your Debian Linux environment, and make sure you get the same version number. If the version numbers differ, then that may explain why you're getting different results from your program. Good luck to you! From sunny.tired at gmail.com Mon Aug 1 21:35:52 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Mon, 1 Aug 2005 15:35:52 -0400 Subject: [Tutor] Color text in Text widget Message-ID: <8171b61605080112356c1264ab@mail.gmail.com> Hi all, How do I add color to the text in the Text widget? I tried using the ASCII sequence but it didnt work. For example, I want to add: This is red , but this is blue Thanks. Santosh. From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 21:36:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 12:36:49 -0700 (PDT) Subject: [Tutor] mailman In-Reply-To: Message-ID: On Mon, 1 Aug 2005, Mohammad Moghimi wrote: > I want to install mailman. [cut] Hi Mohammad, This is the python-tutor mailing list: we help in teaching how to program in Python. However, we aren't the technical support group for the Mailman mailing list software, and we probably won't be able to help you because we have no special knowledge of their product. Try asking the 'Mailman Users' list instead: http://list.org/lists.html Good luck to you. From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 21:48:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 12:48:26 -0700 (PDT) Subject: [Tutor] question on string In-Reply-To: <42EE6488.5050905@tds.net> Message-ID: On Mon, 1 Aug 2005, Kent Johnson wrote: > > I would like to construct some string objects using the cprintf-style > > format: > > > > command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) > > > > Of course it is illegal in python but I couldn't figure out a way to > > construct strings with that kind of formatting and substitution. > > Actually that is correct as written! (though 'file' is a poor choice of > variable name as it shadows the built-in file() function...) [text cut] Just as a side note, building command strings like this is usually not a good idea, just because of issues like shell quotation. Unfortunately, there are a lot of examples on the web that do use string interpolation to build up command lines, but there is usually a better way: Python comes with a subprocess module which can take a list of arguments. For example: ###### >>> import subprocess >>> p = subprocess.Popen(['wc', '-l', '/usr/share/dict/words'], ... stdout=subprocess.PIPE) >>> >>> p.stdout.read() '234937 /usr/share/dict/words\n' ###### The advantage of passing a list instead of a formatted string here is that we don't have to worry if our files contains spaces in their names. Hope this helps! From cgw501 at york.ac.uk Mon Aug 1 22:05:03 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 01 Aug 2005 21:05:03 +0100 Subject: [Tutor] counting problem Message-ID: hi, I have large txt file with lines like this: ['DDB0216437'] 1166 1174 9 ZZZ 100 What I want to do is quickly count the number of lines that share a value in the 4th column and 5th (i.e. in this line I would count all the line that have '9' and 'ZZZ'). Anyone got any ideas for the quickest way to do this? The solution I have is really ugly. thanks, Chris From jobauk at hotmail.com Mon Aug 1 22:12:53 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Mon, 01 Aug 2005 20:12:53 +0000 Subject: [Tutor] Color text in Text widget In-Reply-To: <8171b61605080112356c1264ab@mail.gmail.com> Message-ID: I found a way to do it but I'm not sure it is the cleanest. Maybe someone else on this list can offer a better solution. I use the text's configuration to define tags that I apply to sections of the text. For example: txtBox = Text(self, width=80, height=20) # configuration for red txtBox.tag_config("r", foreground="red") # configuration for blue txtBox.tag_config("b", foreground="blue") txtBox.insert(END,"I am red ", "r") txtBox.insert(END,"and I am blue\n", "b") Hope that helps jorge >From: sunny sunny >To: tutor at python.org >Subject: [Tutor] Color text in Text widget >Date: Mon, 1 Aug 2005 15:35:52 -0400 > >Hi all, > >How do I add color to the text in the Text widget? I tried using the >ASCII sequence but it didnt work. > >For example, I want to add: > This is red , but this is blue > >Thanks. >Santosh. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Aug 1 22:22:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Aug 2005 16:22:09 -0400 Subject: [Tutor] counting problem In-Reply-To: References: Message-ID: <42EE8471.3070605@tds.net> cgw501 at york.ac.uk wrote: > hi, > > I have large txt file with lines like this: > > ['DDB0216437'] 1166 1174 9 ZZZ 100 > > What I want to do is quickly count the number of lines that share a value > in the 4th column and 5th (i.e. in this line I would count all the line > that have '9' and 'ZZZ'). Anyone got any ideas for the quickest way to do > this? The solution I have is really ugly. thanks, This should get you started. It assumes that there is no whitespace embedded in the fields. Add error handling and options to taste. Kent count = 0 f = open('data.txt') for line in f: data = line.split() if data[3] == '9' and data[4] == 'ZZZ': count += 1 f.close() print count From adam.jtm30 at gmail.com Mon Aug 1 22:34:37 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 1 Aug 2005 21:34:37 +0100 Subject: [Tutor] Socket Programming In-Reply-To: <42EE42B6.7010604@gmail.com> References: <42ED3C3D.5060200@gmail.com> <42EE42B6.7010604@gmail.com> Message-ID: Hi Joe you can use 10000 and just send 'Hi!' as long as something else isn't likely to be sent at the same time. It will just read what is in that socket when you call it so if something else that you don't want is there just behind what you're after then you could end up with that as well. On 8/1/05, Joseph Quigley wrote: > > Hi, > > Ok. But what if I wanted to send a 1 mb message? Could I leave > .recv(10000) in and send 'Hi!' as well or would I have to change it? > Thanks, > JQ > > Adam Bark wrote: > > > You have to put in how many bytes of data you want to recieve in > > clientsocket.recv() eg. clientsocket.recv(1024) for 1kB. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/4f322e64/attachment-0001.htm From falcon3166 at hotmail.com Mon Aug 1 22:39:18 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 14:39:18 -0600 Subject: [Tutor] I've run into a jam on the exercise on file I/O Message-ID: Hey all, I've seem to run into a jam while working on the exercise on file I/O. Here's the error: Filename to save: university.txt Traceback (most recent call last): File "D:\Python22\grades.py", line 99, in ? save_grades(students,filename) File "D:\Python22\grades.py", line 51, in save_grades out_file.write(x+","+max_points[x]+"\n") TypeError: sequence index must be integer And the code: max_points = [25,25,50,25,100] assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] students = {'#Max':max_points} def print_menu(): print "1. Add student" print "2. Remove student" print "3. Print grades" print "4. Record grade" print "5. Load Grades" print "6. Save Grades" print "9. Exit" def print_all_grades(): print '\t', for i in range(len(assignments)): print assignments[1],'\t', print keys = students.keys() keys.sort() for x in keys: print x,'\t', grades = students[x] print_grades(grades) def print_grades(grades): for i in range(len(grades)): print grades[i],'\t\t', print def choice(): return int(raw_input("Menu Choice: ")) def school(): return raw_input("Student: ") def load_grades(students,filename): in_file = open(filename, "r") while 1: in_line = in_file.readline() if in_line == "": break in_line = in_line[:-1] [students,max_points] = string.split(in_line,",") max_points[students] = grade in_file.close() def save_grades(students,filename): out_file = open(filename, "w") for x in students.keys(): out_file.write(x+","+max_points[x]+"\n") out_file.close print "Grade Tracking Program." while 1: print_menu() menu_choice = choice() if menu_choice == 1: print "Add student" name = school() students[name] = [0]*len(max_points) elif menu_choice == 2: print "Remove student" name = school() if students.has_key(name): del students[name] else: print "Student: ",name," not found." elif menu_choice == 3: print_all_grades() elif menu_choice == 4: print "Record Grade" name = school() if students.has_key(name): grades = students[name] print "Type in the number of the grade to record" print "Type in a 0 (zero) to exit" for i in range(len(assignments)): print i+1,' ',assignments[i],'\t', print print_grades(grades) which = 1234 while which != -1: which = int(raw_input("Change which Grade: ")) which = which-1 if 0 <= which < len(grades): grade = int(raw_input("Grade: ")) grades[which] = grade elif which != -1: print "Invalid Grade Number" else: print "Student not found" elif menu_choice == 5: filename = raw_input("Filename to load: ") load_grades(students,filename) elif menu_choice == 6: filename = raw_input("Filename to save: ") save_grades(students,filename) elif menu_choice == 9: break else: print "That's not a choice!" print "Goodbye." What's the problem, and how is it fixed? Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/dea6a2d1/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050801/dea6a2d1/PinnoNathanPaul.vcf From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 22:41:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 13:41:36 -0700 (PDT) Subject: [Tutor] counting problem In-Reply-To: <42EE8471.3070605@tds.net> Message-ID: On Mon, 1 Aug 2005, Kent Johnson wrote: > cgw501 at york.ac.uk wrote: > > hi, > > > > I have large txt file with lines like this: > > > > ['DDB0216437'] 1166 1174 9 ZZZ 100 > > > > What I want to do is quickly count the number of lines that share a > > value in the 4th column and 5th (i.e. in this line I would count all > > the line that have '9' and 'ZZZ'). Anyone got any ideas for the > > quickest way to do this? The solution I have is really ugly. thanks, A dictionary approach may also be useful. The following example should help illustrate the technique: ###### >>> def histogram(iterable): ... """Returns a list of counts of each unique element in iterable.""" ... d = {} ... for x in iterable: ... d[x] = d.get(x, 0) + 1 ... return d.items() ... >>> histogram("this is a test of the emergency broadcast system this is only a test") [('a', 4), (' ', 13), ('c', 2), ('b', 1), ('e', 7), ('d', 1), ('g', 1), ('f', 1), ('i', 4), ('h', 3), ('m', 2), ('l', 1), ('o', 3), ('n', 2), ('s', 9), ('r', 2), ('t', 9), ('y', 3)] ###### This is a fairly straightforward way of doing letter-frequency stuff. We can see from the histogram that the letters {'d', 'f', 'g', 'l'] are solitary and occur only once. This tallying approach can also be applied to the original poster's question with the columns of a text file, as long as we figure out what we want to tally up. Good luck! From adam.jtm30 at gmail.com Mon Aug 1 22:47:56 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 1 Aug 2005 21:47:56 +0100 Subject: [Tutor] I've run into a jam on the exercise on file I/O In-Reply-To: References: Message-ID: >>> max_points = [25,25,50,25,100] >>> assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] >>> students = {'#Max':max_points} >>> students {'#Max': [25, 25, 50, 25, 100]} The problem is the key in students is a list not an integer. On 8/1/05, Nathan Pinno wrote: > > Hey all, > I've seem to run into a jam while working on the exercise on file I/O. > Here's the error: > Filename to save: university.txt > Traceback (most recent call last): > File "D:\Python22\grades.py", line 99, in ? > save_grades(students,filename) > File "D:\Python22\grades.py", line 51, in save_grades > out_file.write(x+","+max_points[x]+"\n") > TypeError: sequence index must be integer > And the code: > max_points = [25,25,50,25,100] > assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] > students = {'#Max':max_points} > def print_menu(): > print "1. Add student" > print "2. Remove student" > print "3. Print grades" > print "4. Record grade" > print "5. Load Grades" > print "6. Save Grades" > print "9. Exit" > def print_all_grades(): > print '\t', > for i in range(len(assignments)): > print assignments[1],'\t', > print > keys = students.keys() > keys.sort() > for x in keys: > print x,'\t', > grades = students[x] > print_grades(grades) > def print_grades(grades): > for i in range(len(grades)): > print grades[i],'\t\t', > print > def choice(): > return int(raw_input("Menu Choice: ")) > def school(): > return raw_input("Student: ") > def load_grades(students,filename): > in_file = open(filename, "r") > while 1: > in_line = in_file.readline() > if in_line == "": > break > in_line = in_line[:-1] > [students,max_points] = string.split(in_line,",") > max_points[students] = grade > in_file.close() > def save_grades(students,filename): > out_file = open(filename, "w") > for x in students.keys(): > out_file.write(x+","+max_points[x]+"\n") > out_file.close > print "Grade Tracking Program." > while 1: > print_menu() > menu_choice = choice() > if menu_choice == 1: > print "Add student" > name = school() > students[name] = [0]*len(max_points) > elif menu_choice == 2: > print "Remove student" > name = school() > if students.has_key(name): > del students[name] > else: > print "Student: ",name," not found." > elif menu_choice == 3: > print_all_grades() > elif menu_choice == 4: > print "Record Grade" > name = school() > if students.has_key(name): > grades = students[name] > print "Type in the number of the grade to record" > print "Type in a 0 (zero) to exit" > for i in range(len(assignments)): > print i+1,' ',assignments[i],'\t', > print > print_grades(grades) > which = 1234 > while which != -1: > which = int(raw_input("Change which Grade: ")) > which = which-1 > if 0 <= which < len(grades): > grade = int(raw_input("Grade: ")) > grades[which] = grade > elif which != -1: > print "Invalid Grade Number" > else: > print "Student not found" > elif menu_choice == 5: > filename = raw_input("Filename to load: ") > load_grades(students,filename) > elif menu_choice == 6: > filename = raw_input("Filename to save: ") > save_grades(students,filename) > elif menu_choice == 9: > break > else: > print "That's not a choice!" > print "Goodbye." > What's the problem, and how is it fixed? > Thanks, > Nathan Pinno, > Crew, Camrose McDonalds and owner/operator of Woffee > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/d7d89f5d/attachment-0001.htm From falcon3166 at hotmail.com Mon Aug 1 22:52:16 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 14:52:16 -0600 Subject: [Tutor] I've run into a jam on the exercise on file I/O References: Message-ID: Maybe I should use assignments instead? ----- Original Message ----- From: Adam Bark To: Nathan Pinno Cc: tutor at python.org Sent: Monday, August 01, 2005 2:47 PM Subject: Re: [Tutor] I've run into a jam on the exercise on file I/O >>> max_points = [25,25,50,25,100] >>> assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] >>> students = {'#Max':max_points} >>> students {'#Max': [25, 25, 50, 25, 100]} The problem is the key in students is a list not an integer. On 8/1/05, Nathan Pinno wrote: Hey all, I've seem to run into a jam while working on the exercise on file I/O. Here's the error: Filename to save: university.txt Traceback (most recent call last): File "D:\Python22\grades.py", line 99, in ? save_grades(students,filename) File "D:\Python22\grades.py", line 51, in save_grades out_file.write(x+","+max_points[x]+"\n") TypeError: sequence index must be integer And the code: max_points = [25,25,50,25,100] assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] students = {'#Max':max_points} def print_menu(): print "1. Add student" print "2. Remove student" print "3. Print grades" print "4. Record grade" print "5. Load Grades" print "6. Save Grades" print "9. Exit" def print_all_grades(): print '\t', for i in range(len(assignments)): print assignments[1],'\t', print keys = students.keys() keys.sort() for x in keys: print x,'\t', grades = students[x] print_grades(grades) def print_grades(grades): for i in range(len(grades)): print grades[i],'\t\t', print def choice(): return int(raw_input("Menu Choice: ")) def school(): return raw_input("Student: ") def load_grades(students,filename): in_file = open(filename, "r") while 1: in_line = in_file.readline() if in_line == "": break in_line = in_line[:-1] [students,max_points] = string.split(in_line,",") max_points[students] = grade in_file.close() def save_grades(students,filename): out_file = open(filename, "w") for x in students.keys(): out_file.write(x+","+max_points[x]+"\n") out_file.close print "Grade Tracking Program." while 1: print_menu() menu_choice = choice() if menu_choice == 1: print "Add student" name = school() students[name] = [0]*len(max_points) elif menu_choice == 2: print "Remove student" name = school() if students.has_key(name): del students[name] else: print "Student: ",name," not found." elif menu_choice == 3: print_all_grades() elif menu_choice == 4: print "Record Grade" name = school() if students.has_key(name): grades = students[name] print "Type in the number of the grade to record" print "Type in a 0 (zero) to exit" for i in range(len(assignments)): print i+1,' ',assignments[i],'\t', print print_grades(grades) which = 1234 while which != -1: which = int(raw_input("Change which Grade: ")) which = which-1 if 0 <= which < len(grades): grade = int(raw_input("Grade: ")) grades[which] = grade elif which != -1: print "Invalid Grade Number" else: print "Student not found" elif menu_choice == 5: filename = raw_input("Filename to load: ") load_grades(students,filename) elif menu_choice == 6: filename = raw_input("Filename to save: ") save_grades(students,filename) elif menu_choice == 9: break else: print "That's not a choice!" print "Goodbye." What's the problem, and how is it fixed? Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/896c6b07/attachment.htm From adam.jtm30 at gmail.com Mon Aug 1 22:55:17 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 1 Aug 2005 21:55:17 +0100 Subject: [Tutor] I've run into a jam on the exercise on file I/O In-Reply-To: References: Message-ID: No sorry scratch that last one I was being stupid. The key is a string but max_points is a list so the list index max_points[x] is effectively looking for max_points[student]. def save_grades(students,filename): out_file = open(filename, "w") for x in students.keys(): out_file.write(x+","+max_points[x]+"\n") out_file.close On 8/1/05, Adam Bark wrote: > > >>> max_points = [25,25,50,25,100] > >>> assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] > >>> students = {'#Max':max_points} > >>> students > {'#Max': [25, 25, 50, 25, 100]} > > The problem is the key in students is a list not an integer. > > On 8/1/05, Nathan Pinno wrote: > > > Hey all, > > I've seem to run into a jam while working on the exercise on file I/O. > > Here's the error: > > Filename to save: university.txt > > Traceback (most recent call last): > > File "D:\Python22\grades.py", line 99, in ? > > save_grades(students,filename) > > File "D:\Python22\grades.py", line 51, in save_grades > > out_file.write(x+","+max_points[x]+"\n") > > TypeError: sequence index must be integer > > And the code: > > max_points = [25,25,50,25,100] > > assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] > > students = {'#Max':max_points} > > def print_menu(): > > print "1. Add student" > > print "2. Remove student" > > print "3. Print grades" > > print "4. Record grade" > > print "5. Load Grades" > > print "6. Save Grades" > > print "9. Exit" > > def print_all_grades(): > > print '\t', > > for i in range(len(assignments)): > > print assignments[1],'\t', > > print > > keys = students.keys() > > keys.sort() > > for x in keys: > > print x,'\t', > > grades = students[x] > > print_grades(grades) > > def print_grades(grades): > > for i in range(len(grades)): > > print grades[i],'\t\t', > > print > > def choice(): > > return int(raw_input("Menu Choice: ")) > > def school(): > > return raw_input("Student: ") > > def load_grades(students,filename): > > in_file = open(filename, "r") > > while 1: > > in_line = in_file.readline() > > if in_line == "": > > break > > in_line = in_line[:-1] > > [students,max_points] = string.split(in_line,",") > > max_points[students] = grade > > in_file.close() > > def save_grades(students,filename): > > out_file = open(filename, "w") > > for x in students.keys(): > > out_file.write(x+","+max_points[x]+"\n") > > out_file.close > > print "Grade Tracking Program." > > while 1: > > print_menu() > > menu_choice = choice() > > if menu_choice == 1: > > print "Add student" > > name = school() > > students[name] = [0]*len(max_points) > > elif menu_choice == 2: > > print "Remove student" > > name = school() > > if students.has_key(name): > > del students[name] > > else: > > print "Student: ",name," not found." > > elif menu_choice == 3: > > print_all_grades() > > elif menu_choice == 4: > > print "Record Grade" > > name = school() > > if students.has_key(name): > > grades = students[name] > > print "Type in the number of the grade to record" > > print "Type in a 0 (zero) to exit" > > for i in range(len(assignments)): > > print i+1,' ',assignments[i],'\t', > > print > > print_grades(grades) > > which = 1234 > > while which != -1: > > which = int(raw_input("Change which Grade: ")) > > which = which-1 > > if 0 <= which < len(grades): > > grade = int(raw_input("Grade: ")) > > grades[which] = grade > > elif which != -1: > > print "Invalid Grade Number" > > else: > > print "Student not found" > > elif menu_choice == 5: > > filename = raw_input("Filename to load: ") > > load_grades(students,filename) > > elif menu_choice == 6: > > filename = raw_input("Filename to save: ") > > save_grades(students,filename) > > elif menu_choice == 9: > > break > > else: > > print "That's not a choice!" > > print "Goodbye." > > What's the problem, and how is it fixed? > > Thanks, > > Nathan Pinno, > > Crew, Camrose McDonalds and owner/operator of Woffee > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/210bc5c2/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Aug 1 23:00:20 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 22:00:20 +0100 Subject: [Tutor] visibility of variables References: <42EE50A8.3030803@iol.ie> Message-ID: <045201c596dc$0748f300$8eaa8651@xp> > I have problems with the visibility of variables in python. I am > used to the idea of Javascript and other languages where one can > define > global variables if they are defined outside a function. It seems > Python > is not doing that, but how can I make it work? Kent has answered the question of how to do it in Python but I would point out that using global variables is, in general, considered bad practice. It is best to minimise their use as muh as possible and pass data into functions and return values from them. There usually are a few globals in any program so don't worry too much about them. BUt on the otherhand if most of your functions are writing to global variables then your program design probably needs rethinking! > around this? I could add gemetenkleur in the argument list of the > funct1 > and funct2 functions, but in my case I don't want this (funct1 will > be a > function to be used in scipy.fmin, and I have the idea that only the > simplex can be as an argument). Passing the values as arguments would IMHO be much better in your case Consider your code, slightly rewritten (with shorter names! :-) to reflect what I think you are trying to do: b=[(1,2,3),(3,4,5),(5,6,7)] def funct1(g): print 'g in func1: ',g a=funct2(g) print a def funct2(k): print 'k in funct2 (should be same as g): ',k return 1 def Do(b,f): g=b[:] print 'g has to be from now b: ',g f(g) return g G = Do(b,funct1) print G > Hope someone can help me. I have the idea this is essential to > understand before continuing more in Python. You might also look at the 'What's in a Name' topic in my tutor for more on this (There is a slightly old German translation too). Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tpc247 at gmail.com Mon Aug 1 23:00:51 2005 From: tpc247 at gmail.com (tpc247@gmail.com) Date: Mon, 1 Aug 2005 14:00:51 -0700 Subject: [Tutor] try except continue In-Reply-To: <015701c59410$7466aa00$8eaa8651@xp> References: <015701c59410$7466aa00$8eaa8651@xp> Message-ID: hi guys, so I've been running through Alan's code, and for a while I suspected that the try block must be the first line of code after the loop in order to be executed. The reason I say this is I wanted to see for myself Alan's assertion that the continue skips to the next iteration, instead of continuing with the rest of the try block, so I did the following: def f(): if error: raise ValueError else: print "I'm in f()" def g(): print "I'm in g()" def h(): error = True print "error is: ", error n = 5 while n: print "n is: ", n n -= 1 try: f() g() except ValueError: error = False continue and I got the following as output: >>> h() error is: True n is: 5 n is: 4 n is: 3 n is: 2 n is: 1 I gathered that since I didn't see the output of f() and g(), then those two functions must have never executed, and thus the try block must have never executed. However, when I moved the try block to be the first line after the loop: def h(): error = True print "error is: ", error n = 5 while n: try: f() g() except ValueError: error = False continue print "n is: ", n n -= 1 I got the following as output: >>> h() error is: True Traceback (most recent call last): File "", line 1, in -toplevel- h() File "", line 9, in h except ValueError: KeyboardInterrupt and I actually had to press Ctrl-C to stop the never terminating program. I simply wanted to confirm Alan's assertion that continue will cause the loop to skip to the next iteration, but it seems I can't seem to get my f() and g() to print even though they were able to before. Am I doing something wrong ? From dyoo at hkn.eecs.berkeley.edu Mon Aug 1 23:03:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 14:03:35 -0700 (PDT) Subject: [Tutor] I've run into a jam on the exercise on file I/O In-Reply-To: Message-ID: On Mon, 1 Aug 2005, Nathan Pinno wrote: > I've seem to run into a jam while working on the exercise on file I/O. > Here's the error: > Filename to save: university.txt > Traceback (most recent call last): > File "D:\Python22\grades.py", line 99, in ? > save_grades(students,filename) > File "D:\Python22\grades.py", line 51, in save_grades > out_file.write(x+","+max_points[x]+"\n") > TypeError: sequence index must be integer Hi Nathan, I'll try to capture what I think of when I see error messages like this, to better illustrate how to take something like this, and puzzle it through. Let's take a close look at the error message, first: > TypeError: sequence index must be integer Python doesn't like some place where we're doing an indexing operation. Where would that be? Let's look at the line that Python pointed out, around line 99. > out_file.write(x+","+max_points[x]+"\n") The only indexing operation I can see here is the subexpression: max_points[x] and the error makes sense if if 'x' isn't a number. Let's take a look at where 'x' is being assigned, and see if we're assigning it to a non-number. > def save_grades(students,filename): > out_file = open(filename, "w") > for x in students.keys(): > out_file.write(x+","+max_points[x]+"\n") > out_file.close Ok, 'x' comes from the keys of our 'students' dictionary. Now our problem turns into: are the keys of the students dictionary numbers, or are they something else? At a high level, we're trying to determine: is our use of max_points[x] in the save_grades() function the thing that's broken, or is the value 'x' that's broken? For the moment, we'll follow 'x', and if that turns out ok, then we should go back to save_grades() and see what it's trying to write out. (We can do things in the other order, too, of course. Flip a coin. *grin*) Let's look at how 'students' is being constructed, since the values of 'x' comes from the keys of the 'students' dictionary. ###### > max_points = [25,25,50,25,100] > assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] > students = {'#Max':max_points} ###### Ok. We certainly see that one of the keys in the 'students' dictionary isn't a number, so at least we can confirm the error message. '#Max', for example, is certainly not a number. What is 'students' supposed to represent? That is, can we try describing what the keys are supposed to be, and what the values are supposed to be? I will guess that you're thinking of it more like a table, with: #Max | [25, 25, 50, 25, 100] ---------+----------------------- Danny | [20, 20, 40, 20, 90] Nick | [25, 25, 49, 24, 99] where the keys are student names, and the values are their respective test scores. It might be good to rename 'students' to 'student_grades' then, to make that relationship more clear. Anyway, in that case, the 'students' dictionary actually looks fine: it contains the right thing. Ok, let's go back to the definition of save_grades(): > def save_grades(students,filename): > out_file = open(filename, "w") > for x in students.keys(): > out_file.write(x+","+max_points[x]+"\n") > out_file.close and, for the moment, let's completely ignore the body of the function, and just imagine: what do we imagine should happen when we save the grades to disk? It should read off the students (the "student to grades") dictionary, and write it to disk. Let's look back at the body of save_grades() now. How does max_points relate to writing out all of the students and their grades to disk? Does it really matter, or did we mean to use a different value? Please feel free to ask questions on any point of this. Good luck! From alan.gauld at freenet.co.uk Mon Aug 1 23:05:17 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 22:05:17 +0100 Subject: [Tutor] question on string References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> <42EE5EF0.5060409@lynuxworks.com> Message-ID: <045e01c596dc$b80edb00$8eaa8651@xp> > I would like to construct some string objects using the > cprintf-style format: > > command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) Should work - assuming the 3 variables are defined! Although file is a bad name for a variable since its also the name of the function for opening files! > Of course it is illegal in python but I couldn't figure out a way to > construct strings with that kind of formatting and substitution. What makes you think it is illegal? Did you get an error? If so what did it look like (full text please). > I have been looking and couldn't discover string constructor such as > > command_string = string( "diff -u %s %s > %s.patch" % ( src, dst, > file ) ) You don't need a constructor as such just use the quotes as in the first attempt above. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at sbcglobal.net Mon Aug 1 20:20:16 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Mon, 01 Aug 2005 11:20:16 -0700 Subject: [Tutor] question on string In-Reply-To: <42EE5EF0.5060409@lynuxworks.com> References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> <42EE5EF0.5060409@lynuxworks.com> Message-ID: <6.1.2.0.0.20050801110401.032e7a08@pop.sbcglobal.yahoo.com> At 10:42 AM 8/1/2005, Gilbert Tsang wrote: >Hi there, > >I would like to construct some string objects using the cprintf-style format: > >command_string = "diff -u %s %s > %s.patch" % ( src, dst, file ) > >Of course it is illegal in python How did you conclude that? "diff -u %s %s > %s.patch" % ( src, dst, file ) is a Python expression, and will do what you want! See http://docs.python.org/lib/typesseq-strings.html for the official documentation. >but I couldn't figure out a way to >construct strings with that kind of formatting and substitution. > >I have been looking and couldn't discover string constructor such as > >command_string = string( "diff -u %s %s > %s.patch" % ( src, dst, file ) ) > > From the documentation on docs.python.org, the closest is string >Template (but my python installation doesn't come with this module). Any >insights on initializing string in this manner? > > >Thanks, Gilbert. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/1d8e30d2/attachment.htm From alan.gauld at freenet.co.uk Mon Aug 1 23:17:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 22:17:21 +0100 Subject: [Tutor] counting problem References: Message-ID: <048101c596de$67bd6a20$8eaa8651@xp> > What I want to do is quickly count the number of lines that share a > value in the 4th column and 5th (i.e. in this line I would count all > the line that have '9' and 'ZZZ'). Anyone got any ideas for the > quickest way to do this? The solution I have is really ugly. thanks, Pesonally I'd just use awk: $ awk '$4==9 && $5=="ZZZ" {count++} END {printf count}' myfile.dat Should do it. Alan G. From alan.gauld at freenet.co.uk Mon Aug 1 23:20:36 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 22:20:36 +0100 Subject: [Tutor] Color text in Text widget References: Message-ID: <048f01c596de$dbfe2820$8eaa8651@xp> > I use the text's configuration to define tags that I apply to > sections of the text. For example: > > txtBox = Text(self, width=80, height=20) > # configuration for red > txtBox.insert(END,"I am red ", "r") I don't know if it's the absolute best way but I didn't know you could do that and I think its pretty neat! Pesonally I'd have been manually changing the foreground colour before each insert! Thanks for sharing. Alan G. From gtsang at lnxw.com Mon Aug 1 23:32:03 2005 From: gtsang at lnxw.com (Gilbert Tsang) Date: Mon, 01 Aug 2005 14:32:03 -0700 Subject: [Tutor] question on string In-Reply-To: <1122921585.16017.5.camel@localhost.localdomain> References: <20050717181803.GB33691@alexis.mi.celestial.com> <20050718165526.GC32754@alexis.mi.celestial.com> <42EE5EF0.5060409@lynuxworks.com> <1122921585.16017.5.camel@localhost.localdomain> Message-ID: <42EE94D3.7060704@lynuxworks.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/4dfbc5ae/attachment-0001.htm From falcon3166 at hotmail.com Mon Aug 1 23:33:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 15:33:28 -0600 Subject: [Tutor] Question Message-ID: Hi all, Just curious to wonder if Python can be used to write a program to check an HTTP mail server for mail, and check more than one server, even if they are using different proxies, i.e. HTTP for one and SMTP for the other. Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/3996ec06/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050801/3996ec06/PinnoNathanPaul.vcf From jeffpeery at yahoo.com Tue Aug 2 00:01:24 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 1 Aug 2005 15:01:24 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <6fb78be1a69f4fe1cbe2a8a7d5f7e678@uni-mainz.de> Message-ID: <20050801220124.16014.qmail@web30505.mail.mud.yahoo.com> thanks for the help. I think I'm understanding this a bit better. although I still don't completely understand the output. here is an example... for the input I have 1024 samples taken from a 1 Hz square wave with amplitude = 1. for the output I would expect an infinite number of frequencies. the output from FFT.fft(myData).real is this: . . . -0.498 1 0.0 2 -0.498 3 0.0 4 -0.498 5 0.0 6 -0.498 7 0.0 8 -0.498 9 0.0 10 -0.498 11 0.0 12 -0.498 13 0.0 14 -0.498 15 0.0 16 -0.498 17 . . . I'm not sure why the output alternates from 0 and 0.498. I would expect 0.498 at all frequencies? why the oscillation? Christian Meesters wrote: Jeff Peery wrote: > > Hello, I have a signal that I want to do a fourier transform on. I > tried using FFT.fft(data).real but I don't understand the output. > what is output from this function, and why doesn't it require > amplitude and time as inputs? Hi Jeff, As Danny wrote, your input are real numbers and your output will be complex numbers. I don't want to point you to the numarray documentation once more, but you might to check out this: http://mathworld.wolfram.com/FourierSeries.html as for why you get complex numbers back. (To get only the real value part try real_fft() in numarrayl.) In general in numerical computation your input is simply a series of real numbers - of equal spacing in the dimension you want to consider. Which dimension you choose (amplitudes and time/phase or amplitudes and spacial frequencies and so on) is up to you. It depends on your physical or mathematical question. IMHO the best introduction you can get on Fourier Transforms & programming can be found in Numerical Recipies (here the "Numerical Recipies in C"-link http://www.library.cornell.edu/nr/bookcpdf.html - check chapter 12). Have fun with FFTs! Cheers Christian _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/87fc45fd/attachment.htm From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 00:18:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 15:18:49 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <20050801220124.16014.qmail@web30505.mail.mud.yahoo.com> Message-ID: On Mon, 1 Aug 2005, Jeff Peery wrote: > thanks for the help. I think I'm understanding this a bit better. > although I still don't completely understand the output. here is an > example... for the input I have 1024 samples taken from a 1 Hz square > wave with amplitude = 1. for the output I would expect an infinite > number of frequencies. the output from FFT.fft(myData).real is this: [data cut] > I would expect 0.498 at all frequencies? why the oscillation? That actually sounds fine. By a square wave, you mean something like: ------- ------- ------- | | | | | | | | ------ ------- and according to the MathWorld documentation that Christian mentioned, http://mathworld.wolfram.com/FourierSeries.html according to analysis, the square wave does have a Fourier transform that oscillates the way that you've observing: http://mathworld.wolfram.com/FourierSeriesSquareWave.html where the coefficients are zero on the even n. So I think you're actually getting correct values there. Good luck! From jeffpeery at yahoo.com Tue Aug 2 00:38:42 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 1 Aug 2005 15:38:42 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <200507301331.11248.Pawel_Kraszewski@wp.pl> Message-ID: <20050801223842.24818.qmail@web30505.mail.mud.yahoo.com> ok, this makes more sense. what I want to know is the amplitude for the output frequencies. I'm using import FFT, and FFT.fft(). the first element of the output is the DC constant? not sure what this is. is the amplitude for all other elements plus the DC equal to the actual amplitude? thanks. Pawel Kraszewski wrote: > Hello, I have a signal that I want to do a fourier transform on. I tried > using FFT.fft(data).real but I don't understand the output. what is output > from this function, and why doesn't it require amplitude and time as > inputs? Please write the package you use for FFT. Standard Python doesn't have one. Perhaps you use some custom Python? Like Enthought Python? If so, the exhaustive guide is delivered with it in CHM (windows help) format. 1. In general FFT algorithms require you to supply just N complex values (complex contains both amplitude and phase of signal). If you supply real values, the system assumes phase=0 for each sample and takes given value for amplitude. 2. You DO supply a time information, you just didn't think of it this way: each consecutive sample is taken one fixed clock tick later, so position of sample in data gives you the time it was taken. 3. Results of FFT are in the form of complex vector of the same length as data. Starting from position 0 it gives you an constant (DC factor), position 1 an amplitude and phase (remember - complex number gives you both amplitude and phase) of wave of the length table/2 and so on. If you take real value of this, you discard part of the information. AFAIR - taking real part gives you sine component, taking imaginary part gives you cosine component, taking absolute value gives you total amplitude and taking angle gives you phase. 4. The answer is symmetrical - usually you take only half of it. I don't remember the exact difference between the halves, but you may find it in any article on FFT. Best regards, Pawel Kraszewski _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/058c4f39/attachment.htm From jeffpeery at yahoo.com Tue Aug 2 00:38:43 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 1 Aug 2005 15:38:43 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <200507301331.11248.Pawel_Kraszewski@wp.pl> Message-ID: <20050801223843.32761.qmail@web30502.mail.mud.yahoo.com> ok, this makes more sense. what I want to know is the amplitude for the output frequencies. I'm using import FFT, and FFT.fft(). the first element of the output is the DC constant? not sure what this is. is the amplitude for all other elements plus the DC equal to the actual amplitude? thanks. Pawel Kraszewski wrote: > Hello, I have a signal that I want to do a fourier transform on. I tried > using FFT.fft(data).real but I don't understand the output. what is output > from this function, and why doesn't it require amplitude and time as > inputs? Please write the package you use for FFT. Standard Python doesn't have one. Perhaps you use some custom Python? Like Enthought Python? If so, the exhaustive guide is delivered with it in CHM (windows help) format. 1. In general FFT algorithms require you to supply just N complex values (complex contains both amplitude and phase of signal). If you supply real values, the system assumes phase=0 for each sample and takes given value for amplitude. 2. You DO supply a time information, you just didn't think of it this way: each consecutive sample is taken one fixed clock tick later, so position of sample in data gives you the time it was taken. 3. Results of FFT are in the form of complex vector of the same length as data. Starting from position 0 it gives you an constant (DC factor), position 1 an amplitude and phase (remember - complex number gives you both amplitude and phase) of wave of the length table/2 and so on. If you take real value of this, you discard part of the information. AFAIR - taking real part gives you sine component, taking imaginary part gives you cosine component, taking absolute value gives you total amplitude and taking angle gives you phase. 4. The answer is symmetrical - usually you take only half of it. I don't remember the exact difference between the halves, but you may find it in any article on FFT. Best regards, Pawel Kraszewski _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/35cf86b7/attachment.htm From alan.gauld at freenet.co.uk Tue Aug 2 00:57:50 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 1 Aug 2005 23:57:50 +0100 Subject: [Tutor] try except continue References: <015701c59410$7466aa00$8eaa8651@xp> Message-ID: <052301c596ec$71384ad0$8eaa8651@xp> ---------- code here --------- def f(): if error: raise ValueError else: print "I'm in f()" def g(): print "I'm in g()" def h(): error = True print "error is: ", error n = 5 while n: print "n is: ", n n -= 1 try: f() g() except ValueError: error = False continue h() ---------------------------------- The above fails because error is a local variable in h() so is not visible in f(). If we pass error as an argument to f it works as expected: $ python testry.py error is: True n is: 5 n is: 4 I'm in f() I'm in g() n is: 3 I'm in f() I'm in g() n is: 2 I'm in f() I'm in g() n is: 1 I'm in f() I'm in g() It sounds like you are still struggling with this concept however. Is there anything specificly that you don;t feel comfortable with? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Tue Aug 2 01:46:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 17:46:40 -0600 Subject: [Tutor] I've run into a jam on the exercise on file I/O References: Message-ID: What if I were to use ID's for the students and use the ID's as the sequence index, and link the students and their grades to the IDs? Just a suggestion, Nathan Pinno ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor" Sent: Monday, August 01, 2005 3:03 PM Subject: Re: [Tutor] I've run into a jam on the exercise on file I/O > > > On Mon, 1 Aug 2005, Nathan Pinno wrote: > >> I've seem to run into a jam while working on the exercise on file I/O. >> Here's the error: >> Filename to save: university.txt >> Traceback (most recent call last): >> File "D:\Python22\grades.py", line 99, in ? >> save_grades(students,filename) >> File "D:\Python22\grades.py", line 51, in save_grades >> out_file.write(x+","+max_points[x]+"\n") >> TypeError: sequence index must be integer > > > Hi Nathan, > > > I'll try to capture what I think of when I see error messages like this, > to better illustrate how to take something like this, and puzzle it > through. > > > Let's take a close look at the error message, first: > >> TypeError: sequence index must be integer > > Python doesn't like some place where we're doing an indexing operation. > Where would that be? > > > Let's look at the line that Python pointed out, around line 99. > >> out_file.write(x+","+max_points[x]+"\n") > > The only indexing operation I can see here is the subexpression: > > max_points[x] > > and the error makes sense if if 'x' isn't a number. Let's take a look at > where 'x' is being assigned, and see if we're assigning it to a > non-number. > > >> def save_grades(students,filename): >> out_file = open(filename, "w") >> for x in students.keys(): >> out_file.write(x+","+max_points[x]+"\n") >> out_file.close > > Ok, 'x' comes from the keys of our 'students' dictionary. Now our problem > turns into: are the keys of the students dictionary numbers, or are they > something else? > > > At a high level, we're trying to determine: is our use of max_points[x] in > the save_grades() function the thing that's broken, or is the value 'x' > that's broken? > > For the moment, we'll follow 'x', and if that turns out ok, then we should > go back to save_grades() and see what it's trying to write out. (We can > do things in the other order, too, of course. Flip a coin. *grin*) > > > Let's look at how 'students' is being constructed, since the values of 'x' > comes from the keys of the 'students' dictionary. > > ###### >> max_points = [25,25,50,25,100] >> assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] >> students = {'#Max':max_points} > ###### > > Ok. We certainly see that one of the keys in the 'students' dictionary > isn't a number, so at least we can confirm the error message. '#Max', for > example, is certainly not a number. > > > What is 'students' supposed to represent? That is, can we try describing > what the keys are supposed to be, and what the values are supposed to be? > > I will guess that you're thinking of it more like a table, with: > > #Max | [25, 25, 50, 25, 100] > ---------+----------------------- > Danny | [20, 20, 40, 20, 90] > Nick | [25, 25, 49, 24, 99] > > > where the keys are student names, and the values are their respective test > scores. It might be good to rename 'students' to 'student_grades' then, > to make that relationship more clear. > > > Anyway, in that case, the 'students' dictionary actually looks fine: it > contains the right thing. Ok, let's go back to the definition of > save_grades(): > >> def save_grades(students,filename): >> out_file = open(filename, "w") >> for x in students.keys(): >> out_file.write(x+","+max_points[x]+"\n") >> out_file.close > > and, for the moment, let's completely ignore the body of the function, and > just imagine: what do we imagine should happen when we save the grades to > disk? It should read off the students (the "student to grades") > dictionary, and write it to disk. > > Let's look back at the body of save_grades() now. How does max_points > relate to writing out all of the students and their grades to disk? Does > it really matter, or did we mean to use a different value? > > > > Please feel free to ask questions on any point of this. Good luck! > > From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 02:29:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 17:29:51 -0700 (PDT) Subject: [Tutor] fourier transform (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 1 Aug 2005 16:21:33 -0700 (PDT) From: Jeff Peery To: Danny Yoo Subject: Re: [Tutor] fourier transform Danny, thanks for the help. Yes, for an odd square wave the b's of the fourier series are non zero for even values and zero for odd values of n. these are the coefficients for the fourier series. Although I beleive the fft (fourier transform) should return the amplitude of frequencies that exist. so for example a fft on a 10 hz sin wave with amplitude equal 2 should return all zero amplitudes except for at 10 hz there should be a spike with amplitude 2. although... this would be bn = 2 for n=1 in the fourier series. If I sample this same signal and use FFT.fft() on it the result is not all zeros except at 10 hz. so I guess I'm still confused as to what the output is telling me. thanks again for everyones help. Danny Yoo wrote: On Mon, 1 Aug 2005, Jeff Peery wrote: > thanks for the help. I think I'm understanding this a bit better. > although I still don't completely understand the output. here is an > example... for the input I have 1024 samples taken from a 1 Hz square > wave with amplitude = 1. for the output I would expect an infinite > number of frequencies. the output from FFT.fft(myData).real is this: [data cut] > I would expect 0.498 at all frequencies? why the oscillation? That actually sounds fine. By a square wave, you mean something like: ------- ------- ------- | | | | | | | | ------ ------- and according to the MathWorld documentation that Christian mentioned, http://mathworld.wolfram.com/FourierSeries.html according to analysis, the square wave does have a Fourier transform that oscillates the way that you've observing: http://mathworld.wolfram.com/FourierSeriesSquareWave.html where the coefficients are zero on the even n. So I think you're actually getting correct values there. Good luck! From falcon3166 at hotmail.com Tue Aug 2 03:01:03 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 19:01:03 -0600 Subject: [Tutor] I need advice. Message-ID: Hey all, I want to write a program that will convert time in any other time zone to my time zone. Would it be better to use the Python time molecule or just a whole bunch of if statements? Waiting eagerly for an answer, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/fb06d41a/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050801/fb06d41a/PinnoNathanPaul.vcf From falcon3166 at hotmail.com Tue Aug 2 03:13:12 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 19:13:12 -0600 Subject: [Tutor] Question about BASIC and Python Message-ID: Hi all, I had a co-worker say to me at work that Python was related to or based upon BASIC. Is this true, and if not, how can I tell my friend why they are similar? Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/4cd947eb/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050801/4cd947eb/PinnoNathanPaul.vcf From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 03:31:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 18:31:31 -0700 (PDT) Subject: [Tutor] fourier transform (fwd) In-Reply-To: Message-ID: Hi Jeff, > Yes, for an odd square wave the b's of the fourier series are non zero > for even values and zero for odd values of n. these are the coefficients > for the fourier series. Although I beleive the fft (fourier transform) > should return the amplitude of frequencies that exist. so for example a > fft on a 10 hz sin wave with amplitude equal 2 should return all zero > amplitudes except for at 10 hz there should be a spike with amplitude 2. Up to this point, I agree with you. > although... this would be bn = 2 for n=1 in the fourier series. But at this point, I'm not so sure. I was expecting coefficient bn to be the contribution at n hertz. n=0 is the contribution from the steady state, so for n=1, I didn't expect to get the contribution from the 10hz wave, but the 1hz one instead. I'm hesitant about this because I really don't remember anything from my EE intro class... *grin* I think we're straying a bit wildly from Python tutorial material, but let's try an example and check something out. I want to sample points from the function: f(x) = sin(x) + sin(2x) + sin(3x) between [0, 2pi]. Let's see... ###### >>> import math >>> def f(x): ... return math.sin(x) + math.sin(2*x) + math.sin(3*x) ... >>> def build_sample(f, n): ... sample = [] ... x = 0 ... while x < 2*math.pi: ... sample.append(f(x)) ... x = x + 2*math.pi / float(n) ... return sample ... ###### This build_sample function will make things nicer to take arbitrary samples of any function. ###### >>> sample = build_sample(f, 2000) ###### I'll take a sample of 2000 points, just to make the function sorta smooth to the FFT function. Ok, let's see what the FFT gives us here: ###### >>> import numarray.fft >>> frequences = numarray.fft.fft(sample) >>> frequences[0].real -5.0942902674044888e-11 >>> frequences[1].real 1.5720366156507799 >>> frequences[2].real 3.1424651347438695 >>> frequences[3].real 4.7037495618800307 >>> frequences[4].real -0.016650764926842861 >>> frequences[5].real -0.012744203044761522 >>> frequences[6].real -0.011435677529394448 ###### And to me, this looks like frequences[0] contains the steady state values, frequences[1] the frequency contribution from 1Hz, and so on. (I have to admit that I don't quite understand what the values mean yet.) Let's try another test: ###### >>> def f(x): ... return 42 + math.sin(2*x) ... >>> sample = build_sample(f, 20000) >>> frequences = numarray.fft.fft(sample) >>> frequences[0].real 840041.99999999814 >>> frequences[1].real 0.00010469890965382478 >>> frequences[2].real 3.1415140090902716 >>> frequences[3].real -0.00056553943694630812 >>> frequences[4].real -0.00041889401962948863 ###### Again, I have to plead a huge amount of ignorance here: I don't quite understand what the real components of the frequencies is supposed to mean. *grin* But it does look like the FFT is sensitive to our f() function at the right frequences --- it's giving us some honking huge value at the steady state, and another blip at frequences[2]. Finally, we can try a square wave: ###### >>> def square(x): ... if x > math.pi: ... return -1 ... return 1 ... >>> freqs = numarray.fft.fft(build_sample(square, 1000)) >>> freqs[0].real -1.0 >>> freqs[1].real 2.9999901501133008 >>> freqs[2].real -0.99996060055012559 >>> freqs[3].real 2.9999113516016997 >>> freqs[4].real -0.99984240375361688 ###### Interesting: I do see some kind of oscillation here, but don't quite understand what it means. What happens if we push the sample rate higher? ###### >>> t = numarray.fft.fft(build_sample(square, 100000)) >>> t = numarray.fft.fft(build_sample(square, 100000)) >>> t[0].real -1.0 >>> t[1].real 2.999999999013506 >>> t[2].real -0.99999999604174983 >>> t[3].real 2.9999999911217117 >>> t[4].real -0.99999998418203995 >>> t[5].real 2.9999999753002307 >>> t[6].real -0.999999964464928 >>> t[7].real 2.9999999516338782 ###### Hmmm... the numbers seem to be about the same. What if we drop them down really low? ###### >>> t = numarray.fft.fft(build_sample(square, 10)) >>> t[0].real 2.0 >>> t[1].real -4.4408920985006262e-15 >>> t[2].real 2.0 >>> t[3].real -1.2382749738730321e-15 >>> t[4].real 2.0 >>> t[5].real 2.2764082277776284e-17 >>> t[6].real 2.0 ###### Odd. Now the odd components look really small! So sample rate does appear to be pretty important: otherwise, we get some weird results from the FFT. Then again, maybe they're not "weird": maybe I'm just misinterpreting the results again. *grin* I wish I knew more about the FFT! I do have the excellently whimsical book "Who is Fourier?" in my bookshelf, but haven't made the time to read it yet. Talk to you later! From rdm at rcblue.com Tue Aug 2 06:36:53 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 01 Aug 2005 21:36:53 -0700 Subject: [Tutor] terminology question Message-ID: <6.2.1.2.2.20050801213512.03bbae30@rcblue.com> Why are list comprehensions called that? Thanks, Dick Moores rdm at rcblue.com From jfouhy at paradise.net.nz Tue Aug 2 06:52:05 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 02 Aug 2005 16:52:05 +1200 (NZST) Subject: [Tutor] terminology question In-Reply-To: <6.2.1.2.2.20050801213512.03bbae30@rcblue.com> References: <6.2.1.2.2.20050801213512.03bbae30@rcblue.com> Message-ID: <1122958325.42eefbf5854c9@www.paradise.net.nz> Quoting Dick Moores : > Why are list comprehensions called that? Because that's what they're called in Haskell, I guess.. It's historical, based on the term "set comprehension" from mathematics, also known as "set builder notation": http://en.wikipedia.org/wiki/Set_comprehension -- John. From rdm at rcblue.com Tue Aug 2 07:28:10 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 01 Aug 2005 22:28:10 -0700 Subject: [Tutor] terminology question In-Reply-To: <1122958325.42eefbf5854c9@www.paradise.net.nz> References: <6.2.1.2.2.20050801213512.03bbae30@rcblue.com> <1122958325.42eefbf5854c9@www.paradise.net.nz> Message-ID: <6.2.1.2.2.20050801222601.06d0a630@rcblue.com> jfouhy at paradise.net.nz wrote at 21:52 8/1/2005: >Quoting Dick Moores : > > > Why are list comprehensions called that? > >Because that's what they're called in Haskell, I guess.. This Haskell, I suppose? >It's historical, based on the term "set comprehension" from mathematics, >also >known as "set builder notation": >http://en.wikipedia.org/wiki/Set_comprehension And I was a math major.. Thanks! Dick From cyresse at gmail.com Tue Aug 2 07:31:05 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 2 Aug 2005 17:31:05 +1200 Subject: [Tutor] Question about BASIC and Python In-Reply-To: References: Message-ID: Erm.... erm.... erm.... having used Visual Basic, XBasic and QBasic, I can honestly say, that about the only similarity is that VB is more or less object orientated, and that they use modules. On 8/2/05, Nathan Pinno wrote: > > Hi all, > I had a co-worker say to me at work that Python was related to or based > upon BASIC. Is this true, and if not, how can I tell my friend why they are > similar? > Nathan Pinno, > Crew, Camrose McDonalds and owner/operator of Woffee > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/d33cd056/attachment.htm From bgailer at sbcglobal.net Tue Aug 2 07:09:22 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Mon, 01 Aug 2005 22:09:22 -0700 Subject: [Tutor] Question about BASIC and Python In-Reply-To: References: Message-ID: <6.1.2.0.0.20050801220126.032e84d0@pop.sbcglobal.yahoo.com> At 06:13 PM 8/1/2005, Nathan Pinno wrote: >Hi all, > >I had a co-worker say to me at work that Python was related to or based >upon BASIC. Is this true, and if not, how can I tell my friend why they >are similar? There are many versions of BASIC (Beginners All-Purpose Symbolic Instruction Code) (or something like that). What most have in common with Python (and a lot of other programming languages) is: variables of various data types statements expressions with numeric, string, relational and boolean operations sequential execution control structures for conditionals and loops subroutines input/output arrays some BASIC versions also add exception handling an attempt at OO Python differs in the use of indentation to convey control structure dictionaries object-oriented to the max builtin object methods all items are objects all objects may be dynamically altered object properties may be added anytime modules big library of modules and many more Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/e3a662e0/attachment.htm From janemuiri at hotmail.com Tue Aug 2 03:15:44 2005 From: janemuiri at hotmail.com (Jane MUIRI) Date: Tue, 02 Aug 2005 04:15:44 +0300 Subject: [Tutor] QUESTION Message-ID: Hi! I'd like to know what kind of Python I can download. I've tried but in vain! My computer is windows xp servixe pack 1, version 2002. Please, tell me what to do. Jane. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From falcon3166 at hotmail.com Tue Aug 2 07:39:41 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 1 Aug 2005 23:39:41 -0600 Subject: [Tutor] Question about BASIC and Python References: <6.1.2.0.0.20050801220126.032e84d0@pop.sbcglobal.yahoo.com> Message-ID: Thanks Bob and Liam. I was wondering myself. ----- Original Message ----- From: Bob Gailer To: Nathan Pinno ; Tutor mailing list Sent: Monday, August 01, 2005 11:09 PM Subject: Re: [Tutor] Question about BASIC and Python At 06:13 PM 8/1/2005, Nathan Pinno wrote: Hi all, I had a co-worker say to me at work that Python was related to or based upon BASIC. Is this true, and if not, how can I tell my friend why they are similar? There are many versions of BASIC (Beginners All-Purpose Symbolic Instruction Code) (or something like that). What most have in common with Python (and a lot of other programming languages) is: variables of various data types statements expressions with numeric, string, relational and boolean operations sequential execution control structures for conditionals and loops subroutines input/output arrays some BASIC versions also add exception handling an attempt at OO Python differs in the use of indentation to convey control structure dictionaries object-oriented to the max builtin object methods all items are objects all objects may be dynamically altered object properties may be added anytime modules big library of modules and many more Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050801/2b83b8cf/attachment.htm From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 07:41:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 Aug 2005 22:41:58 -0700 (PDT) Subject: [Tutor] I need advice. In-Reply-To: Message-ID: On Mon, 1 Aug 2005, Nathan Pinno wrote: > I want to write a program that will convert time in any other time zone > to my time zone. Would it be better to use the Python time molecule or > just a whole bunch of if statements? Hi Nathan, I'd recommend looking at the 'datetime' Python module. Getting this stuff right is hard, so unless you really want to learn how time conversions work, take advantage of the library. There's something there that does do time zones: http://www.python.org/doc/lib/datetime-tzinfo.html http://www.python.org/doc/lib/tzinfo-examples.txt Good luck! From cyresse at gmail.com Tue Aug 2 07:44:57 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 2 Aug 2005 17:44:57 +1200 Subject: [Tutor] QUESTION In-Reply-To: References: Message-ID: This link - http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi straight from the python.org website is for a Windows installer. May I also recommend this - http://wiki.python.org/moin/BeginnersGuide The Python Beginner's Guide? Good luck, Liam Clarke On 8/2/05, Jane MUIRI wrote: > > Hi! > I'd like to know what kind of Python I can download. I've tried but in > vain! > My computer is windows xp servixe pack 1, version 2002. > Please, tell me what to do. > Jane. > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/107b3f32/attachment.htm From falcon3166 at hotmail.com Tue Aug 2 08:02:06 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 2 Aug 2005 00:02:06 -0600 Subject: [Tutor] I need advice. References: Message-ID: I forgot to tell that I use Python 2.2.3. When I first got Python, I got 2.4.1, but it refused to run the second time. So I went and got 2.2.3. Your answer would make sense if I had 2.4.1, but I don't. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Monday, August 01, 2005 11:41 PM Subject: Re: [Tutor] I need advice. > > > On Mon, 1 Aug 2005, Nathan Pinno wrote: > >> I want to write a program that will convert time in any other time zone >> to my time zone. Would it be better to use the Python time molecule or >> just a whole bunch of if statements? > > Hi Nathan, > > I'd recommend looking at the 'datetime' Python module. Getting this stuff > right is hard, so unless you really want to learn how time conversions > work, take advantage of the library. There's something there that does do > time zones: > > http://www.python.org/doc/lib/datetime-tzinfo.html > http://www.python.org/doc/lib/tzinfo-examples.txt > > Good luck! > > From alan.gauld at freenet.co.uk Tue Aug 2 09:29:50 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 08:29:50 +0100 Subject: [Tutor] Question References: Message-ID: <056d01c59733$f7b863f0$8eaa8651@xp> > Just curious to wonder if Python can be used to write a > program to check an HTTP mail server for mail, Yes, you would probably use the urllib module for that. > and check more than one server, Yes that would be a fairly typical use for Python as a web client. > even if they are using different proxies, > i.e. HTTP for one and SMTP for the other. Proxies are servers that hide the real server, they act as pass through servers either to filter or cache the data or to protect the recipient or sender. http and smtp are protocols not proxies. Python can deal with multiple protocols fairly easily - there are even modules specifically for each but dealing with proxies is more difficult, it will rely on the proxies working like regular servers - which they should! But trying to access the real server behind the proxy may be impossible. Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee From alan.gauld at freenet.co.uk Tue Aug 2 09:36:16 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 08:36:16 +0100 Subject: [Tutor] Question about BASIC and Python References: Message-ID: <058f01c59734$ddca8da0$8eaa8651@xp> > I had a co-worker say to me at work that Python was related > to or based upon BASIC. Is this true, and if not, how can I > tell my friend why they are similar? Both Python and BASIC are interpreted languages intended to be used (amongst other things) to learn how to program. There the similarity ends. Python is very different to BASIC. Its different in the way it is interpreted, in the structure of the programs, the way functions operate, the type system, in fact just about every conceivable way. There are more similarities between Visual Basic - which is very different to the original BASIC - and Python, but they are still significantly different languages. Thats why I use VBScript (a lightweight VB) as a comparison with Python in my tutor - to illustrate how a *different* language does the same thing. Take a look at some of the topics in my tutor to see the differences. If Python is based on any other language its probably Lisp! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 2 09:43:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 08:43:21 +0100 Subject: [Tutor] I've run into a jam on the exercise on file I/O References: Message-ID: <059901c59735$db8da080$8eaa8651@xp> > What if I were to use ID's for the students and use the ID's as the > sequence > index, and link the students and their grades to the IDs? Its not necessary for what you are doing but it's how you'd normally do it in a relational database, so if you ever needed to turn your file based program into a full blown database then using IDs would actually help! The other thing you could do is hold all the data for a single student in one structure. Thus instead of having lots of lists all linked by a common index (or ID) you have one collection of students (probably a dictionary keyed by name) each with all of its own data. This involves a more complex data structure and is a move in the direction of object oriented programming but without actual classes and objects being involved. This might also allow you to use the shelve moduile to save/restore your data to file easily. Just a thought, Alan G. From alan.gauld at freenet.co.uk Tue Aug 2 09:47:00 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 08:47:00 +0100 Subject: [Tutor] I need advice. References: Message-ID: <05a501c59736$5dadb320$8eaa8651@xp> > I want to write a program that will convert time in any other > time zone to my time zone. This is a deceptively complex task. There are around 40 timezones varying by anything from 15 minutes to 2 hours. And some places change timezone throughout the year. Others have multiple daylight saving dates etc etc. > Would it be better to use the Python time molecule Use the force Luke... If a standrad module exists then its almost certain that more thought and debugging has gone into it than you want to expend! Use what's there and tweak it to suit your needs. HTH, Alan G. From alan.gauld at freenet.co.uk Tue Aug 2 11:12:28 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 10:12:28 +0100 Subject: [Tutor] I need advice. References: Message-ID: <05db01c59742$4e8a9d70$8eaa8651@xp> > I forgot to tell that I use Python 2.2.3. When I first got Python, I > got > 2.4.1, but it refused to run the second time. So I went and got > 2.2.3. Your answer would make sense if I had 2.4.1, but I don't. Version 2.3 should work and has the datetime stuff I think - just checked and it does... But 2.4 should work too, although I confess I haven't tried 2.4 yet except for cygwin. So it might be worth having another go at installing 2.4. Alan G. From alan.gauld at freenet.co.uk Tue Aug 2 11:08:48 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 10:08:48 +0100 Subject: [Tutor] QUESTION References: Message-ID: <05cd01c59741$cd714c70$8eaa8651@xp> Hi Jane, > I'd like to know what kind of Python I can download. I've tried but > in vain! > My computer is windows xp servixe pack 1, version 2002. There are two main possibilities, either the generuc Python designed for any computer or the ActiveSTate vesion witch is the generic version with some Windows specifics added in. Since you are on Windows I'd recommend the ActiveState version: http://www.activestate.com/Products/ActivePython/ However it doesn't seem to work for me using Firefox - I suspect you need IE... So the alternative is the generic Python site: http://www.python.org/download/ Just click on the Windows installer Python 2.4.1 Windows installer (Windows binary -- does not include source) That should download an executable file to your computer. (Make a note of where it gets stored!) Execute that file and Python will be installed on your PC. You will find a new menu under Start->Programs Within that menu start off with "Python GUI" or "IDLE" or something similar - they keep changing the exact wording... When you wind up with a window containing a nearly blank screen and a >>> prompt, congratulations! you have started Python and you can start working your way through one of the non programmers tutorials - I am assuming you are a non programmer? HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From damien.gouteux at gmail.com Tue Aug 2 11:20:32 2005 From: damien.gouteux at gmail.com (Damien) Date: Tue, 02 Aug 2005 11:20:32 +0200 Subject: [Tutor] mailman In-Reply-To: References: Message-ID: <42EF3AE0.20907@gmail.com> Mohammad Moghimi a ?crit : > [...] > checking that Python has a working distutils... configure: error: > > ***** Distutils is not available or is incomplete for /usr/bin/python > ***** If you installed Python from RPM (or other package manager) > ***** be sure to install the -devel package, or install Python > ***** from source. See README.LINUX for details > > I downloaded Distutil from python.org > http://www.python.org/sigs/distutils-sig/download/Distutils-1.0.2.tar.gz > > I wanted to install this one but I got another error message in running > python setup.py install > > Traceback (most recent call last): > File "setup.py", line 30, in ? > packages = ['distutils', 'distutils.command'], > File > "/home/soccer/mohammad/python/Distutils-1.0.2/distutils/core.py", line > 101, in setup > _setup_distribution = dist = klass(attrs) > File > "/home/soccer/mohammad/python/Distutils-1.0.2/distutils/dist.py", line > 130, in __init__ > setattr(self, method_name, getattr(self.metadata, method_name)) > AttributeError: DistributionMetadata instance has no attribute > 'get___doc__' > > How can I solve this problem?! > -- Mohammad Hi all, This problem is not about mailman, but about the Distutils. I have the same bug on Windows. It'is very boring because py2exe needs the distutils. The bug needs to be fixed manually in the source of the distutils in : "distutils/dist.py", line 130, in __init__" The bug is easy to fix (I will post the solution later, if I can found it). I hope this information will help you. Nobody else has this bug with the Distutils ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/39ae039f/attachment.htm From kent37 at tds.net Tue Aug 2 13:06:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Aug 2005 07:06:32 -0400 Subject: [Tutor] terminology question In-Reply-To: <1122958325.42eefbf5854c9@www.paradise.net.nz> References: <6.2.1.2.2.20050801213512.03bbae30@rcblue.com> <1122958325.42eefbf5854c9@www.paradise.net.nz> Message-ID: <42EF53B8.30102@tds.net> jfouhy at paradise.net.nz wrote: > Quoting Dick Moores : > > >>Why are list comprehensions called that? > > > Because that's what they're called in Haskell, I guess.. > > It's historical, based on the term "set comprehension" from mathematics, also > known as "set builder notation": http://en.wikipedia.org/wiki/Set_comprehension The Wikipedia page on "list comprehension" explicitly makes the connection to "set comprehension" and shows how the math notation and Haskell syntax resemble each other. http://en.wikipedia.org/wiki/List_comprehension Kent From python at kapitalisten.no Tue Aug 2 15:12:11 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 2 Aug 2005 15:12:11 +0200 (CEST) Subject: [Tutor] Corrupt files Message-ID: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> Hello. I have created a program that automatically downloads some files I need. It can be .zip, .jpg, .mpg or .txt. However, a lot of the time urlretrieve downloads the file, gives no error, but the downloaded file is corrupted. I use a simple check for the size of the file. If it is way too small, I automatically remove it. The files are ok on the server. Is there some function/modulte that checks a files integrity wheter or not the file is corrupt or not? Thanks in advance. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From sunny.tired at gmail.com Tue Aug 2 15:40:31 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Tue, 2 Aug 2005 09:40:31 -0400 Subject: [Tutor] Color text in Text widget In-Reply-To: References: <8171b61605080112356c1264ab@mail.gmail.com> Message-ID: <8171b616050802064017491783@mail.gmail.com> Thanks. Its works very well. Santosh. On 8/1/05, Jorge Louis de Castro wrote: > I found a way to do it but I'm not sure it is the cleanest. Maybe someone > else on this list can offer a better solution. > > I use the text's configuration to define tags that I apply to sections of > the text. For example: > > txtBox = Text(self, width=80, height=20) > # configuration for red > txtBox.tag_config("r", foreground="red") > # configuration for blue > txtBox.tag_config("b", foreground="blue") > > txtBox.insert(END,"I am red ", "r") > txtBox.insert(END,"and I am blue\n", "b") > > Hope that helps > jorge > > >From: sunny sunny > >To: tutor at python.org > >Subject: [Tutor] Color text in Text widget > >Date: Mon, 1 Aug 2005 15:35:52 -0400 > > > >Hi all, > > > >How do I add color to the text in the Text widget? I tried using the > >ASCII sequence but it didnt work. > > > >For example, I want to add: > > This is red , but this is blue > > > >Thanks. > >Santosh. > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > From damien.gouteux at gmail.com Tue Aug 2 16:11:20 2005 From: damien.gouteux at gmail.com (Damien) Date: Tue, 02 Aug 2005 16:11:20 +0200 Subject: [Tutor] Directory or File ? Message-ID: <42EF7F08.1060808@gmail.com> Hi all, I want to know if a file is a directory or a simple file. I have done a little ugly script : # i is my filename, os is imported old = os.getcwd() try: chdir(i) is_dir = True except: is_dir = False os.chdir(old) return is_dir But maybe there is a better way ? If you know a better way, please tell me. Thanks, Damien G. From kent37 at tds.net Tue Aug 2 16:21:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Aug 2005 10:21:10 -0400 Subject: [Tutor] Directory or File ? In-Reply-To: <42EF7F08.1060808@gmail.com> References: <42EF7F08.1060808@gmail.com> Message-ID: <42EF8156.4080704@tds.net> Damien wrote: > Hi all, > I want to know if a file is a directory or a simple file. Look at os.path.isdir() Kent > I have done a little ugly script : > # i is my filename, os is imported > old = os.getcwd() > try: > chdir(i) > is_dir = True > except: > is_dir = False > os.chdir(old) > return is_dir > > But maybe there is a better way ? > If you know a better way, please tell me. > > Thanks, > Damien G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kraus at hagen-partner.de Tue Aug 2 16:27:19 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 02 Aug 2005 16:27:19 +0200 Subject: [Tutor] Directory or File ? In-Reply-To: <42EF7F08.1060808@gmail.com> References: <42EF7F08.1060808@gmail.com> Message-ID: Damien wrote: > Hi all, > I want to know if a file is a directory or a simple file. > I have done a little ugly script : > # i is my filename, os is imported > old = os.getcwd() > try: > chdir(i) > is_dir = True > except: > is_dir = False > os.chdir(old) > return is_dir > > But maybe there is a better way ? > If you know a better way, please tell me. > > Thanks, > Damien G. Use os.path.isdir: http://python.org/doc/2.4.1/lib/module-os.path.html#l2h-1739 HTH, Wolfram From damien.gouteux at gmail.com Tue Aug 2 18:00:07 2005 From: damien.gouteux at gmail.com (Damien) Date: Tue, 02 Aug 2005 18:00:07 +0200 Subject: [Tutor] Directory or File ? In-Reply-To: <42EF8156.4080704@tds.net> References: <42EF7F08.1060808@gmail.com> <42EF8156.4080704@tds.net> Message-ID: <42EF9887.1070307@gmail.com> Ok, sorry. In the future, I will look more closely the module before sending my question. Thanks. Kent Johnson a ?crit : >Damien wrote: > > >>Hi all, >>I want to know if a file is a directory or a simple file. >> >> > >Look at os.path.isdir() > >Kent > > > >>I have done a little ugly script : >># i is my filename, os is imported >>old = os.getcwd() >>try: >> chdir(i) >> is_dir = True >>except: >> is_dir = False >>os.chdir(old) >>return is_dir >> >>But maybe there is a better way ? >>If you know a better way, please tell me. >> >>Thanks, >>Damien 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 > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/b0b6ad7c/attachment.htm From sunny.tired at gmail.com Tue Aug 2 18:10:59 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Tue, 2 Aug 2005 12:10:59 -0400 Subject: [Tutor] time.sleep() error Message-ID: <8171b616050802091047f03386@mail.gmail.com> Hi all, I am using time.sleep to stop my program execution for some time. I have imported time and am able to use it sucessfully in the main program. However if I use it in any function I get the following error: the time.sleep(1) command generates this error : TypeError : 'int' object is not callable I have tried to add import time after the function definition, it still does not work. Please help. Thanks. Santosh From kent37 at tds.net Tue Aug 2 18:24:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Aug 2005 12:24:15 -0400 Subject: [Tutor] time.sleep() error In-Reply-To: <8171b616050802091047f03386@mail.gmail.com> References: <8171b616050802091047f03386@mail.gmail.com> Message-ID: <42EF9E2F.8070703@tds.net> sunny sunny wrote: > Hi all, > > I am using time.sleep to stop my program execution for some time. I > have imported time and am able to use it sucessfully in the main > program. > > However if I use it in any function I get the following error: > > the time.sleep(1) command generates this error : > TypeError : 'int' object is not callable > > I have tried to add import time after the function definition, it > still does not work. Please help. It looks like somehow the name time.sleep has been bound to an integer. Please post the code and the full error trace. Kent From sunny.tired at gmail.com Tue Aug 2 18:27:27 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Tue, 2 Aug 2005 12:27:27 -0400 Subject: [Tutor] time.sleep() error In-Reply-To: <8171b616050802091047f03386@mail.gmail.com> References: <8171b616050802091047f03386@mail.gmail.com> Message-ID: <8171b61605080209272307d93d@mail.gmail.com> Some additional information: I am calling this function from a thread and I get the error. However if I call the function from the main program it works fine. I am using thread.start_new_thread() to start the thread. Thanks. Santosh. On 8/2/05, sunny sunny wrote: > Hi all, > > I am using time.sleep to stop my program execution for some time. I > have imported time and am able to use it sucessfully in the main > program. > > However if I use it in any function I get the following error: > > the time.sleep(1) command generates this error : > TypeError : 'int' object is not callable > > I have tried to add import time after the function definition, it > still does not work. Please help. > > Thanks. > Santosh > From geon at post.cz Tue Aug 2 18:35:21 2005 From: geon at post.cz (geon) Date: Tue, 02 Aug 2005 18:35:21 +0200 Subject: [Tutor] time.sleep() error In-Reply-To: <8171b616050802091047f03386@mail.gmail.com> References: <8171b616050802091047f03386@mail.gmail.com> Message-ID: <42EFA0C9.5050908@post.cz> sunny sunny napsal(a): >Hi all, > >I am using time.sleep to stop my program execution for some time. I >have imported time and am able to use it sucessfully in the main >program. > >However if I use it in any function I get the following error: > >the time.sleep(1) command generates this error : >TypeError : 'int' object is not callable > > > Dont you actually have something like this?: from time import * # somewhere you use sleep like this sleep=10 # and then sleep(1) # you get: # sleep(1) #TypeError: 'int' object is not callable In this case you "overwrite" the original function sleep() with your/my variable sleep.... Solution: rename your/my variable sleep to f.e. notAwake=10 :-) -- geon From meesters at uni-mainz.de Tue Aug 2 18:52:11 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 2 Aug 2005 18:52:11 +0200 Subject: [Tutor] fourier transform Message-ID: <5cb658357624b3fb3a517573bc53947e@uni-mainz.de> Hi Pawel Kraszewski wrote: > 4. The answer is symmetrical - usually you take only half of it. I > don't > remember the exact difference between the halves, but you may find it > in any > article on FFT. The real part is identical the imaginary part has the opposite sign ("same amplitude, opposite phase"). Jeff Peery wrote: > thanks for the help. I think I'm understanding this a bit better. > although I still don't completely understand the output. here is an > example... for the input I have 1024 samples taken from a 1 Hz square > wave with amplitude = 1. for the output I would expect an infinite > number of frequencies. the output from FFT.fft(myData).real is this: > > . > . > . > -0.498 1 > 0.0 2 > -0.498 3 > 0.0 4 > -0.498 5 > 0.0 6 > -0.498 7 > 0.0 8 Frankly, I don't understand this. After your description I thought your input is like "array([0, 1, 0, ..., 1, 0, 1])". But this can't be. Could you show us how exactly your input array looks like? And how do we have to read your output? Is this a 1d-array? What do the two numbers per line mean? Cheers Christian PS Sorry for the late reply. From falcon3166 at hotmail.com Tue Aug 2 19:16:37 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 2 Aug 2005 11:16:37 -0600 Subject: [Tutor] I need advice. References: <05a501c59736$5dadb320$8eaa8651@xp> Message-ID: I think I'll leave this one for someone else. I got too confused too quick. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Tutor mailing list" Sent: Tuesday, August 02, 2005 1:47 AM Subject: Re: [Tutor] I need advice. >> I want to write a program that will convert time in any other time zone >> to my time zone. > > This is a deceptively complex task. There are around 40 timezones > varying by anything from 15 minutes to 2 hours. And some places change > timezone throughout the year. Others have multiple daylight saving dates > etc etc. > >> Would it be better to use the Python time molecule > > Use the force Luke... > If a standrad module exists then its almost certain that more thought and > debugging has gone into it than you want to expend! > Use what's there and tweak it to suit your needs. > > HTH, > > Alan G. > From menacing_imp at hotmail.com Tue Aug 2 19:21:49 2005 From: menacing_imp at hotmail.com (Greg Janczak) Date: Tue, 02 Aug 2005 12:21:49 -0500 Subject: [Tutor] (no subject) Message-ID: This is a totally unrelated question but does anyone know a good free iso image burner? greg _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kristian at zimmer428.net Tue Aug 2 19:34:02 2005 From: kristian at zimmer428.net (Kristian Rink) Date: Tue, 02 Aug 2005 19:34:02 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <42EFAE8A.2090504@zimmer428.net> Greg Janczak schrieb: > This is a totally unrelated question but does anyone know a good free iso > image burner? Well, what don't you like about cdrecord? Otherwise, specifying which operating system you're intending to use this on would be quite a good idea. ;) Cheers, Kris -- "Sei Du selbst die Ver?nderung, die Du Dir w?nschst f?r diese Welt." (Gandhi) -| Kristian Rink icq# 48874445 jab# kawazu at jabber.ccc.de -| http://www.zimmer428.net ** http://www.fotolog.net/kawazu From geon at post.cz Tue Aug 2 20:05:36 2005 From: geon at post.cz (geon) Date: Tue, 02 Aug 2005 20:05:36 +0200 Subject: [Tutor] time.sleep() error In-Reply-To: <42EFA0C9.5050908@post.cz> References: <8171b616050802091047f03386@mail.gmail.com> <42EFA0C9.5050908@post.cz> Message-ID: <42EFB5F0.7090306@post.cz> geon napsal(a): >sunny sunny napsal(a): > > > >>Hi all, >> >>I am using time.sleep to stop my program execution for some time. I >>have imported time and am able to use it sucessfully in the main >>program. >> >>However if I use it in any function I get the following error: >> >>the time.sleep(1) command generates this error : >>TypeError : 'int' object is not callable >> >> >> >> >> > >Dont you actually have something like this?: > >from time import * > ># somewhere you use sleep like this >sleep=10 > ># and then >sleep(1) > ># you get: ># sleep(1) >#TypeError: 'int' object is not callable > >In this case you "overwrite" the original function sleep() with your/my >variable sleep.... >Solution: rename your/my variable sleep to f.e. notAwake=10 :-) > > > Solution2: do not use from time import *. Prefer import time. Now you know why :-) Its not a waste of time still to rewrite you code in this way. -- geon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/264ed36d/attachment.htm From falcon3166 at hotmail.com Tue Aug 2 20:08:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 2 Aug 2005 12:08:36 -0600 Subject: [Tutor] Question about resetting values Message-ID: I am writing a Blackjack program, and was wondering how to reset the values to zero, e.g. cash = 0? Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/c3063c30/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050802/c3063c30/PinnoNathanPaul.vcf From mjekl at clix.pt Tue Aug 2 15:28:43 2005 From: mjekl at clix.pt (Miguel Lopes) Date: Tue, 02 Aug 2005 14:28:43 +0100 Subject: [Tutor] JBUS and Python which way Message-ID: <20050802132843.14832.qmail@maboque.srv.clix.pt> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20050802/ba083cfc/attachment.diff From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 20:35:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Aug 2005 11:35:58 -0700 (PDT) Subject: [Tutor] Corrupt files In-Reply-To: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> Message-ID: On Tue, 2 Aug 2005, [iso-8859-1] Øyvind wrote: > Is there some function/modulte that checks a files integrity wheter or > not the file is corrupt or not? Hello! A general technique that people have used before is to provide file "checksums" of large files. These checksums can be used to verify that the file passed through fine over the wire. As a concrete example, the large Python 2.41 installer file is paired with a "md5" checksum, listed below under "Files, MD5 checksums, signatures, and sizes:" at the bottom of: http://www.python.org/2.4.1/ So the idea is to take the downloaded file, run the standard 'md5sum' checksum program, and see that the checksums match the published one. (If you don't have this utility: http://www.python.org/2.4.1/md5sum.py) If the checksums don't match up, there's definitely file corruption. Hope this helps! From geon at post.cz Tue Aug 2 20:43:03 2005 From: geon at post.cz (geon) Date: Tue, 02 Aug 2005 20:43:03 +0200 Subject: [Tutor] Corrupt files In-Reply-To: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> References: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> Message-ID: <42EFBEB7.4010908@post.cz> ?yvind napsal(a): >Hello. > >I have created a program that automatically downloads some files I need. >It can be .zip, .jpg, .mpg or .txt. However, a lot of the time urlretrieve >downloads the file, gives no error, but the downloaded file is corrupted. >I use a simple check for the size of the file. If it is way too small, I >automatically remove it. > remove it and try to download it again, lets say , 3times until you get correct copy... >The files are ok on the server. > >Is there some function/modulte that checks a files integrity wheter or not >the file is corrupt or not? > > > Until you are provided with, say, md5 checksum, there is no other way than comparing sizes, I think ... -- geon From eafcub at jagua.cfg.sld.cu Tue Aug 2 20:33:07 2005 From: eafcub at jagua.cfg.sld.cu (Enrique Acosta Figueredo) Date: Tue, 2 Aug 2005 14:33:07 -0400 (CDT) Subject: [Tutor] For Damien In-Reply-To: References: Message-ID: <2630.169.158.166.215.1123007587.squirrel@jagua.cfg.sld.cu> if os.path.isfile(i): ... print "file" ... else: ... print "directory" ... > 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: terminology question (Kent Johnson) > 2. Corrupt files (?yvind) > 3. Re: Color text in Text widget (sunny sunny) > 4. Directory or File ? (Damien) > 5. Re: Directory or File ? (Kent Johnson) > 6. Re: Directory or File ? (Wolfram Kraus) > 7. Re: Directory or File ? (Damien) > 8. time.sleep() error (sunny sunny) > 9. Re: time.sleep() error (Kent Johnson) > 10. Re: time.sleep() error (sunny sunny) > 11. Re: time.sleep() error (geon) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 02 Aug 2005 07:06:32 -0400 > From: Kent Johnson > Subject: Re: [Tutor] terminology question > Cc: "tutor at python.org" > Message-ID: <42EF53B8.30102 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > jfouhy at paradise.net.nz wrote: >> Quoting Dick Moores : >> >> >>>Why are list comprehensions called that? >> >> >> Because that's what they're called in Haskell, I guess.. >> >> It's historical, based on the term "set comprehension" from mathematics, >> also >> known as "set builder notation": >> http://en.wikipedia.org/wiki/Set_comprehension > > The Wikipedia page on "list comprehension" explicitly makes the connection > to "set comprehension" and shows how the math notation and Haskell syntax > resemble each other. > http://en.wikipedia.org/wiki/List_comprehension > > Kent > > > > ------------------------------ > > Message: 2 > Date: Tue, 2 Aug 2005 15:12:11 +0200 (CEST) > From: ?yvind > Subject: [Tutor] Corrupt files > To: tutor at python.org > Message-ID: <45522.193.71.38.142.1122988331.squirrel at mail.sporck.net> > Content-Type: text/plain;charset=iso-8859-1 > > Hello. > > I have created a program that automatically downloads some files I need. > It can be .zip, .jpg, .mpg or .txt. However, a lot of the time urlretrieve > downloads the file, gives no error, but the downloaded file is corrupted. > I use a simple check for the size of the file. If it is way too small, I > automatically remove it. The files are ok on the server. > > Is there some function/modulte that checks a files integrity wheter or not > the file is corrupt or not? > > Thanks in advance. > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > > > ------------------------------ > > Message: 3 > Date: Tue, 2 Aug 2005 09:40:31 -0400 > From: sunny sunny > Subject: Re: [Tutor] Color text in Text widget > To: jorge at bcs.org.uk > Cc: tutor at python.org > Message-ID: <8171b616050802064017491783 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Thanks. > Its works very well. > Santosh. > > On 8/1/05, Jorge Louis de Castro wrote: >> I found a way to do it but I'm not sure it is the cleanest. Maybe >> someone >> else on this list can offer a better solution. >> >> I use the text's configuration to define tags that I apply to sections >> of >> the text. For example: >> >> txtBox = Text(self, width=80, height=20) >> # configuration for red >> txtBox.tag_config("r", foreground="red") >> # configuration for blue >> txtBox.tag_config("b", foreground="blue") >> >> txtBox.insert(END,"I am red ", "r") >> txtBox.insert(END,"and I am blue\n", "b") >> >> Hope that helps >> jorge >> >> >From: sunny sunny >> >To: tutor at python.org >> >Subject: [Tutor] Color text in Text widget >> >Date: Mon, 1 Aug 2005 15:35:52 -0400 >> > >> >Hi all, >> > >> >How do I add color to the text in the Text widget? I tried using the >> >ASCII sequence but it didnt work. >> > >> >For example, I want to add: >> > This is red , but this is blue >> > >> >Thanks. >> >Santosh. >> >_______________________________________________ >> >Tutor maillist - Tutor at python.org >> >http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > ------------------------------ > > Message: 4 > Date: Tue, 02 Aug 2005 16:11:20 +0200 > From: Damien > Subject: [Tutor] Directory or File ? > To: tutor at python.org > Message-ID: <42EF7F08.1060808 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi all, > I want to know if a file is a directory or a simple file. > I have done a little ugly script : > # i is my filename, os is imported > old = os.getcwd() > try: > chdir(i) > is_dir = True > except: > is_dir = False > os.chdir(old) > return is_dir > > But maybe there is a better way ? > If you know a better way, please tell me. > > Thanks, > Damien G. > > > ------------------------------ > > Message: 5 > Date: Tue, 02 Aug 2005 10:21:10 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Directory or File ? > Cc: tutor at python.org > Message-ID: <42EF8156.4080704 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Damien wrote: >> Hi all, >> I want to know if a file is a directory or a simple file. > > Look at os.path.isdir() > > Kent > >> I have done a little ugly script : >> # i is my filename, os is imported >> old = os.getcwd() >> try: >> chdir(i) >> is_dir = True >> except: >> is_dir = False >> os.chdir(old) >> return is_dir >> >> But maybe there is a better way ? >> If you know a better way, please tell me. >> >> Thanks, >> Damien G. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > ------------------------------ > > Message: 6 > Date: Tue, 02 Aug 2005 16:27:19 +0200 > From: Wolfram Kraus > Subject: Re: [Tutor] Directory or File ? > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii; format=flowed > > Damien wrote: >> Hi all, >> I want to know if a file is a directory or a simple file. >> I have done a little ugly script : >> # i is my filename, os is imported >> old = os.getcwd() >> try: >> chdir(i) >> is_dir = True >> except: >> is_dir = False >> os.chdir(old) >> return is_dir >> >> But maybe there is a better way ? >> If you know a better way, please tell me. >> >> Thanks, >> Damien G. > > Use os.path.isdir: > http://python.org/doc/2.4.1/lib/module-os.path.html#l2h-1739 > > HTH, > Wolfram > > > > ------------------------------ > > Message: 7 > Date: Tue, 02 Aug 2005 18:00:07 +0200 > From: Damien > Subject: Re: [Tutor] Directory or File ? > To: Kent Johnson , Wolfram Kraus > > Cc: tutor at python.org > Message-ID: <42EF9887.1070307 at gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Ok, sorry. In the future, I will look more closely the module before > sending my question. > Thanks. > > Kent Johnson a ?crit : > >>Damien wrote: >> >> >>>Hi all, >>>I want to know if a file is a directory or a simple file. >>> >>> >> >>Look at os.path.isdir() >> >>Kent >> >> >> >>>I have done a little ugly script : >>># i is my filename, os is imported >>>old = os.getcwd() >>>try: >>> chdir(i) >>> is_dir = True >>>except: >>> is_dir = False >>>os.chdir(old) >>>return is_dir >>> >>>But maybe there is a better way ? >>>If you know a better way, please tell me. >>> >>>Thanks, >>>Damien 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 >> >> >> > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20050802/b0b6ad7c/attachment-0001.htm > > ------------------------------ > > Message: 8 > Date: Tue, 2 Aug 2005 12:10:59 -0400 > From: sunny sunny > Subject: [Tutor] time.sleep() error > To: tutor at python.org > Message-ID: <8171b616050802091047f03386 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi all, > > I am using time.sleep to stop my program execution for some time. I > have imported time and am able to use it sucessfully in the main > program. > > However if I use it in any function I get the following error: > > the time.sleep(1) command generates this error : > TypeError : 'int' object is not callable > > I have tried to add import time after the function definition, it > still does not work. Please help. > > Thanks. > Santosh > > > ------------------------------ > > Message: 9 > Date: Tue, 02 Aug 2005 12:24:15 -0400 > From: Kent Johnson > Subject: Re: [Tutor] time.sleep() error > Cc: tutor at python.org > Message-ID: <42EF9E2F.8070703 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > sunny sunny wrote: >> Hi all, >> >> I am using time.sleep to stop my program execution for some time. I >> have imported time and am able to use it sucessfully in the main >> program. >> >> However if I use it in any function I get the following error: >> >> the time.sleep(1) command generates this error : >> TypeError : 'int' object is not callable >> >> I have tried to add import time after the function definition, it >> still does not work. Please help. > > It looks like somehow the name time.sleep has been bound to an integer. > Please post the code and the full error trace. > > Kent > > > > ------------------------------ > > Message: 10 > Date: Tue, 2 Aug 2005 12:27:27 -0400 > From: sunny sunny > Subject: Re: [Tutor] time.sleep() error > To: tutor at python.org > Message-ID: <8171b61605080209272307d93d at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Some additional information: > > I am calling this function from a thread and I get the error. > However if I call the function from the main program it works fine. > > I am using thread.start_new_thread() to start the thread. > > Thanks. > Santosh. > > On 8/2/05, sunny sunny wrote: >> Hi all, >> >> I am using time.sleep to stop my program execution for some time. I >> have imported time and am able to use it sucessfully in the main >> program. >> >> However if I use it in any function I get the following error: >> >> the time.sleep(1) command generates this error : >> TypeError : 'int' object is not callable >> >> I have tried to add import time after the function definition, it >> still does not work. Please help. >> >> Thanks. >> Santosh >> > > > ------------------------------ > > Message: 11 > Date: Tue, 02 Aug 2005 18:35:21 +0200 > From: geon > Subject: Re: [Tutor] time.sleep() error > To: Tutor Python > Message-ID: <42EFA0C9.5050908 at post.cz> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > sunny sunny napsal(a): > >>Hi all, >> >>I am using time.sleep to stop my program execution for some time. I >>have imported time and am able to use it sucessfully in the main >>program. >> >>However if I use it in any function I get the following error: >> >>the time.sleep(1) command generates this error : >>TypeError : 'int' object is not callable >> >> >> > > Dont you actually have something like this?: > > from time import * > > # somewhere you use sleep like this > sleep=10 > > # and then > sleep(1) > > # you get: > # sleep(1) > #TypeError: 'int' object is not callable > > In this case you "overwrite" the original function sleep() with your/my > variable sleep.... > Solution: rename your/my variable sleep to f.e. notAwake=10 :-) > > -- > geon > > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 18, Issue 16 > ************************************* > > -- > Sistema Antivirus INFOSUR > Mailscanner - www.mailscanner.org > Enrique Acosta Figueredo Programador, Linux User # 391079 (http://counter.li.org) -- Sistema Antivirus INFOSUR Mailscanner - www.mailscanner.org From falcon3166 at hotmail.com Tue Aug 2 20:51:41 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 2 Aug 2005 12:51:41 -0600 Subject: [Tutor] I need advice. References: Message-ID: I am now using Python 2.4.1, but decided to abandon it. It got too confusing too fast. I'm better off writing simple games and apps for now. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: "Tutor mailing list" Sent: Tuesday, August 02, 2005 12:02 AM Subject: Re: [Tutor] I need advice. >I forgot to tell that I use Python 2.2.3. When I first got Python, I got > 2.4.1, but it refused to run the second time. So I went and got 2.2.3. > Your > answer would make sense if I had 2.4.1, but I don't. > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Monday, August 01, 2005 11:41 PM > Subject: Re: [Tutor] I need advice. > > >> >> >> On Mon, 1 Aug 2005, Nathan Pinno wrote: >> >>> I want to write a program that will convert time in any other time zone >>> to my time zone. Would it be better to use the Python time molecule or >>> just a whole bunch of if statements? >> >> Hi Nathan, >> >> I'd recommend looking at the 'datetime' Python module. Getting this >> stuff >> right is hard, so unless you really want to learn how time conversions >> work, take advantage of the library. There's something there that does >> do >> time zones: >> >> http://www.python.org/doc/lib/datetime-tzinfo.html >> http://www.python.org/doc/lib/tzinfo-examples.txt >> >> Good luck! >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From genietdev0 at iol.ie Tue Aug 2 22:11:05 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Tue, 02 Aug 2005 21:11:05 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color Message-ID: <42EFD359.3080607@iol.ie> Hello all of you, I am trying to simply(?) print some text in a print statement as bold (or itlaics or an certain color). How do I do this in python? Browsing the web gives we all kind of soluation, but non seem to work (a lot are related when printing on the web). Say I want to print the text (in the mentioned format): This is bold, red, blue, italics How do I do this in python 2.2 and using IDLE? Thanks for your help. All the best, Victor From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 22:22:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Aug 2005 13:22:13 -0700 (PDT) Subject: [Tutor] Corrupt files (fwd) Message-ID: ---------- Forwarded message ---------- Date: Tue, 2 Aug 2005 22:12:34 +0200 (CEST) From: "[iso-8859-1] Øyvind" To: Danny Yoo Subject: Re: [Tutor] Corrupt files Hello and thank you. I don't really think that will help. The files are mostly smaller ones of for example jpg, avi, txt, doc and xls files. It is not published any MD5 checksums. Is there any way to check for example that a jpg file is completed without opening it? Or, is there some way to check the filesize on the server thru http (urlretrieve) and compare with the filesize of the downloaded file? Do you think that would work? Thanks in advance.... > > > On Tue, 2 Aug 2005, [iso-8859-1] Øyvind wrote: > >> Is there some function/modulte that checks a files integrity wheter or >> not the file is corrupt or not? > > Hello! > > A general technique that people have used before is to provide file > "checksums" of large files. These checksums can be used to verify that > the file passed through fine over the wire. > > As a concrete example, the large Python 2.41 installer file is paired with > a "md5" checksum, listed below under "Files, MD5 checksums, signatures, > and sizes:" at the bottom of: > > http://www.python.org/2.4.1/ > > So the idea is to take the downloaded file, run the standard 'md5sum' > checksum program, and see that the checksums match the published one. > (If you don't have this utility: http://www.python.org/2.4.1/md5sum.py) > If the checksums don't match up, there's definitely file corruption. > > > Hope this helps! > > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From alan.gauld at freenet.co.uk Tue Aug 2 22:45:25 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 21:45:25 +0100 Subject: [Tutor] Question about resetting values References: Message-ID: <066201c597a3$1c0266b0$8eaa8651@xp> > I am writing a Blackjack program, and was wondering how to > reset the values to zero, e.g. cash = 0? Yes, that's how you do it. Now what is the bit you don't understand? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 2 22:48:53 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 2 Aug 2005 21:48:53 +0100 Subject: [Tutor] Corrupt files References: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> <42EFBEB7.4010908@post.cz> Message-ID: <066e01c597a3$9859c2d0$8eaa8651@xp> >>I have created a program that automatically downloads some files I >>need. >>It can be .zip, .jpg, .mpg or .txt. However, a lot of the time >>urlretrieve >>downloads the file, gives no error, but the downloaded file is >>corrupted. >>I use a simple check for the size of the file. If it is way too >>small, I >>automatically remove it. Is it possible you are downloading a binary file as a text file? If so the EOF character may be present and this is what truncates the file. A sign that this is the problem is if the same file always stops after the same number of bytes. I've never used urlretrieve but its a common problewm with ftp, and I assume url is the same. Is there a flag/parameter you can set to fetch in binary mode? Just guessing, Alan G. From zmerch at 30below.com Tue Aug 2 22:56:25 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Tue, 02 Aug 2005 16:56:25 -0400 Subject: [Tutor] Corrupt files In-Reply-To: <42EFBEB7.4010908@post.cz> References: <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> <45522.193.71.38.142.1122988331.squirrel@mail.sporck.net> Message-ID: <5.1.0.14.2.20050802164047.03a1dac8@mail.30below.com> Rumor has it that geon may have mentioned these words: >?yvind napsal(a): > > >Hello. > > > >I have created a program that automatically downloads some files I need. > >It can be .zip, .jpg, .mpg or .txt. However, a lot of the time urlretrieve > >downloads the file, gives no error, but the downloaded file is corrupted. > >I use a simple check for the size of the file. If it is way too small, I > >automatically remove it. > > > >remove it and try to download it again, lets say , 3times until you get >correct copy... Or, depending on it's extension, try to open the newly downloaded file with the corresponding Python extension, i.e. (.jpg|.gif|.png) try to open with PIL[1], .zip files with the python zipfile module, etc. I *think* there's modules for .mpgs and maybe .avi's... but .txt files might be tough to authenticate, as there's no actual 'file format.' This python pseudocode might explain more: =-=-=-=-=-=-= snip here =-=-=-=-=-=-= def openzip(filename): import zipfile try: filebuf = zipfile.open(filename) except: return "Error 99: cannot open file; corrupted zipfile." filebuf.close() return None if __name__ == '__main__': if filename[:-4] == '.zip': retcode = openzip(filename) if retcode != None: print "Corrupt File - Try to download again!" =-=-=-=-=-=-= snip here =-=-=-=-=-=-= Just put an 'openzip' or 'openjpg' type of function for each type of file you'll need to authenticate. [[ This code will *not* run -- it certainly won't run in Eudora (where it's being typed), so it's only for showing the general idea... YMMV, UAYOR, etc. ;-) ]] Hope this helps, Roger "Merch" Merchberger [1] PIL == Python Image Library; it will open almost any type of static graphic image available. -- Roger "Merch" Merchberger | "Bugs of a feather flock together." sysadmin, Iceberg Computers | Russell Nelson zmerch at 30below.com | From greg.lindstrom at novasyshealth.com Tue Aug 2 22:48:06 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 02 Aug 2005 15:48:06 -0500 Subject: [Tutor] Deleting an entry from a dictionary Message-ID: <42EFDC06.7000105@novasyshealth.com> Hello- This must be simple, but for the life of me I can't figure out how to delete an entry from a dictionary. For example, meals = {} meals['breakfast'] = 'slimfast' meals['lunch'] = 'slimfast' meals['dinner'] = 'something sensible' How do I eliminate 'lunch' from the dictionary so that I only have 'breakfast' and 'dinner'? Thanks! --greg From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 23:12:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Aug 2005 14:12:23 -0700 (PDT) Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <42EFDC06.7000105@novasyshealth.com> Message-ID: On Tue, 2 Aug 2005, Greg Lindstrom wrote: > This must be simple, but for the life of me I can't figure out how to > delete an entry from a dictionary. For example, > > meals = {} > meals['breakfast'] = 'slimfast' > meals['lunch'] = 'slimfast' > meals['dinner'] = 'something sensible' > > How do I eliminate 'lunch' from the dictionary so that I only have > 'breakfast' and 'dinner'? Hi Greg, Actually, it isn't obvious at all, so don't be too discouraged. The 'del' statement should do the trick: ###### >>> d = {'a': 'Alpha', 'b' : 'Beta'} >>> del d['a'] >>> d {'b': 'Beta'} ###### Here's a reference list of all the things you can do to a dictionary: http://www.python.org/doc/lib/typesmapping.html Good luck! From adam.jtm30 at gmail.com Tue Aug 2 23:16:30 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 2 Aug 2005 22:16:30 +0100 Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <42EFDC06.7000105@novasyshealth.com> References: <42EFDC06.7000105@novasyshealth.com> Message-ID: meals.pop(key) will do it. Example: >>> meals = {} >>> meals['breakfast'] = 'slimfast' >>> meals['lunch'] = 'slimfast' >>> meals['dinner'] = 'something sensible' >>> meals {'lunch': 'slimfast', 'breakfast': 'slimfast', 'dinner': 'something sensible'} >>> meals.pop("breakfast") 'slimfast' >>> meals {'lunch': 'slimfast', 'dinner': 'something sensible'} On 8/2/05, Greg Lindstrom wrote: > > Hello- > This must be simple, but for the life of me I can't figure out how to > delete an entry from a dictionary. For example, > > meals = {} > meals['breakfast'] = 'slimfast' > meals['lunch'] = 'slimfast' > meals['dinner'] = 'something sensible' > > How do I eliminate 'lunch' from the dictionary so that I only have > 'breakfast' and 'dinner'? > > Thanks! > --greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/f89233db/attachment.htm From dyoo at hkn.eecs.berkeley.edu Tue Aug 2 23:21:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Aug 2005 14:21:56 -0700 (PDT) Subject: [Tutor] print a line in IDLE as bold, italics or a color In-Reply-To: <42EFD359.3080607@iol.ie> Message-ID: On Tue, 2 Aug 2005, Victor Reijs wrote: > I am trying to simply(?) print some text in a print statement as bold > (or itlaics or an certain color). How do I do this in python? Browsing > the web gives we all kind of soluation, but non seem to work (a lot are > related when printing on the web). > > Say I want to print the text (in the mentioned format): This is bold, > red, blue, italics > > How do I do this in python 2.2 and using IDLE? Hi Victor, You may need to open up a special window for doing text displays with some variety. The Tkinter system provides one, which can be opened up like this: ###### import Tkinter txtBox = Text() ###### We had some discussion about this just yesterday, and Jorge Louis de Castro showed how to selectively insert colored text into that txtBox: http://mail.python.org/pipermail/tutor/2005-August/040244.html Hope this helps! From srini_iyyer_bio at yahoo.com Tue Aug 2 23:54:54 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 2 Aug 2005 14:54:54 -0700 (PDT) Subject: [Tutor] substituting empty line with stuff In-Reply-To: Message-ID: <20050802215455.24800.qmail@web53505.mail.yahoo.com> Hello group: I have a file (3339203 lines) that looks like this: (col:1) (col:2) (col:3) AD134KL XXXXX XXXXX Xaaaa Xaaaa Xbbbb Xbbbb AD144KL YYYYY YYYYY Yaaaa Yaaaa Now I have to fill the rows in column 1 with their designated stuff: AD134KL AD134KL XXXXX XXXXX AD134KL Xaaaa Xaaaa AD134KL Xbbbb Xbbbb AD144KL AD144KL YYYYY YYYYY AD144KL Yaaaa Yaaaa My code: f1 = open('xx','r') meat = f1.readlines() mind = [] for i in range(len(meat)): if meat[i].startswith('AD'): mind.append(i) mind = [0,4] for i in range(len(mind)): k = i+1 l = mind[i]+1 j = mind[k]-1 print l,j 1 3 Logic: Now I want to substitute 'AD134KL' between 0 and 4 which is 1,2,and 3. and move on.. After coming to this stage, I lost grip and I do not know what to do.. Can experts help me please. thank you srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Wed Aug 3 00:03:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 Aug 2005 15:03:51 -0700 (PDT) Subject: [Tutor] print a line in IDLE as bold, italics or a color In-Reply-To: <42EFE6C0.7030700@iol.ie> Message-ID: On Tue, 2 Aug 2005, Victor Reijs wrote: > This is in a seperate text box, but I want to have the colors > (bold/italics) in the default IDLE window. [Note: please use Reply-to-all] This will probably be more difficult. I don't believe IDLE itself allows a user's program to set its own fonts and colors within the running IDLE window. I'm sure it's technically possible, but not without some significant hacking at the IDLE interface. From genietdev0 at iol.ie Wed Aug 3 00:49:04 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Tue, 02 Aug 2005 23:49:04 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color In-Reply-To: References: Message-ID: <42EFF860.5070407@iol.ie> Hello Danny, Danny Yoo wrote: >>This is in a seperate text box, but I want to have the colors >>(bold/italics) in the default IDLE window. > > This will probably be more difficult. I don't believe IDLE itself allows > a user's program to set its own fonts and colors within the running IDLE > window. > > I'm sure it's technically possible, but not without some significant > hacking at the IDLE interface. Error messages in IDLE also get a color (red), so it loooks to be standard 'IDLE'/python;-) Also IDEL recognize keywords while typing and changes the color (to orange), so it is quite normal in IDLE... But now; how can user's python program use it? All the best, Victor From jeffpeery at yahoo.com Wed Aug 3 02:03:10 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 2 Aug 2005 17:03:10 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <5cb658357624b3fb3a517573bc53947e@uni-mainz.de> Message-ID: <20050803000310.29809.qmail@web30507.mail.mud.yahoo.com> Hi Christian, sorry for the lack of detail. how about I use a sine wave because I know what the output should look like - amplitude of one at frequency equal to the frequency of the sine wave. one period of a sin wave that cycles at one hertz: period = 1 input = sin(arange(0,64)*3.14159*2/64.0) do the fft: myFFT = FFT.real_fft(myData) the change in time between elements is: delta_time = period/64 inverse of time is the frequency: delta_freq = 1/delta_time print the results: for i in range(1,len(myFFT)): print myFFT[i], delta_freq*i hope this is more clear. from the output I would expect that two spikes appear with amplitude = 1. one spike is the positive frequency (first half of the fft) and another spike is the negative frequency (second half), the first half and second half are symmetrical about the midpoint of the fft. but this is what I get: -8.22612478587e-005 64.0 2.65354186171e-006 128.0 2.65357174311e-006 192.0 2.65358011376e-006 256.0 2.65358370024e-006 320.0 2.65358557785e-006 384.0 2.65358668451e-006 448.0 2.65358739808e-006 512.0 2.65358788076e-006 576.0 2.65358822231e-006 640.0 . . . I don't understand the output amplitudes. they should all be zero except for at one herz it should be one. not sure about the frequency for that matter either. I gotta dig up my math book and figure this out. in the meantime any suggestions for what this is outputing would be greatly appreciated! thanks. Jeff Christian Meesters wrote: Hi Pawel Kraszewski wrote: > 4. The answer is symmetrical - usually you take only half of it. I > don't > remember the exact difference between the halves, but you may find it > in any > article on FFT. The real part is identical the imaginary part has the opposite sign ("same amplitude, opposite phase"). Jeff Peery wrote: > thanks for the help. I think I'm understanding this a bit better. > although I still don't completely understand the output. here is an > example... for the input I have 1024 samples taken from a 1 Hz square > wave with amplitude = 1. for the output I would expect an infinite > number of frequencies. the output from FFT.fft(myData).real is this: > > . > . > . > -0.498 1 > 0.0 2 > -0.498 3 > 0.0 4 > -0.498 5 > 0.0 6 > -0.498 7 > 0.0 8 Frankly, I don't understand this. After your description I thought your input is like "array([0, 1, 0, ..., 1, 0, 1])". But this can't be. Could you show us how exactly your input array looks like? And how do we have to read your output? Is this a 1d-array? What do the two numbers per line mean? Cheers Christian PS Sorry for the late reply. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050802/911477e9/attachment.htm From webdev at matheteuo.org Wed Aug 3 05:45:16 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 2 Aug 2005 23:45:16 -0400 Subject: [Tutor] I need advice. In-Reply-To: <05db01c59742$4e8a9d70$8eaa8651@xp> References: <05db01c59742$4e8a9d70$8eaa8651@xp> Message-ID: <20050802234516.53a464d3@luke.matheteuo.rel> On Tue, 2 Aug 2005 10:12:28 +0100 "Alan G" wrote: > > > I forgot to tell that I use Python 2.2.3. When I first got Python, I > > got > > 2.4.1, but it refused to run the second time. So I went and got > > 2.2.3. Your answer would make sense if I had 2.4.1, but I don't. > > Version 2.3 should work and has the datetime stuff I think > - just checked and it does... > > But 2.4 should work too, although I confess I haven't tried 2.4 yet > except > for cygwin. So it might be worth having another go at installing 2.4. > > Alan G. > > I use 2.4 on the 'Doze box at work. I have no problems with it so far. Of course, I can't install my own RDBMS (they would freak!), but I've managed to get away with Python. :-) I'm running Python 2.3 on my SUSE 9.2 box. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From falcon3166 at hotmail.com Wed Aug 3 08:30:30 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 00:30:30 -0600 Subject: [Tutor] Question about resetting values References: <066201c597a3$1c0266b0$8eaa8651@xp> Message-ID: Never mind all. I was just being stupid as usual. I thought that there might be a Python command for resetting and wanted to find out if that was the case. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Tutor mailing list" Sent: Tuesday, August 02, 2005 2:45 PM Subject: Re: [Tutor] Question about resetting values >> I am writing a Blackjack program, and was wondering how to reset the >> values to zero, e.g. cash = 0? > > Yes, that's how you do it. Now what is the bit you don't understand? > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > From falcon3166 at hotmail.com Wed Aug 3 08:39:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 00:39:28 -0600 Subject: [Tutor] I need advice about which way to go. Message-ID: Hi all, I am writing a poker game and a blackjack game. I was wondering which way would be Python smart and work properly. I am trying to figure out whether or not to use t(n) as a card indicator, when n = randomly drawn number. I could go that way, or code it as t1, t2, t3, etc. Which way is the right and correct way to go? Also for blackjack, I want to use it as playertotal = playertotal + n, and computertotal = computertotal + n. or 1,2,3, etc. Which is better? Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/6369d2c5/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050803/6369d2c5/PinnoNathanPaul.vcf From zamb at saudi.net.sa Wed Aug 3 08:44:08 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Wed, 03 Aug 2005 09:44:08 +0300 Subject: [Tutor] Corrupt files (fwd) In-Reply-To: References: Message-ID: <1123051448.3086.10.camel@localhost.localdomain> On Tue, 2005-08-02 at 13:22 -0700, Danny Yoo wrote: > > ---------- Forwarded message ---------- > Date: Tue, 2 Aug 2005 22:12:34 +0200 (CEST) > From: "[iso-8859-1] yvind" > To: Danny Yoo > Subject: Re: [Tutor] Corrupt files > > Hello and thank you. > > I don't really think that will help. The files are mostly smaller ones of > for example jpg, avi, txt, doc and xls files. It is not published any MD5 > checksums. Is there any way to check for example that a jpg file is > completed without opening it? Or, is there some way to check the filesize > on the server thru http (urlretrieve) and compare with the filesize of the > downloaded file? Do you think that would work? > > Thanks in advance.... > I'm not sure what this is all about, but here's something you might find it useful. An HTTP "HEAD" request is like an HTTP "GET" (or normal retrieval) but the server will not send any data, only the header part. This might be useful to you to compare the size and modification date of the files. Of course, this all assume that the server does send such information (sadly, some badly programmed/configured HTTP server don't do that!). For more information about "GET" and "HEAD", search the web or ask here again. Ziyad. From alan.gauld at freenet.co.uk Wed Aug 3 09:02:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 08:02:37 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color References: <42EFF860.5070407@iol.ie> Message-ID: <06bc01c597f9$5511d4d0$8eaa8651@xp> > Error messages in IDLE also get a color (red), so it loooks to be > standard 'IDLE'/python;-) > Also IDEL recognize keywords while typing and changes the color (to > orange), so it is quite normal in IDLE... > But now; how can user's python program use it? IDLE is written in Tkinter so it uses the same techniques that you would use to change the colour of text in a Text widget. But IDLE does not expose the Text widget to you as a user. In fact it doesn't make much sense for IDLE to do that since IDLE is only a development tool. It is not where you are expected to run your programs. THus IDLE tries to mimic the environment where your programs should run not to provide facilities that would only work within IDLE. Is there any reason why you want to change the ouput only in IDLE? Or do you really want to be able to control the output of your program wherever it runs? If the latter then you will need to create your own Text window and display the output there. Alan G. From alan.gauld at freenet.co.uk Wed Aug 3 09:14:55 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 08:14:55 +0100 Subject: [Tutor] I need advice about which way to go. References: Message-ID: <06cc01c597fb$0d07af00$8eaa8651@xp> Hi Nathan, The problem with this problem descripton is that you have an idea clear in your own head but the rest oif us only have the words. So... > I am writing a poker game and a blackjack game. Two separate games or one game that can play both? > I was wondering which way would be Python smart and work properly. That depends on you really, there is no Python way to write card games (unless you count using PyGame but even thats not mandatory). This is really a matter of design and Python doesn't impose many limits on that, there are lots of valid approaches you could take. > I am trying to figure out whether or not to use t(n) as a card > indicator, > when n = randomly drawn number. t(n) means a function called t that takes a parameter called n. I'm not sure how you would use that as a card indicator. Are you confusing functions and lists? Do you mean t[n] where n is an index into a list called t? Then if t held all the card values (or names) n could indicate one particular card. That might work. Another way could be a dictionary with a coded name per card as the key along with the value. (Aces pose a problem regardless of solution because they have two values) > I could go that way, or code it as t1, t2, t3, etc. Having 52 variables, one per card could work but seems clumsy. Also figuring out how to deal a hand would be tricky with discreet variables. > Which way is the right and correct way to go? There is no single right way, but a collection of some sort sounds better than a set of independant variables. > Also for blackjack, I want to use it as playertotal = playertotal + > n, > and computertotal = computertotal + n. or 1,2,3, etc. Which is > better? I don't understand that bit at all?! What does 'n'represent? What are the 1,2,3 for? Alan G. From genietdev0 at iol.ie Wed Aug 3 09:46:15 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Wed, 03 Aug 2005 08:46:15 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color In-Reply-To: <06bc01c597f9$5511d4d0$8eaa8651@xp> References: <42EFF860.5070407@iol.ie> <06bc01c597f9$5511d4d0$8eaa8651@xp> Message-ID: <42F07647.30305@iol.ie> Hello Alan, Thanks for your feedback. I managed to get some color in my print in IDLE (or the Paint Shop Pro Script Output window): ### import sys print >> sys.stderr,'Hello world' ### All the best, Victor Alan G wrote: > Is there any reason why you want to change the ouput only in IDLE? > Or do you really want to be able to control the output of your > program wherever it runs? If the latter then you will need to > create your own Text window and display the output there. From alan.gauld at freenet.co.uk Wed Aug 3 10:22:39 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 09:22:39 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color References: <42EFF860.5070407@iol.ie> <06bc01c597f9$5511d4d0$8eaa8651@xp> <42F07647.30305@iol.ie> Message-ID: <06df01c59804$8375e540$8eaa8651@xp> > Thanks for your feedback. I managed to get some color in my print in > IDLE (or the Paint Shop Pro Script Output window): I'm intrigued. Does PSP now support scripting in Python? Is that a standard feature? (I'm a Photoshop Elements user myself...) > ### > import sys > print >> sys.stderr,'Hello world' > ### Ah yes, neat idea. By writing to stderr IDLE will treat it as an error and color it appropriately. Alan G From genietdev0 at iol.ie Wed Aug 3 10:26:55 2005 From: genietdev0 at iol.ie (Victor Reijs) Date: Wed, 03 Aug 2005 09:26:55 +0100 Subject: [Tutor] print a line in IDLE as bold, italics or a color In-Reply-To: <06df01c59804$8375e540$8eaa8651@xp> References: <42EFF860.5070407@iol.ie> <06bc01c597f9$5511d4d0$8eaa8651@xp> <42F07647.30305@iol.ie> <06df01c59804$8375e540$8eaa8651@xp> Message-ID: <42F07FCF.6080901@iol.ie> Hello Alan, Alan G wrote: >> Thanks for your feedback. I managed to get some color in my print in >> IDLE (or the Paint Shop Pro Script Output window): > > I'm intrigued. Does PSP now support scripting in Python? > Is that a standard feature? (I'm a Photoshop Elements user > myself...) It is python (I wonder even if the system itself is not python;-), because the calls to PSP routines are kind of Python calls... I am working on this: http://www.iol.ie/~geniet/eng/pspscripthelp.htm All the best, Victor From shitizb at yahoo.com Wed Aug 3 10:57:10 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed, 3 Aug 2005 01:57:10 -0700 (PDT) Subject: [Tutor] Web Browser in Python Message-ID: <20050803085710.11838.qmail@web53808.mail.yahoo.com> Hi, I need to program a web browser in python.I dont have any idea of how to start, what i do have is time and willingness to learn.Could anyone direct me to some suitable reference? Shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/cdb5adec/attachment.htm From tegmine at gmail.com Wed Aug 3 14:00:22 2005 From: tegmine at gmail.com (Luis N) Date: Wed, 3 Aug 2005 05:00:22 -0700 Subject: [Tutor] Web Browser in Python In-Reply-To: <20050803085710.11838.qmail@web53808.mail.yahoo.com> References: <20050803085710.11838.qmail@web53808.mail.yahoo.com> Message-ID: <77bfa81a050803050045e706be@mail.gmail.com> On 8/3/05, Shitiz Bansal wrote: > Hi, > I need to program a web browser in python.I dont have any idea of how to > start, what i do have is time and willingness to learn.Could anyone direct > me to some suitable reference? > Shitiz > How about Grail http://grail.sourceforge.net/ ? Luis. From amonroe at columbus.rr.com Wed Aug 3 14:32:52 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 3 Aug 2005 08:32:52 -0400 Subject: [Tutor] Web Browser in Python In-Reply-To: <77bfa81a050803050045e706be@mail.gmail.com> References: <20050803085710.11838.qmail@web53808.mail.yahoo.com> <77bfa81a050803050045e706be@mail.gmail.com> Message-ID: <84135662001.20050803083252@columbus.rr.com> >> I need to program a web browser in python.I dont have any idea of how to >> start, what i do have is time and willingness to learn.Could anyone direct >> me to some suitable reference? >> Shitiz >> > How about Grail http://grail.sourceforge.net/ ? Looks neat, but it doesn't run on my box: C:\net\grail-0.6>grail.py C:\net\grail-0.6\grailbase\app.py:6: DeprecationWarning: the regex module is deprecated; please use the re module import regex C:\Python23\lib\regsub.py:15: DeprecationWarning: the regsub module is deprecated; please use re.sub() DeprecationWarning) Traceback (most recent call last): File "C:\net\grail-0.6\grail.py", line 499, in ? main() File "C:\net\grail-0.6\grail.py", line 108, in main app = Application(prefs=prefs, display=display) File "C:\net\grail-0.6\grail.py", line 248, in __init__ self.stylesheet = Stylesheet.Stylesheet(self.prefs) File "C:\net\grail-0.6\Stylesheet.py", line 21, in __init__ self.load() File "C:\net\grail-0.6\Stylesheet.py", line 45, in load massaged.append((g, c), v % fparms_dict) TypeError: append() takes exactly one argument (2 given) From meesters at uni-mainz.de Wed Aug 3 14:49:37 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 3 Aug 2005 14:49:37 +0200 Subject: [Tutor] fourier transform In-Reply-To: <20050803000310.29809.qmail@web30507.mail.mud.yahoo.com> References: <20050803000310.29809.qmail@web30507.mail.mud.yahoo.com> Message-ID: <1afebc6f7dff1e8c8c06cc284c1a6b14@uni-mainz.de> Hi Jeff, On 3 Aug 2005, at 02:03, Jeff Peery wrote: > hope this is more clear. from the output I would expect that two > spikes appear with amplitude = 1.? [snip] > I don't understand the output amplitudes. they should all be zero > except for at one herz it should be one. not sure about the frequency > for that matter either. I gotta dig up my math book and figure this > out. in the meantime any suggestions for what this is outputing would > be greatly appreciated! thanks. > ? Yes, well, the math book idea might be a good one ;-). No, but seriously: You are just making a little mistake. First of all you are NOT exactly calculating a Fourier transform but a numerical estimation of it (you are dealing with an array of discrete data points, which is unavoidable when dealing with computers ;-)). Look on your sine wave. Is it a perfect one? Then, what do you see when you plot your data? Some 'noise' and one little peak. The noise is due to errors which have to do with floating point arithmetics (see http://docs.python.org/tut/node16.html). It's really small and in most cases I'm sure it's neglectable as well. But when looking on your idea of what you would expect, I'm wondering whether you actually want a power spectrum estimation (see http://mathworld.wolfram.com/PowerSpectrum.html)? Try myFFT = abs(fft.fft(inp)) instead of myFFT = fft.real_fft(inp) This a least might come close to what I think you want to see, right? You might have a look on myFFt = fft.fft(inp).real as well, because it might make things to appear a little clearer. One more remark: Try to avoid overwriting python key words like 'input'. Hope this helped. Cheers Christian PS Here is the code I used. It looks a bit different from yours - I hope the comments help a bit: from numarray import * import numarray.fft as fft #at least one of the numbers should be floating point here period = 1.0 #use numarray's / Numpy's pi instead of 3.14... inp = sin(arange(0,64)*pi*2/64.0) myFFT = abs(fft.fft(inp)) #or #myFFt = fft.fft(inp).real #or #myFFT = fft.real_fft(inp) #depending on what you really want dtime = period/64.0 dfreq = 1.0/dtime for i in range(len(myFFT)): print myFFT[i], dfreq*i From jsmith at medplus.com Wed Aug 3 14:52:25 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 3 Aug 2005 08:52:25 -0400 Subject: [Tutor] Deleting an entry from a dictionary Message-ID: <3B05FA2AD704244BB0CAB99D8026F5558DE3@medexch2.medplus.com> Although that works, I kinda prefer del meals['breakfast'] since that explicitly indicates what is going on. Speaking of which, I note that there is a pop for lists but no shift. Is there a Python idiom for this or is it just val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) which seems a little clumsy. Jeff -----Original Message----- From: tutor-bounces+jsmith=medplus.com at python.org [mailto:tutor-bounces+jsmith=medplus.com at python.org] On Behalf Of Adam Bark Sent: Tuesday, August 02, 2005 5:17 PM To: Greg Lindstrom Cc: tutor at python.org Subject: Re: [Tutor] Deleting an entry from a dictionary meals.pop(key) will do it. Example: >>> meals = {} >>> meals['breakfast'] = 'slimfast' >>> meals['lunch'] = 'slimfast' >>> meals['dinner'] = 'something sensible' >>> meals {'lunch': 'slimfast', 'breakfast': 'slimfast', 'dinner': 'something sensible'} >>> meals.pop("breakfast") 'slimfast' >>> meals {'lunch': 'slimfast', 'dinner': 'something sensible'} On 8/2/05, Greg Lindstrom > wrote: Hello- This must be simple, but for the life of me I can't figure out how to delete an entry from a dictionary. For example, meals = {} meals['breakfast'] = 'slimfast' meals['lunch'] = 'slimfast' meals['dinner'] = 'something sensible' How do I eliminate 'lunch' from the dictionary so that I only have 'breakfast' and 'dinner'? Thanks! --greg _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/9e3db575/attachment.htm From enas_khalil at yahoo.com Wed Aug 3 14:59:03 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Wed, 3 Aug 2005 05:59:03 -0700 (PDT) Subject: [Tutor] i want to build my own arabic training corpus data and use the NLTK to deal with In-Reply-To: Message-ID: <20050803125903.29013.qmail@web50306.mail.yahoo.com> i want to build my own arabic training corpus data and use the NLTK to parse and make test for unkown data how can i build this file and make it available to treat with it using different NLTK classes please tell me how can i start thanks --------------------------------- Start your day with Yahoo! - make it your home page -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/75f14a48/attachment.htm From kent37 at tds.net Wed Aug 3 15:12:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Aug 2005 09:12:47 -0400 Subject: [Tutor] Web Browser in Python In-Reply-To: <84135662001.20050803083252@columbus.rr.com> References: <20050803085710.11838.qmail@web53808.mail.yahoo.com> <77bfa81a050803050045e706be@mail.gmail.com> <84135662001.20050803083252@columbus.rr.com> Message-ID: <42F0C2CF.9070703@tds.net> R. Alan Monroe wrote: >>>I need to program a web browser in python.I dont have any idea of how to >>>start, what i do have is time and willingness to learn.Could anyone direct >>>me to some suitable reference? >>>Shitiz >>> > > >>How about Grail http://grail.sourceforge.net/ ? > > > Looks neat, but it doesn't run on my box: Grail is pretty much dead, I think. If you look at the checkin mailing list the last activity was in 2001. If you really want to write a web browser it might be a good starting point though. wxPython has an HTML widget that could also be a starting point. I hope you realize that creating a browser on the scale of Firefox or IE is a massive and difficult project. Is that your goal or did you have something more modest in mind? Kent From kent37 at tds.net Wed Aug 3 15:14:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Aug 2005 09:14:33 -0400 Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5558DE3@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F5558DE3@medexch2.medplus.com> Message-ID: <42F0C339.4010204@tds.net> Smith, Jeff wrote: > Speaking of which, I note that there is a pop for lists but no shift. > Is there a Python idiom for this or is it just > val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) > which seems a little clumsy. val = mylist.pop(0) Kent From srini_iyyer_bio at yahoo.com Wed Aug 3 15:38:58 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 3 Aug 2005 06:38:58 -0700 (PDT) Subject: [Tutor] Please help Message-ID: <20050803133858.34153.qmail@web53503.mail.yahoo.com> sorry for repost. Hello group: I have a file (3339203 lines) that looks like this: (col:1) (col:2) (col:3) AD134KL XXXXX XXXXX Xaaaa Xaaaa Xbbbb Xbbbb AD144KL YYYYY YYYYY Yaaaa Yaaaa Now I have to fill the rows in column 1 with their designated stuff: AD134KL AD134KL XXXXX XXXXX AD134KL Xaaaa Xaaaa AD134KL Xbbbb Xbbbb AD144KL AD144KL YYYYY YYYYY AD144KL Yaaaa Yaaaa My code: f1 = open('xx','r') meat = f1.readlines() mind = [] for i in range(len(meat)): if meat[i].startswith('AD'): mind.append(i) mind = [0,4] for i in range(len(mind)): k = i+1 l = mind[i]+1 j = mind[k]-1 print l,j 1 3 Logic: Now I want to substitute 'AD134KL' between 0 and 4 which is 1,2,and 3. and move on.. After getting the idexes of blank rows between two AD* as a list, I lost grip and I cannot think of what should be done next Is this a good way to solve it . or is there any other easy way Can experts help me please. thank you srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From adam.jtm30 at gmail.com Wed Aug 3 16:02:03 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 3 Aug 2005 15:02:03 +0100 Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5558DE3@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F5558DE3@medexch2.medplus.com> Message-ID: Oh yeah using del is better. I was typing as Danny sent his reply so I didn't realise untill after I had sent that. On 8/3/05, Smith, Jeff wrote: > > Although that works, I kinda prefer > del meals['breakfast'] > since that explicitly indicates what is going on. > Speaking of which, I note that there is a pop for lists but no shift. Is > there a Python idiom for this or is it just > val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) > which seems a little clumsy. > Jeff > -----Original Message----- > *From:* tutor-bounces+jsmith=medplus.com at python.org [mailto: > tutor-bounces+jsmith=medplus.com at python.org] *On Behalf Of *Adam Bark > *Sent:* Tuesday, August 02, 2005 5:17 PM > *To:* Greg Lindstrom > *Cc:* tutor at python.org > *Subject:* Re: [Tutor] Deleting an entry from a dictionary > > meals.pop(key) will do it. > Example: > >>> meals = {} > >>> meals['breakfast'] = 'slimfast' > >>> meals['lunch'] = 'slimfast' > >>> meals['dinner'] = 'something sensible' > >>> meals > {'lunch': 'slimfast', 'breakfast': 'slimfast', 'dinner': 'something > sensible'} > >>> meals.pop("breakfast") > 'slimfast' > >>> meals > {'lunch': 'slimfast', 'dinner': 'something sensible'} > > On 8/2/05, Greg Lindstrom wrote: > > > > Hello- > > This must be simple, but for the life of me I can't figure out how to > > delete an entry from a dictionary. For example, > > > > meals = {} > > meals['breakfast'] = 'slimfast' > > meals['lunch'] = 'slimfast' > > meals['dinner'] = 'something sensible' > > > > How do I eliminate 'lunch' from the dictionary so that I only have > > 'breakfast' and 'dinner'? > > > > Thanks! > > --greg > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/2b3e8bf6/attachment-0001.htm From jsmith at medplus.com Wed Aug 3 16:21:46 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 3 Aug 2005 10:21:46 -0400 Subject: [Tutor] Deleting an entry from a dictionary Message-ID: <3B05FA2AD704244BB0CAB99D8026F5558E08@medexch2.medplus.com> Ummm...that doesn't do what I asked. pop is a linguistic idiom for (val, mylist) = (mylist[-1], mylist[0:-1]) shift is the standard idiom for (val, mylist) = (mylist[0], mylist[1:]) but Python doesn't appear to offer this. Jeff -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Wednesday, August 03, 2005 9:15 AM Cc: tutor at python.org Subject: Re: [Tutor] Deleting an entry from a dictionary Smith, Jeff wrote: > Speaking of which, I note that there is a pop for lists but no shift. > Is there a Python idiom for this or is it just > val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) > which seems a little clumsy. val = mylist.pop(0) Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From python at jayloden.com Wed Aug 3 12:28:49 2005 From: python at jayloden.com (Jay Loden) Date: Wed, 3 Aug 2005 10:28:49 +0000 Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5558E08@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F5558E08@medexch2.medplus.com> Message-ID: <200508031028.49485.python@jayloden.com> I don't believe it does...some time ago I asked about this when I was creating a list and I wanted the opposite of list.append() - if you search "prepend to a list" you should find the responses I was sent. The only solutions Python offers that I'm aware of are to either use list.insert() at the zero index, or use list.reverse() with list.append() to flip the list around, add an item, then reverse it back to the original order with one new item at the beginning. -Jay On Wednesday 03 August 2005 2:21 pm, Smith, Jeff wrote: > Ummm...that doesn't do what I asked. > > pop is a linguistic idiom for > > (val, mylist) = (mylist[-1], mylist[0:-1]) > > shift is the standard idiom for > > (val, mylist) = (mylist[0], mylist[1:]) > > but Python doesn't appear to offer this. > > Jeff > From davholla2002 at yahoo.co.uk Wed Aug 3 16:37:42 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 3 Aug 2005 15:37:42 +0100 (BST) Subject: [Tutor] Extract information from an HTML table Message-ID: <20050803143742.91205.qmail@web25406.mail.ukl.yahoo.com> Hi All, I would like to do the following. I have an HTML document with a table with 2 columns. I would like to write a program to join the 2 columns together, ideally with same font etc. Ie get all the information between and and the next and and put it together. Does anyone have any idea on how to do this ? I suppose I could remove every second and , any better ideas ? Thanks in advance David --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/91e87331/attachment.htm From kent37 at tds.net Wed Aug 3 16:40:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Aug 2005 10:40:57 -0400 Subject: [Tutor] Deleting an entry from a dictionary In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5558E08@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F5558E08@medexch2.medplus.com> Message-ID: <42F0D779.2030600@tds.net> Smith, Jeff wrote: > Ummm...that doesn't do what I asked. > > pop is a linguistic idiom for > > (val, mylist) = (mylist[-1], mylist[0:-1]) No, actually, not quite. >From the docs: s.pop([i]) same as x = s[i]; del s[i]; return x so val = mylist.pop(0) is the same as val = mylist[0] del mylist[0] which, other than the fact that it mutates mylist instead of returning a new slice, is identical to what you asked for. For example: >>> l=[1,2,3] >>> l.pop(0) 1 >>> l [2, 3] The default value for i is -1 so val = mylist.pop() is equivalent to what you have above (again, other than mutating instead of slicing). Kent > > shift is the standard idiom for > > (val, mylist) = (mylist[0], mylist[1:]) > > but Python doesn't appear to offer this. > > Jeff > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Wednesday, August 03, 2005 9:15 AM > Cc: tutor at python.org > Subject: Re: [Tutor] Deleting an entry from a dictionary > > > Smith, Jeff wrote: > >>Speaking of which, I note that there is a pop for lists but no shift. >>Is there a Python idiom for this or is it just >> val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) >>which seems a little clumsy. > > > val = mylist.pop(0) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Wed Aug 3 16:51:11 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 3 Aug 2005 10:51:11 -0400 Subject: [Tutor] Deleting an entry from a dictionary Message-ID: <3B05FA2AD704244BB0CAB99D8026F5558E17@medexch2.medplus.com> Sorry about that. I missed the '0' in your statement and just read it as pop(). I guess I'm sill not used to giving pop an argument :-) Jeff -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Wednesday, August 03, 2005 10:41 AM Cc: tutor at python.org Subject: Re: [Tutor] Deleting an entry from a dictionary Smith, Jeff wrote: > Ummm...that doesn't do what I asked. > > pop is a linguistic idiom for > > (val, mylist) = (mylist[-1], mylist[0:-1]) No, actually, not quite. >From the docs: s.pop([i]) same as x = s[i]; del s[i]; return x so val = mylist.pop(0) is the same as val = mylist[0] del mylist[0] which, other than the fact that it mutates mylist instead of returning a new slice, is identical to what you asked for. For example: >>> l=[1,2,3] >>> l.pop(0) 1 >>> l [2, 3] The default value for i is -1 so val = mylist.pop() is equivalent to what you have above (again, other than mutating instead of slicing). Kent > > shift is the standard idiom for > > (val, mylist) = (mylist[0], mylist[1:]) > > but Python doesn't appear to offer this. > > Jeff > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Wednesday, August 03, 2005 9:15 AM > Cc: tutor at python.org > Subject: Re: [Tutor] Deleting an entry from a dictionary > > > Smith, Jeff wrote: > >>Speaking of which, I note that there is a pop for lists but no shift. >>Is there a Python idiom for this or is it just >> val = mylist.shift() => (val, mylist) = (mylist[0], mylist[1:]) >>which seems a little clumsy. > > > val = mylist.pop(0) > > Kent > > _______________________________________________ > 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 ajschmidt at fredericksburg.com Wed Aug 3 17:01:09 2005 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Wed, 03 Aug 2005 11:01:09 -0400 Subject: [Tutor] Please help In-Reply-To: <20050803133858.34153.qmail@web53503.mail.yahoo.com> References: <20050803133858.34153.qmail@web53503.mail.yahoo.com> Message-ID: <42F0DC35.4090202@fredericksburg.com> Hey, I had a similar problem not too long ago. My data came in the first format, but I didn't need it formated like that. Here is how I would have written it: import re col=re.compile('(AD.*?)\s*$') datas=re.compile('\s*(.+?)\s+(.+?)') f1 = open('xx','r') mind={} matching='' for i in meat: match=col.find(i) if match: mind[match.group(1)]=[] matching=match.group(1) match=datas.find(i) if match: mind[matching].append([match.group(1),match.group(2)]) That would collect the data and put it into a dictionary with the values being a list of the two part data. You could print like this: for each in mind.keys(): print each for value in mind[each]: print each+" "+value[0]+" "+value[1] That should do it! Ask if you don't understand any part of it. Allen J. Schmidt, Jr. From python at jayloden.com Wed Aug 3 13:06:20 2005 From: python at jayloden.com (Jay Loden) Date: Wed, 3 Aug 2005 11:06:20 +0000 Subject: [Tutor] How do I add an argument too... In-Reply-To: References: Message-ID: <200508031106.21134.python@jayloden.com> I think it was just a typo for "the python distro" that came out as "the epython distro"... On Thursday 21 July 2005 9:15 pm, Danny Yoo wrote: > On Thu, 21 Jul 2005, Joseph Quigley wrote: > > optparse.. Can I download that as a module or do I have to download > > epython? > > Hi Joseph, > > optparse derives from a hird-party library called Optik, so in a pinch, > you can probably just use Optik: > > http://optik.sourceforge.net/ > > It's also possible to port optparse back to older versions of Python, > although that may take more work. > > Good luck! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ajschmidt at fredericksburg.com Wed Aug 3 17:08:15 2005 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Wed, 03 Aug 2005 11:08:15 -0400 Subject: [Tutor] Please help In-Reply-To: <20050803133858.34153.qmail@web53503.mail.yahoo.com> References: <20050803133858.34153.qmail@web53503.mail.yahoo.com> Message-ID: <42F0DDDF.2010201@fredericksburg.com> Whoops! Had to correct it! Hey, I had a similar problem not too long ago. My data came in the first format, but I didn't need it formated like that. Here is how I would have written it: import re col=re.compile('(AD.*?)\s*$') datas=re.compile('\s*(.+?)\s+(.+?)') f1 = open('xx','r') mind={} matching='' for i in fl: match=col.find(i) if match: mind[match.group(1)]=[] matching=match.group(1) match=datas.find(i) if match: mind[matching].append([match.group(1),match.group(2)]) That would collect the data and put it into a dictionary with the values being a list of the two part data. You could print like this: for each in mind.keys(): print each for value in mind[each]: print each+" "+value[0]+" "+value[1] That should do it! Ask if you don't understand any part of it. Allen J. Schmidt, Jr. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From jsmith at medplus.com Wed Aug 3 17:29:41 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 3 Aug 2005 11:29:41 -0400 Subject: [Tutor] HTML/text formatting question Message-ID: <3B05FA2AD704244BB0CAB99D8026F5558E29@medexch2.medplus.com> I have a tool that outputs data in either html or text output. Currently I'm writing chucks like: if html: print '' print '' print ' and and the next and and put it together. Does > anyone have any idea on how to do this ? I suppose I could remove every > second and , any better ideas ? Hi David, Yes. Unless your situtation is very dire, don't try to code this by using regular expressions! *grin* Use an HTML parser for this if you can. There are parsers in the Standard Library. There's also one called Beautiful Soup that I've heard very good things about: http://www.crummy.com/software/BeautifulSoup/ For example: ##### >>> import BeautifulSoup >>> from BeautifulSoup import BeautifulSoup >>> text = "

' print 'Differences %s: %s' % (htypestr, lbl1) if html: ... This seems clunky and my next step was going to be to define generic functions which would generate the surrounding html tags only when passed the proper argument. I was wondering if there was a better way to do this with a standard Python library. It looked like formatter might but that it also might be too low-level. Any help is appreciated, Jeff From jeffpeery at yahoo.com Wed Aug 3 18:27:19 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 3 Aug 2005 09:27:19 -0700 (PDT) Subject: [Tutor] fourier transform In-Reply-To: <1afebc6f7dff1e8c8c06cc284c1a6b14@uni-mainz.de> Message-ID: <20050803162719.98840.qmail@web30503.mail.mud.yahoo.com> Hi again, is there a good reason why the output is dependant upon the sampling rate. in the example if you increase from say 64 to 128 samples the output increases by a factor of 2. Christian Meesters wrote: Hi Jeff, On 3 Aug 2005, at 02:03, Jeff Peery wrote: > hope this is more clear. from the output I would expect that two > spikes appear with amplitude = 1. [snip] > I don't understand the output amplitudes. they should all be zero > except for at one herz it should be one. not sure about the frequency > for that matter either. I gotta dig up my math book and figure this > out. in the meantime any suggestions for what this is outputing would > be greatly appreciated! thanks. > Yes, well, the math book idea might be a good one ;-). No, but seriously: You are just making a little mistake. First of all you are NOT exactly calculating a Fourier transform but a numerical estimation of it (you are dealing with an array of discrete data points, which is unavoidable when dealing with computers ;-)). Look on your sine wave. Is it a perfect one? Then, what do you see when you plot your data? Some 'noise' and one little peak. The noise is due to errors which have to do with floating point arithmetics (see http://docs.python.org/tut/node16.html). It's really small and in most cases I'm sure it's neglectable as well. But when looking on your idea of what you would expect, I'm wondering whether you actually want a power spectrum estimation (see http://mathworld.wolfram.com/PowerSpectrum.html)? Try myFFT = abs(fft.fft(inp)) instead of myFFT = fft.real_fft(inp) This a least might come close to what I think you want to see, right? You might have a look on myFFt = fft.fft(inp).real as well, because it might make things to appear a little clearer. One more remark: Try to avoid overwriting python key words like 'input'. Hope this helped. Cheers Christian PS Here is the code I used. It looks a bit different from yours - I hope the comments help a bit: from numarray import * import numarray.fft as fft #at least one of the numbers should be floating point here period = 1.0 #use numarray's / Numpy's pi instead of 3.14... inp = sin(arange(0,64)*pi*2/64.0) myFFT = abs(fft.fft(inp)) #or #myFFt = fft.fft(inp).real #or #myFFT = fft.real_fft(inp) #depending on what you really want dtime = period/64.0 dfreq = 1.0/dtime for i in range(len(myFFT)): print myFFT[i], dfreq*i -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/823cf143/attachment-0001.htm From python at jayloden.com Wed Aug 3 14:49:44 2005 From: python at jayloden.com (Jay Loden) Date: Wed, 3 Aug 2005 12:49:44 +0000 Subject: [Tutor] Zope/Python web devel Message-ID: <200508031249.44227.python@jayloden.com> I've been considering some web projects recently, but I have some concerns about selecting the tools I plan to use. I like Python, and I was immediately thinking of using Zope to build on. However, I am concerned about performance, resource usage, and scalability. Does anyone here have any experience with Zope or any other application frameworks like CherryPy used in a large/enterprise environment? Is Zope overly memory hungry or slow? If performance is a key point, am I better off growing my own solution from the ground up? Second, and more specific to Python itself - does anyone here have first hand knowledge of how Python compares with other solutions for server side web development? I'm specifically interested in comparisons to PHP, but Ruby, Perl, Java, C/C++ and Lisp, etc. observations would be welcome. Basically, I'm trying to get a feel for what kind of performance and resource usage I'd see out of Python versus other options. I realize this is heavily dependent on what exactly I end up doing, but just as a general observation, I'd like to know what others have experienced. I know that some large web applications are built on Python (Yahoo Mail, Google), but there's certainly less being done in Python on the web than in Perl or PHP. I just want to make sure this isn't because of Python disadvantages as opposed to simple market share. All responses are welcome. If anyone has links to some benchmarking studies comparing the two for web development I'd be grateful for those as well. -Jay From alan.gauld at freenet.co.uk Wed Aug 3 18:50:03 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 17:50:03 +0100 Subject: [Tutor] Web Browser in Python References: <20050803085710.11838.qmail@web53808.mail.yahoo.com> Message-ID: <076901c5984b$65481880$8eaa8651@xp> > I need to program a web browser in python.I dont have any idea of > how > to start, what i do have is time and willingness to learn. Can you explain what you have in mind? Do you actually want to create a web browser like IE or FireFox from scratch using Python? Or do you want to control your existing web browser using python? Or do you want to simply fetch some data from the web using python? If its the first then I suggest you start with Grail and try to bring it up to date. If its the second there are some modules around that help, specifically there is one for IE. And Konqueror in Linux/KDE has a programmable intrface that you probably can use, If its the last one you probably don;t need a browser but should investigate the urlib module. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Aug 3 19:01:00 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 18:01:00 +0100 Subject: [Tutor] Please help References: <20050803133858.34153.qmail@web53503.mail.yahoo.com> Message-ID: <077a01c5984c$eca15660$8eaa8651@xp> > sorry for repost. OK, since nobody respoinded I'll make a few suggestions. > I have a file (3339203 lines) that looks like this: Get it working first then worry about tuning it for the volumes later. > > (col:1) (col:2) (col:3) Is the above explanatory or part of the file? Doesn't matter juch but just to be clear. > AD134KL > XXXXX XXXXX > Xaaaa Xaaaa > Xbbbb Xbbbb > AD134KL > AD134KL XXXXX XXXXX > AD134KL Xaaaa Xaaaa > AD134KL Xbbbb Xbbbb So when you find a line with one field you need to store that value and preppend it to all subsequent lines until you get an empty line or another with a single field? In pseudo code: for line in infile if len(line) == 1: # just a newline outfile.write(line) continue fields = line.strip().split() if len(fields) == 1 tag = fields[0] output = line else: fields.insert(0,tag) output = "%12s%12s%12s\n" % tuple(fields) outfile.write(output) Does that make any kind of sense? Alan G. From shantanoo at gmail.com Wed Aug 3 18:50:42 2005 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Wed, 3 Aug 2005 22:20:42 +0530 Subject: [Tutor] substituting empty line with stuff In-Reply-To: <20050802215455.24800.qmail@web53505.mail.yahoo.com> References: <20050802215455.24800.qmail@web53505.mail.yahoo.com> Message-ID: <20050803165042.GA14404@ghar.dhoomketu.net.in> +++ Srinivas Iyyer [02-08-05 14:54 -0700]: | Hello group: | | I have a file (3339203 lines) that looks like this: | | (col:1) (col:2) (col:3) | AD134KL | XXXXX XXXXX | Xaaaa Xaaaa | Xbbbb Xbbbb | | AD144KL | YYYYY YYYYY | Yaaaa Yaaaa | | Now I have to fill the rows in column 1 with their | designated stuff: | | AD134KL | AD134KL XXXXX XXXXX | AD134KL Xaaaa Xaaaa | AD134KL Xbbbb Xbbbb | AD144KL | AD144KL YYYYY YYYYY | AD144KL Yaaaa Yaaaa | | | | My code: | | f1 = open('xx','r') | meat = f1.readlines() | | mind = [] | | for i in range(len(meat)): | if meat[i].startswith('AD'): | mind.append(i) | | mind = [0,4] | | for i in range(len(mind)): | k = i+1 | l = mind[i]+1 | j = mind[k]-1 | print l,j | | 1 3 | | Logic: Now I want to substitute 'AD134KL' between 0 | and 4 which is 1,2,and 3. and move on.. | | After coming to this stage, I lost grip and I do not | know what to do.. | | Can experts help me please. | | thank you | srini | Maybe... for x in open('_file_'): a=x.split() if len(a) == 1: b = a[0] else: print b, print x, Regards, Shantanoo From dyoo at hkn.eecs.berkeley.edu Wed Aug 3 19:36:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 10:36:08 -0700 (PDT) Subject: [Tutor] i want to build my own arabic training corpus data and use the NLTK to deal with In-Reply-To: <20050803125903.29013.qmail@web50306.mail.yahoo.com> Message-ID: On Wed, 3 Aug 2005, enas khalil wrote: > i want to build my own arabic training corpus data and use the NLTK to > parse and make test for unkown data Hi Enas, By NLTK, I'll assume that you mean the Natural Language Toolkit at: http://nltk.sourceforge.net/ Have you gone through the introduction and tutorials from the NLTK web page? http://nltk.sourceforge.net/getting_started.html http://nltk.sourceforge.net/tutorial/index.html > how can i build this file and make it available to treat with it using > different NLTK classes Your question is a bit specialized, so we may not be the best people to ask about this. The part that you may want to think about is how to break a corpus into a sequence of tokens, since tokens are primarily what the NLTK classes work with. This may or may not be immediately easy, depending on how much you can take advantage of existing NLTK classes. As the documentation in NLTK mentions: """If we turn to languages other than English, segmenting words can be even more of a challenge. For example, in Chinese orthography, characters correspond to monosyllabic morphemes. Many morphemes are words in their own right, but many words contain more than one morpheme; most of them consist of two morphemes. However, there is no visual representation of word boundaries in Chinese text.""" I don't know how Arabic works, so I'm not sure if the caveat above is something that we need to worry about. There are a few built-in NLTK tokenizers that break a corpus into tokens, including a WhitespaceTokenizer and a RegexpTokenizer class, both introduced here: http://nltk.sourceforge.net/tutorial/tokenization/nochunks.html For example: ###### >>> import nltk.token >>> mytext = nltk.token.Token(TEXT="hello world this is a test") >>> mytext ###### At the moment, this is a single token. We can use a naive approach in breaking this into words by using whitespace as our delimiter: ###### >>> import nltk.tokenizer >>> nltk.tokenizer.WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(mytext) >>> mytext <[, , , , , ]> ###### And now our text is broken into a sequence of discrete tokens, where we can now play with the 'subtokens' of our text: ###### >>> mytext['WORDS'] [, , , , , ] >>> len(mytext['WORDS']) 6 ###### If Arabic follows conventions that fit closely with the assumptions of those tokenizers, you should be in good shape. Otherwise, you'll probably have to do some work to build your own customized tokenizers. From dyoo at hkn.eecs.berkeley.edu Wed Aug 3 19:50:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 10:50:09 -0700 (PDT) Subject: [Tutor] Extract information from an HTML table In-Reply-To: <20050803143742.91205.qmail@web25406.mail.ukl.yahoo.com> Message-ID: On Wed, 3 Aug 2005, David Holland wrote: > I would like to do the following. I have an HTML document with a table > with 2 columns. I would like to write a program to join the 2 columns > together, ideally with same font etc. Ie get all the information between >

helloworld
" >>> soup = BeautifulSoup(text) ##### Once we have a soup, we can start walking through it: ###### >>> soup
helloworld
>>> soup.table
helloworld
>>> soup.table.tr >>> soup.table.tr.td hello >>> soup.table.tr.td.string 'hello' >>> soup.table.tr.td.nextSibling world >>> >>> for td in soup.table.tr: ... print td.string ... hello world ##### So it handles a lot of the ugliness behind parsing HTML. Good luck to you! From 3dbernard at gmail.com Wed Aug 3 20:00:48 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 3 Aug 2005 14:00:48 -0400 Subject: [Tutor] CVS for Python Message-ID: <61d0e2b40508031100174399bb@mail.gmail.com> Hello, Does anyone can recomment a good CVS for Python? Thanks Benrard From alan.gauld at freenet.co.uk Wed Aug 3 20:11:15 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 19:11:15 +0100 Subject: [Tutor] HTML/text formatting question References: <3B05FA2AD704244BB0CAB99D8026F5558E29@medexch2.medplus.com> Message-ID: <079a01c59856$bd2e6170$8eaa8651@xp> > if html: > print '' > print '' > print '

' You can use a single print with a triple quoted string to simplify a bit. > I was wondering if there was a better way to do this with a standard > Python library. I donlt think there is one in the standard library but there is an HTML generator module (HTMLgen) in the Vaults of Parnassus. It acts a bit like the CGI module in Perl if you are familiar with that. There s a tutorial here: http://www.linuxjournal.com/article/2986 HTH, Alan G. From falcon3166 at hotmail.com Wed Aug 3 20:12:51 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 12:12:51 -0600 Subject: [Tutor] I need advice about which way to go. References: <06cc01c597fb$0d07af00$8eaa8651@xp> Message-ID: Sorry about that, I thought it was clear that n = number randomly chosen. I was thinking of if the number was a five, it would choose a card with a five on it. I don't want to have to code stuff that I have to repeat again and again. I'm not worrying about card types, I have that figured out separately. The two games are indeed separate, too much trouble to do them a 1 program that can play both games. Maybe I should have shown my code and asked using the code as a visual reference. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Tutor mailing list" Sent: Wednesday, August 03, 2005 1:14 AM Subject: Re: [Tutor] I need advice about which way to go. > Hi Nathan, > > The problem with this problem descripton is that you have an idea > clear in your own head but the rest oif us only have the words. > So... > >> I am writing a poker game and a blackjack game. > > Two separate games or one game that can play both? > >> I was wondering which way would be Python smart and work properly. > > That depends on you really, there is no Python way to write card games > (unless you count using PyGame but even thats not mandatory). This is > really a matter of design and Python doesn't impose many limits on that, > there are lots of valid approaches you could take. > >> I am trying to figure out whether or not to use t(n) as a card indicator, >> when n = randomly drawn number. > > t(n) means a function called t that takes a parameter called n. I'm > not sure how you would use that as a card indicator. Are you confusing > functions and lists? Do you mean t[n] where n is an index into a list > called t? Then if t held all the card values (or names) n could indicate > one particular card. That might work. > > Another way could be a dictionary with a coded name per card as the key > along with the value. (Aces pose a problem regardless of solution because > they have two values) > >> I could go that way, or code it as t1, t2, t3, etc. > > Having 52 variables, one per card could work but seems clumsy. > Also figuring out how to deal a hand would be tricky with discreet > variables. > >> Which way is the right and correct way to go? > > There is no single right way, but a collection of some sort sounds > better than a set of independant variables. > >> Also for blackjack, I want to use it as playertotal = playertotal + n, >> and computertotal = computertotal + n. or 1,2,3, etc. Which is better? > > I don't understand that bit at all?! What does 'n'represent? > What are the 1,2,3 for? > > Alan G. > From dyoo at hkn.eecs.berkeley.edu Wed Aug 3 20:24:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 11:24:50 -0700 (PDT) Subject: [Tutor] CVS for Python In-Reply-To: <61d0e2b40508031100174399bb@mail.gmail.com> Message-ID: On Wed, 3 Aug 2005, Bernard Lebel wrote: > Does anyone can recomment a good CVS for Python? Hi Bernard, I'm not quite sure I understand what you mean yet. Are you looking for a revision control system for Python? If that's what you're looking for, then CVS is one implementation of such a system, http://www.nongnu.org/cvs/ but there's a nicer one called Subversion: http://subversion.tigris.org/ Neither are explicitely tied to Python, which is why I'm still a little confused about the question. From bgailer at sbcglobal.net Wed Aug 3 20:28:20 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 03 Aug 2005 11:28:20 -0700 Subject: [Tutor] I need advice about which way to go. In-Reply-To: References: <06cc01c597fb$0d07af00$8eaa8651@xp> Message-ID: <6.1.2.0.0.20050803112700.0330f470@pop.sbcglobal.yahoo.com> At 11:12 AM 8/3/2005, Nathan Pinno wrote: >Sorry about that, I thought it was clear that n = number randomly chosen. I >was thinking of if the number was a five, it would choose a card with a five >on it. I don't want to have to code stuff that I have to repeat again and >again. That's what classes, loops and functions are for. >I'm not worrying about card types, I have that figured out separately. >The two games are indeed separate, too much trouble to do them a 1 program >that can play both games. >Maybe I should have shown my code and asked using the code as a visual >reference. Good idea. How about now? Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/2e71237d/attachment.htm From falcon3166 at hotmail.com Wed Aug 3 20:36:23 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 12:36:23 -0600 Subject: [Tutor] I need advice about which way to go. References: <06cc01c597fb$0d07af00$8eaa8651@xp> <6.1.2.0.0.20050803112700.0330f470@pop.sbcglobal.yahoo.com> Message-ID: Here is the code then: #This is code for a blackjack game. import random cash = 0 new_cash = 100 cards = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"} card_types = {"Diamond", "Heart", "Spade", "Club"} bet = 0 playertotal = 0 comp_total = 0 def menu(): print "1. Bet and play." print "2. Cash out and Exit" def option(): return int(raw_input("Menu choice: ")) def card_choice(): return random.choice(range(1,14) def types(): return random.choice(range(1,5) def player_cards(): print a," of ",t1 print b," of ",t2 print "Blackjack" print "By Nathan Pinno" while 1: menu() choice = option() if choice == 1: bet = int(raw_input("How much do you want to bet: ") while 1: if bet > new_cash: print "Sorry, you don't have that much cash! Your total cash is: $",new_cash else: break a,b = card_choice() t1,t2 = types() if t1 == 1: t1 = card_types[0] elif t1 == 2: t1 = cardtypes[1] elif t1 == 3: t1 = cardtypes[2] else: t1 = cardtypes[3] if a == 1: a = cards[0] playertotal = playertotal + 1 elif a == 2: a = cards[1] playertotal = playertotal + 2 Now do you have an idea of what I'm pointing to? ----- Original Message ----- From: Bob Gailer To: Nathan Pinno ; Tutor mailing list Sent: Wednesday, August 03, 2005 12:28 PM Subject: Re: [Tutor] I need advice about which way to go. At 11:12 AM 8/3/2005, Nathan Pinno wrote: Sorry about that, I thought it was clear that n = number randomly chosen. I was thinking of if the number was a five, it would choose a card with a five on it. I don't want to have to code stuff that I have to repeat again and again. That's what classes, loops and functions are for. I'm not worrying about card types, I have that figured out separately. The two games are indeed separate, too much trouble to do them a 1 program that can play both games. Maybe I should have shown my code and asked using the code as a visual reference. Good idea. How about now? Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/98c3c1ee/attachment.htm From falcon3166 at hotmail.com Wed Aug 3 20:42:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 12:42:36 -0600 Subject: [Tutor] I've run into a jam on the exercise on file I/O References: <059901c59735$db8da080$8eaa8651@xp> Message-ID: I've been chatting with Albertito on MSN and came up with this solution: int(x), and change student into student ids, and remove #Max. Will this work, or will I need to add sequential IDs? ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Yoo, Danny" ; "Bark, Adam" Cc: "Tutor" Sent: Tuesday, August 02, 2005 1:43 AM Subject: Re: [Tutor] I've run into a jam on the exercise on file I/O > >> What if I were to use ID's for the students and use the ID's as the >> sequence >> index, and link the students and their grades to the IDs? > > Its not necessary for what you are doing but it's how you'd normally do it > in a relational database, so if you ever needed to turn your file based > program into a full blown database then using IDs would actually help! > > The other thing you could do is hold all the data for a single student > in one structure. Thus instead of having lots of lists all linked by > a common index (or ID) you have one collection of students (probably > a dictionary keyed by name) each with all of its own data. This > involves a more complex data structure and is a move in the direction > of object oriented programming but without actual classes and objects > being involved. This might also allow you to use the shelve moduile > to save/restore your data to file easily. > > Just a thought, > > Alan G. > From alan.gauld at freenet.co.uk Wed Aug 3 20:45:18 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 19:45:18 +0100 Subject: [Tutor] CVS for Python References: <61d0e2b40508031100174399bb@mail.gmail.com> Message-ID: <07c601c5985b$7f36a260$8eaa8651@xp> > Does anyone can recomment a good CVS for Python? CVS? What exactly do you want beyond the standard tool? Alan G. From 3dbernard at gmail.com Wed Aug 3 20:52:14 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 3 Aug 2005 14:52:14 -0400 Subject: [Tutor] CVS for Python In-Reply-To: <07c601c5985b$7f36a260$8eaa8651@xp> References: <61d0e2b40508031100174399bb@mail.gmail.com> <07c601c5985b$7f36a260$8eaa8651@xp> Message-ID: <61d0e2b405080311521216b102@mail.gmail.com> Okay sorry for not being clear. I meant CVS for my own Python scripts. Right now, when I make a change to an existing script, I copy it into an "old" directory, rename with to append the version number, and overrwrite the actual script with the new version. This works well but sometimes is a pain to handle when multiple files are involved in toolsets. Thanks Bernard On 8/3/05, Alan G wrote: > > Does anyone can recomment a good CVS for Python? > > CVS? > > What exactly do you want beyond the standard tool? > > Alan G. > > From kent37 at tds.net Wed Aug 3 20:58:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Aug 2005 14:58:48 -0400 Subject: [Tutor] HTML/text formatting question In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5558E29@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F5558E29@medexch2.medplus.com> Message-ID: <42F113E8.5070605@tds.net> Smith, Jeff wrote: > I have a tool that outputs data in either html or text output. > > Currently I'm writing chucks like: > > if html: > print '' > print '' > print ' And you overwrite the #mail# with scott at python.org You will end up with: Which will not display the way you want! > def insertdata(name, data): > file = open('template.html', 'r+') > contents = file.read() > pos = contents.index(name) > file.seek(pos) > file.write(data) This does not insert it overwrites. You are better to insert the content into contents and then just write it all back to the file in one move. > file.write(contents[pos + len(name):]) > file.close() HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lists at janeden.org Fri Aug 26 14:54:26 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 26 Aug 2005 14:54:26 +0200 Subject: [Tutor] Instance attribute as a parameter's default value Message-ID: Hi, I need to use an instance attribute as the default value for a parameter to a method. This obviously won't work: page.Children() def Children(self, id=self.id, level=2): How can I get the id parameter to use the attribute page.id? I know I could simply use the method call page.Children(id=page.id) but I thought it is much more elegant to use a default value here. Is it possible? TIA, Jan -- The day Microsoft makes something that doesn't suck is the day they start selling vacuum cleaners. From lists at janeden.org Fri Aug 26 15:01:04 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 26 Aug 2005 15:01:04 +0200 Subject: [Tutor] Instance attribute as a parameter's default value In-Reply-To: Message-ID: Hi, Jan Eden wrote on 26.08.2005: >Hi, > >I need to use an instance attribute as the default value for a parameter to a >method. > >This obviously won't work: > >page.Children() > >def Children(self, id=self.id, level=2): > >How can I get the id parameter to use the attribute page.id? I know I could >simply use the method call > >page.Children(id=page.id) > >but I thought it is much more elegant to use a default value here. > >Is it possible? Addition: I do use def Children(self, id=0, level=2): if not id: id = self.id right now. But still - there has to be a smarter way. Thanks, Jan -- Any sufficiently advanced technology is insufficiently documented. From pierre.barbier at cirad.fr Fri Aug 26 15:15:05 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 26 Aug 2005 15:15:05 +0200 Subject: [Tutor] Instance attribute as a parameter's default value In-Reply-To: References: Message-ID: <430F15D9.7040505@cirad.fr> Jan Eden a ?crit : > Hi, > > Jan Eden wrote on 26.08.2005: > > >>Hi, >> >>I need to use an instance attribute as the default value for a parameter to a >>method. >> >>This obviously won't work: >> >>page.Children() >> >>def Children(self, id=self.id, level=2): >> >>How can I get the id parameter to use the attribute page.id? I know I could >>simply use the method call >> >>page.Children(id=page.id) >> >>but I thought it is much more elegant to use a default value here. >> >>Is it possible? > > > Addition: I do use > > def Children(self, id=0, level=2): > if not id: id = self.id > > right now. But still - there has to be a smarter way. Well, I prefer the use of "None" for that, as it cannot be mixed up with any other value: def Children(self, id=None, level=2): if id is None: id = self.id Another possibility (mainly if you have many such arguments) is the use of something like: def Children(self, **kwords): id = kwords.pop("id", None) level = kwords.pop("level", 2) Although it is not equivalent ! In the second cases, you have to name the parameter to set it ! But I sometimes find this A Good Thing (tm) when no argument order is better ... Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Fri Aug 26 15:28:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 09:28:16 -0400 Subject: [Tutor] Working with files In-Reply-To: <00e601c5aa36$04d0b5f0$52199c51@xp> References: <430CDED8.6070304@scottoertel.info><6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> <430E3E67.60205@scottoertel.info> <00e601c5aa36$04d0b5f0$52199c51@xp> Message-ID: <430F18F0.5020201@tds.net> Alan G wrote: > ARe you sure? The problem using seek and write is that if the data > you are inserting is bigger than your marker you will overwrite the > data following the marker. Alan, you missed the last part of the code - he writes the rest of the data following the match into the file. This is an innovative approach which may have some benefit over the usual / read the whole file / change the data in memory / write the whole file / method as it avoids re-writing the part of the file before the change. It also avoids making a new string with the modified data. These could be significant benefits if the data is very large. > This does not insert it overwrites. > You are better to insert the content into contents and > then just write it all back to the file in one move. > > >> file.write(contents[pos + len(name):]) >> file.close() This is the piece you missed. ^^^^ Kent From kent37 at tds.net Fri Aug 26 15:32:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 09:32:02 -0400 Subject: [Tutor] Instance attribute as a parameter's default value In-Reply-To: References: Message-ID: <430F19D2.4080506@tds.net> Jan Eden wrote: > Hi, > > Jan Eden wrote on 26.08.2005: > > >>Hi, >> >>I need to use an instance attribute as the default value for a parameter to a >>method. >> >>This obviously won't work: >> >>page.Children() >> >>def Children(self, id=self.id, level=2): >> >>How can I get the id parameter to use the attribute page.id? I know I could >>simply use the method call >> >>page.Children(id=page.id) >> >>but I thought it is much more elegant to use a default value here. >> >>Is it possible? > > > Addition: I do use > > def Children(self, id=0, level=2): > if not id: id = self.id > > right now. But still - there has to be a smarter way. Other than using None instead of 0 as Pierre suggests, this is the best way. The problem is that the default argument is bound when the function definition is executed, so the value has to be defined at that time and it is then fixed. To use a (changeable) attribute as the default you have to read it when the function body is executed. Kent From albertito_g at hotmail.com Fri Aug 26 15:50:04 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 26 Aug 2005 13:50:04 +0000 Subject: [Tutor] Generate 8 digit random number Message-ID: Hi everyone I need to generate a password..It has to be an 8 digit number and it has to be random The code I've been trying is the following: import random random.randrange(00000000,99999999) The code works but sometimes it picks a number with 7 digits. Is there any way that I can tell him to select always a random number with 8 digits? Thanks in advanced Alberto From kent37 at tds.net Fri Aug 26 16:00:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 10:00:50 -0400 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <430F2092.4070009@tds.net> Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? random.randrange(10000000,99999999) ?? Kent From albertito_g at hotmail.com Fri Aug 26 16:05:33 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 26 Aug 2005 14:05:33 +0000 Subject: [Tutor] Generate 8 digit random number In-Reply-To: <430F2092.4070009@tds.net> Message-ID: Hi Kent Nope... Not working....I'm still getting 7 even 6 digits number Any other idea? Thanks Alberto >From: Kent Johnson >CC: tutor at python.org >Subject: Re: [Tutor] Generate 8 digit random number >Date: Fri, 26 Aug 2005 10:00:50 -0400 > >Alberto Troiano wrote: > > Hi everyone > > > > I need to generate a password..It has to be an 8 digit number and it has >to > > be random > > > > The code I've been trying is the following: > > > > > > import random > > random.randrange(00000000,99999999) > > > > The code works but sometimes it picks a number with 7 digits. Is there >any > > way that I can tell him to select always a random number with 8 digits? > >random.randrange(10000000,99999999) ?? > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From pierre.barbier at cirad.fr Fri Aug 26 16:12:31 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 26 Aug 2005 16:12:31 +0200 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <430F234F.1090308@cirad.fr> Is "0" a valid digit for your password ? If the answer is "YES" then, remember that the "0" at the left of a number are juste removed ! In that case, try writing your password with : "%08d" % password Pierre Alberto Troiano a ?crit : > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From pietro.ciuffo at nekhem.com Fri Aug 26 16:09:08 2005 From: pietro.ciuffo at nekhem.com (Pietro Ciuffo) Date: Fri, 26 Aug 2005 16:09:08 +0200 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <20050826140908.GA2839@(none)> On Fri, Aug 26, 2005 at 01:50:04PM +0000, Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced Hi, The following code seeems to work. from random import choice lnd='0123456789' print ''.join(map(lambda x,y=lnd: choice(y), range(8))) Bye -- The Old Man and the Sea LITE(tm) -- by Ernest Hemingway 'An old man goes fishing, but doesn't have much luck.' From kent37 at tds.net Fri Aug 26 16:16:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 10:16:37 -0400 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <430F2445.2000802@tds.net> Alberto Troiano wrote: > Hi Kent > > Nope... > Not working....I'm still getting 7 even 6 digits number Are you sure? It works for me: >>> import random >>> random.randrange(10000000,99999999) 42247129 >>> for i in range(1000): ... x = random.randrange(10000000,99999999) ... if len(str(x)) < 8: ... print x ... >>> (prints nothing - they are all 8 digits) Kent > > Any other idea? > > Thanks > > Alberto > >> From: Kent Johnson >> CC: tutor at python.org >> Subject: Re: [Tutor] Generate 8 digit random number >> Date: Fri, 26 Aug 2005 10:00:50 -0400 >> >> Alberto Troiano wrote: >> > Hi everyone >> > >> > I need to generate a password..It has to be an 8 digit number and it >> has to >> > be random >> > >> > The code I've been trying is the following: >> > >> > >> > import random >> > random.randrange(00000000,99999999) >> > >> > The code works but sometimes it picks a number with 7 digits. Is >> there any >> > way that I can tell him to select always a random number with 8 digits? >> >> random.randrange(10000000,99999999) ?? >> >> Kent >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > > From albertito_g at hotmail.com Fri Aug 26 16:31:21 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 26 Aug 2005 14:31:21 +0000 Subject: [Tutor] Generate 8 digit random number In-Reply-To: <430F2445.2000802@tds.net> Message-ID: Hey ALL The code Kent sent might work ok but I didn't see it because of what Pierre said about the left 0's I think I will go with Pietro's approach. I think is neater and shorter than the randrange approach Thanks to all that helped Best Regards Alberto >From: Kent Johnson >CC: tutor at python.org >Subject: Re: [Tutor] Generate 8 digit random number >Date: Fri, 26 Aug 2005 10:16:37 -0400 > >Alberto Troiano wrote: > > Hi Kent > > > > Nope... > > Not working....I'm still getting 7 even 6 digits number > >Are you sure? It works for me: > >>> import random > >>> random.randrange(10000000,99999999) >42247129 > >>> for i in range(1000): > ... x = random.randrange(10000000,99999999) > ... if len(str(x)) < 8: > ... print x > ... > >>> (prints nothing - they are all 8 digits) > >Kent > > > > Any other idea? > > > > Thanks > > > > Alberto > > > >> From: Kent Johnson > >> CC: tutor at python.org > >> Subject: Re: [Tutor] Generate 8 digit random number > >> Date: Fri, 26 Aug 2005 10:00:50 -0400 > >> > >> Alberto Troiano wrote: > >> > Hi everyone > >> > > >> > I need to generate a password..It has to be an 8 digit number and it > >> has to > >> > be random > >> > > >> > The code I've been trying is the following: > >> > > >> > > >> > import random > >> > random.randrange(00000000,99999999) > >> > > >> > The code works but sometimes it picks a number with 7 digits. Is > >> there any > >> > way that I can tell him to select always a random number with 8 >digits? > >> > >> random.randrange(10000000,99999999) ?? > >> > >> Kent > >> > >> _______________________________________________ > >> 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 lopoff at gmx.net Fri Aug 26 18:38:58 2005 From: lopoff at gmx.net (lmac) Date: Fri, 26 Aug 2005 18:38:58 +0200 Subject: [Tutor] find() function an Tupel. Always returns -1. Message-ID: <430F45A2.9080701@gmx.net> hi there, i got a problem with Tupel and the find() function. I know in the document are this Keywords which i am looking for but find() always returns -1. Thanks for the help. fedora_user ------------------------------------------------------------------------ #!/usr/bin/python # -*- coding: utf_8 -*- import string import sys import os import urllib anf_bez = ('Startpreis:','Restzeit:','Angebotsbeginn:','?bersicht:','Artikelstandort:','Versand nach:', 'Artikelnummer:','Kategorie') end_bez = ('','MESZ','MESZ','Gebote','','','','') # Artikelnummer von dem die Infos gespeichert werden artikelno = `sys.argv[1:2]` artikelno = artikelno[2:-2] if len(artikelno) != 0: TARGET_DIR = "/opt/internet/eBay/" EBAY_HTTP = "http://cgi.ebay.de/ws/eBayISAPI.dll?ViewItem&item=" EBAY_PAGE = EBAY_HTTP + artikelno SAVE_PAGE = "" SAVE_PAGE = SAVE_PAGE + "eBay-artikel" + artikelno + ".html" SAVE_PAGE = os.path.join(TARGET_DIR,SAVE_PAGE) # webSite laden und speichern urllib.urlretrieve(EBAY_PAGE,SAVE_PAGE) # webSite ?ffnen und absuchen file = open(SAVE_PAGE,"rt") for a in file: asi = 0 # Suchindex f?r 'anf_bez' esi = 0 # Suchindex f?r 'end_bez' while asi < 8: anf = -1 end = -1 anf = a.find( anf_bez[asi] ) # <------------ always returns -1, never find anything ????? ----------------- if anf != -1: end = a[anf].find( end_bez[esi] ) if end != -1: print a[anf:end] asi = asi+1 esi = esi+1 print asi,esi print EBAY_PAGE print SAVE_PAGE else: print "Artikelnummer als Argument ?bergeben." ------------------------------------------------------------------------ From dyoo at hkn.eecs.berkeley.edu Fri Aug 26 18:53:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Aug 2005 09:53:34 -0700 (PDT) Subject: [Tutor] Beautiful Soup / Unicode problem? In-Reply-To: Message-ID: > Here you go: > > >>> import types > >>> print types.StringTypes > (, ) > >>> import sys > >>> print sys.version > 2.3.4 (#2, May 29 2004, 03:31:27) > [GCC 3.3.3 (Debian 20040417)] > >>> print type(u'hello' in types.StringTypes > True > >>>sys.getdefaultencoding() > 'ascii' [CCing Leonard Richardson: we found a bug and a correction to the code. See below.] Ok, this is officially a mystery. *grin* Let me try some tests too. ###### >>> import BeautifulSoup >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> import re >>> result = soup.fetchText(re.compile('.*')) Traceback (most recent call last): File "", line 1, in ? File "BeautifulSoup.py", line 465, in fetchText return self.fetch(recursive=recursive, text=text, limit=limit) File "BeautifulSoup.py", line 491, in fetch return self._fetch(name, attrs, text, limit, generator) File "BeautifulSoup.py", line 193, in _fetch if self._matches(i, text): File "BeautifulSoup.py", line 251, in _matches chunk = str(chunk) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 0: ordinal not in range(128) ###### Gaaa! Ok, that's not right. Well, at least I'm seeing the same results as you. *grin* This seems like a bug in BeautifulSoup; let me look at the flow of values again... ah! I see. That was silly. The problem is that 'chunk' can be a NavigableString or a NavigatableUnicodeString, and neither of those types are in types.StringType. So the bit of code here: if not type(chunk) in types.StringTypes: never worked properly. *grin* A possible fix to this is to change the check for direct types into a check for subclass or isinstance; we can to change the line in BeautifulSoup.py:250 from: if not type(chunk) in types.StringTypes: to: if not isinstance(chunk, basestring): Testing the change now... ###### >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> result = soup.fetchText(re.compile('.*')) >>> result [u'\xbb'] ###### Ah, better. *grin* One other problem is the implementation of __repr__(); I know it's convenient for it to delegate to str(), but that poses a problem: ###### >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> soup Traceback (most recent call last): File "", line 1, in ? File "BeautifulSoup.py", line 374, in __repr__ return str(self) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 6: ordinal not in range(128) ###### repr() should never fail like this, regardless of our default encoding. The cheap way out might be to just not implement repr(), but that's probably not so nice. *grin* I'd have to look at the implementation of __str__() some more and see if there's a good general way to fix this. Best of wishes! From grouch at gmail.com Fri Aug 26 18:08:34 2005 From: grouch at gmail.com (grouchy) Date: Fri, 26 Aug 2005 11:08:34 -0500 Subject: [Tutor] Beautiful Soup / Unicode problem? In-Reply-To: References: Message-ID: Hi Danny, > If you have a moment, do you mind doing this on your system? > Here you go: >>> import types >>> print types.StringTypes (, ) >>> import sys >>> print sys.version 2.3.4 (#2, May 29 2004, 03:31:27) [GCC 3.3.3 (Debian 20040417)] >>> print type(u'hello' in types.StringTypes True >>>sys.getdefaultencoding() 'ascii' I have a second machine running XP and Activestate 2.4.1, I get the same results with the exception of: >>> sys.version '2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)]' Today I tried changing my default encoding to uft8, and the error went away. I have no idea -why- it would go away, and it feels like a hacky solution. And confusing, because I wasn't trying to print anything to the screen, so why would python care or complain? Almost forgot, I tried the included Beautiful Soup tests on both machines and got an error on both: # python BeautifulSoupTests.py ...........................E.... ====================================================================== ERROR: testBasicUnicode (__main__.UnicodeRed) ---------------------------------------------------------------------- Traceback (most recent call last): File "BeautifulSoupTests.py", line 209, in testBasicUnicode self.assertEqual(type(str(self.soup)), sType) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc8' in position 13: ordinal not in range(128) So there may be a bug, but I don't know if it's my problem It's strange that the tests fail on two different computers running two versions of python, however. > > and show us what comes up? > > > > Good luck to you! > > From grouch at gmail.com Fri Aug 26 18:57:44 2005 From: grouch at gmail.com (grouchy) Date: Fri, 26 Aug 2005 11:57:44 -0500 Subject: [Tutor] Beautiful Soup / Unicode problem? Message-ID: >This is the first question in the BeautifulSoup FAQ at >http://www.crummy.com/software/BeautifulSoup/FAQ.html >Unfortunately the author of BS considers this a problem with your Python installation! So it >seems he doesn't have a good understanding of Python and Unicode. (OK, I can forgive him >that, I think there are only a handful of people who really do understand it completely.) >The first fix given doesn't work. The second fix works but it is not a good idea to change the >default encoding for your Python install. There is a hack you can use to change the default >encoding just for one program; in your program put > reload(sys); sys.setdefaultencoding('utf-8') >This seems to fix the problem you are having. >Kent Hi Kent, I did read the FAQ before posting, honest :) But it does seem to be addressing a different issue. He says to try: >>> latin1word = 'Sacr\xe9 bleu!' >>> unicodeword = unicode(latin1word, 'latin-1') >>> print unicodeword Sacr? bleu! Which worked fine for me. And then he gives a solution for fixing -display- problems on the terminal. For instance, his first solution was : "The easy way is to remap standard output to a converter that's not afraid to send ISO-Latin-1 or UTF-8 characters to the terminal." But I avoided displaying anything in my original example, because I didn't want to confuse the issue. It's also why I didn't mention the damning FAQ entry: >>> y = results[1].a.fetchText(re.compile('.+')) Is all I am trying to do. I don't expect non-ASCII characters to display correctly, however I was suprised when I tried "print x" in my original example, and it printed. I would have expected to have to do something like: >>> print x.encode("utf8") Matt Croydon::Postneo 2.0 ? Blog Archive ? Mobile Screen Scraping ... I've just looked, and I have to do this explicit encoding under python 2.3.4, but not under 2.4.1. So perhaps 2.4 is less afraid/smarter about converting and displaying non-ascii characters to the terminal. Either way, I don't -think- that's my problem with Beautiful Soup. Changing my default encoding does indeed fix it, but it may be a reflection of the author making bad assumptions because his default was set to utf-8. I'm not really experienced enough to tell what is going on in his code, but I've been trying. Does seem to defeat the point of unicode, however. From byron at christianfreebies.com Fri Aug 26 22:49:41 2005 From: byron at christianfreebies.com (Byron) Date: Fri, 26 Aug 2005 13:49:41 -0700 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <430F8065.3050600@christianfreebies.com> Hi Alberto, Here's how to do it: ------------------------------- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 10000): generateKey() count += 1 ------------------------------- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john.ertl at fnmoc.navy.mil Fri Aug 26 23:23:07 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Fri, 26 Aug 2005 14:23:07 -0700 Subject: [Tutor] Generate 8 digit random number Message-ID: Alberto If you don't mind having leading 0 then you could just do the random like you did then format it to 9 digits. You could give this a try num = random.randrange(00000000,99999999) num8 = "%09i" % num John Ertl -----Original Message----- From: Byron [mailto:byron at christianfreebies.com] Sent: Friday, August 26, 2005 1:50 PM To: Alberto Troiano; tutor at python.org Subject: Re: [Tutor] Generate 8 digit random number Hi Alberto, Here's how to do it: ------------------------------- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 10000): generateKey() count += 1 ------------------------------- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > _______________________________________________ > 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 john.ertl at fnmoc.navy.mil Fri Aug 26 23:26:27 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Fri, 26 Aug 2005 14:26:27 -0700 Subject: [Tutor] Generate 8 digit random number Message-ID: Sorry for that you will have to change the %09 to a %08 to get 8 digits. I got a bit to fixated on the 99999999 John Ertl -----Original Message----- From: Ertl, John Sent: Friday, August 26, 2005 2:23 PM To: Alberto Troiano; tutor at python.org Subject: RE: [Tutor] Generate 8 digit random number Alberto If you don't mind having leading 0 then you could just do the random like you did then format it to 9 digits. You could give this a try num = random.randrange(00000000,99999999) num8 = "%09i" % num John Ertl -----Original Message----- From: Byron [mailto:byron at christianfreebies.com] Sent: Friday, August 26, 2005 1:50 PM To: Alberto Troiano; tutor at python.org Subject: Re: [Tutor] Generate 8 digit random number Hi Alberto, Here's how to do it: ------------------------------- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 10000): generateKey() count += 1 ------------------------------- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > _______________________________________________ > 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 ukc802591034 at btconnect.com Sat Aug 27 00:01:55 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Fri, 26 Aug 2005 23:01:55 +0100 Subject: [Tutor] Working with files References: <430CDED8.6070304@scottoertel.info><6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> <430E3E67.60205@scottoertel.info><00e601c5aa36$04d0b5f0$52199c51@xp> <430F18F0.5020201@tds.net> Message-ID: <005201c5aa89$e05e8720$0201a8c0@xp> > Alan, you missed the last part of the code - he writes the rest of > the data following the match into the file. I didn't miss it but I did misread it! :-) > file.write(contents[pos + len(name):]) I assumed 'name' was here referring to the actual value inserted. But of course that would have been a different bug to the one I described. > This is an innovative approach which may have some benefit over the > usual / read the whole file / change the data in memory / write the > whole file / method as it avoids re-writing the part of the file > before the change. Yes indeed, now that I actually see what's happening it's quite cute! > It also avoids making a new string with the modified data. True but it does involve a new string fom the slice, so I wouldn't expect a huge saving there. But the random file access should be faster than a full rewrite operation. Thanks for pointing out my mistake and my compliments to the OP! Alan G. From ukc802591034 at btconnect.com Sat Aug 27 00:02:59 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Fri, 26 Aug 2005 23:02:59 +0100 Subject: [Tutor] Generate 8 digit random number References: Message-ID: <005501c5aa89$ebd60380$0201a8c0@xp> > I need to generate a password..It has to be an 8 digit number and it > has to be random I assume you mean a string representing an 8 digit random number? If so... > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is > there any way that I can tell him to select always a random number > with 8 digits? Eventually it will generate a single digit number if its truly random! But when you convert it to a string (see assumption above!) you can pad it with zeros passString = "%08d" % random.randrange(0,99999999) Is that what you want? Alan G. From carroll at tjc.com Sat Aug 27 00:06:05 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 26 Aug 2005 15:06:05 -0700 (PDT) Subject: [Tutor] Generate 8 digit random number In-Reply-To: Message-ID: On Fri, 26 Aug 2005, Alberto Troiano wrote: > I need to generate a password..It has to be an 8 digit number and it has > to be random > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? well, you've gotten a lot of good answers, so let me chime in with a really ugly one: >>> ''.join(['0000000',str(random.randrange(00000000,99999999))])[-8:] '00101381' (I don't really recommend this, but this is pretty much akin to the prefered way in IBM's EXEC2 language as I used to use it some 25 years ago!) From arcege at gmail.com Sat Aug 27 01:52:04 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Fri, 26 Aug 2005 19:52:04 -0400 Subject: [Tutor] Generate 8 digit random number In-Reply-To: References: Message-ID: <7e5ba92205082616521bb8f41@mail.gmail.com> On 8/26/05, Alberto Troiano wrote: > > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has > to > be random > > The code I've been trying is the following: > > > import random > random.randrange(00000000,99999999) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > Along with everyone else's solutions, I'll throw out: str(random.randrange(99999999)).zfill(8) -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050826/7d169729/attachment.html From ukc802591034 at btconnect.com Sat Aug 27 02:33:52 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 27 Aug 2005 01:33:52 +0100 Subject: [Tutor] Strange XP stdin behaviour. Message-ID: <009901c5aa9f$0008b5e0$0201a8c0@xp> Hi gang, a strange one uncovered by a student of my tutorial. If you create the following example program, lets call it intest.py: ####### intest.py ##### inp = raw_input() while inp != '': print inp inp = raw_input() ####################### And the following data file -------- Not part of in.txt ----- 6 7 8 -------- Not part of in.txt ----- Then run Python from a DOS prompt like so: C:\somepath> pythopn intest.py < in.txt The file content is echo'd as expected. But if you start it: C:\somepath> intest.py < in.txt There is no output! In fact, I get an error: E:\PROJECTS\Python>intest.py < in.txt Traceback (most recent call last): File "E:\PROJECTS\Python\intest.py", line 2, in ? inp = raw_input() EOFError: EOF when reading a line And if you run C:\somepath> intest.py You get the interactive version as expected. Why the difference with the redirected file? I am confused. What am I missing? XP seems to have a different runtime environment depending on how the script is run... BTW This also happens under cygwin. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050827/05554dc4/attachment.htm From dyoo at hkn.eecs.berkeley.edu Sat Aug 27 02:54:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Aug 2005 17:54:40 -0700 (PDT) Subject: [Tutor] Strange XP stdin behaviour. In-Reply-To: <009901c5aa9f$0008b5e0$0201a8c0@xp> Message-ID: > C:\somepath> intest.py < in.txt > > There is no output! > In fact, I get an error: > > E:\PROJECTS\Python>intest.py < in.txt > Traceback (most recent call last): > File "E:\PROJECTS\Python\intest.py", line 2, in ? > inp = raw_input() > EOFError: EOF when reading a line Hi Alan, Yes, this is a Windows-specific thing. Unfortunately, Windows's treatment of shell scripts is slightly inconsistant. However, there are workarounds by making a '.CMD' file. See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366355 for details. Hope this helps! From ukc802591034 at btconnect.com Sat Aug 27 08:55:37 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 27 Aug 2005 07:55:37 +0100 Subject: [Tutor] Strange XP stdin behaviour. References: Message-ID: <009f01c5aad4$54d570b0$0201a8c0@xp> >> C:\somepath> intest.py < in.txt >> >> There is no output! >> In fact, I get an error: > > Yes, this is a Windows-specific thing. Unfortunately, Windows's > treatment > of shell scripts is slightly inconsistant. However, there are > workarounds > by making a '.CMD' file. See: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366355 > Thanks Danny, interesting link in that it shows a solution I didn't know about in the one-liner at the bottom of the discussion. But really I was hoping someone could explain *why* there is a difference. If PATHEXT can detect that intest.py needs to be run through Python why doesn't redirection work as expected? What is happening to stdin/stdout in this case? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From andreas at kostyrka.org Fri Aug 26 19:39:40 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 26 Aug 2005 19:39:40 +0200 Subject: [Tutor] Should I be thinking of threads for this ? In-Reply-To: <430E1BED.6020709@javacat.f2s.com> References: <430E1BED.6020709@javacat.f2s.com> Message-ID: <1125077980.13864.3.camel@andi-lap> Am Donnerstag, den 25.08.2005, 20:28 +0100 schrieb Nick Lunt: > Hello folks, > > I have the following code taken from the Twisted examples - > > [code] > # filewatcher.py > from twisted.application import internet > > def watch(fp): > fp.seek(fp.tell()) > for line in fp.readlines(): > sys.stdout.write(line) > > import sys > from twisted.internet import reactor > s = internet.TimerService(1.0, watch, file(sys.argv[1])) s = [internet.TimerService(1.0, watch, file(x) for x in sys.argv[1:]] for x in s: x.startService() > s.startService() > reactor.run() > s.stopService() > [/code] > > I find this piece of code amazing and I am keen to put it to use. > If I run './filewatcher.py myfile' it will print out any changes made to > 'myfile', very similar to 'tail -f' . > > Now if I want to have this program monitor several files at once I could > run './filewatcher.py file1 file2 filex' or './filewatcher.py file1 & > ./filewatcher file2 & etc' both with minor modifications to the code, Well, compared to threads, executing a stat and/or read (I guess it goes the read way, which is interesting, usually one watches files by doing stat) is not relevant. > but I think that could cause performance problems relating to the OS. > So I'm thinking I will need to learn python threads (no bad thing) How would adding Threads to the mix solve any performance problems *g* Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20050826/d959ebd8/attachment.pgp From albertito_g at hotmail.com Sat Aug 27 15:36:47 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Sat, 27 Aug 2005 13:36:47 +0000 Subject: [Tutor] Generate 8 digit random number Message-ID: Hey Tutors I saw a lot of responses...After analyze them I have resumed two approaches 1.- Generate a random number from 0 to 99999999 and fill this number with zeros (Almost everyone's approach) 2.- Generate 8 random numbers and join them (Pietro and someone else) Which one of this is more randomic? I mean which one of these has lower chances to get duplicates? Until now I'm using approach number 2.......Unless anyone has something against it... Please, let me know what do you think about them Thanks to all for the tremendous help (at least it is tremendous for me) Alberto From kent37 at tds.net Sat Aug 27 15:47:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 27 Aug 2005 09:47:44 -0400 Subject: [Tutor] Should I be thinking of threads for this ? In-Reply-To: <430E1BED.6020709@javacat.f2s.com> References: <430E1BED.6020709@javacat.f2s.com> Message-ID: <43106F00.4060502@tds.net> Nick Lunt wrote: > Hello folks, > > I have the following code taken from the Twisted examples - > > [code] > # filewatcher.py > from twisted.application import internet > > def watch(fp): > fp.seek(fp.tell()) > for line in fp.readlines(): > sys.stdout.write(line) > > import sys > from twisted.internet import reactor > s = internet.TimerService(1.0, watch, file(sys.argv[1])) > s.startService() > reactor.run() > s.stopService() > [/code] > > I find this piece of code amazing and I am keen to put it to use. > If I run './filewatcher.py myfile' it will print out any changes made to > 'myfile', very similar to 'tail -f' . > > Now if I want to have this program monitor several files at once I could > run './filewatcher.py file1 file2 filex' or './filewatcher.py file1 & > ./filewatcher file2 & etc' both with minor modifications to the code, > but I think that could cause performance problems relating to the OS. > So I'm thinking I will need to learn python threads (no bad thing) > instead, but Im hoping that someone could tell me if that seems the best > way to go ? What performance problems you you anticipate? I don't know much about Twisted but my understanding is that tasks are run in a single thread when they are ready. In your case you are scheduling a simple task to run every second. I would think that you could schedule several such tasks and they would each run every second. If your task were time-consuming you might have to worry about doing something different but in this case I think it will be fine. Just try something like for name in sys.argv[1:]: s = internet.TimerService(1.0, watch, file(name)) s.startService() I suppose if you used threads there would be the possibility of a context switch while watch() is running, if one thread becomes blocked on I/O then another thread can run. I don't know how Twisted handles this - I think you have to wrap the file and stdio in Twisted object that handle the blocking. twisted.protocols.basic.FileSender and twisted.internet.stdio.StandardIO look like they may be starting points. Kent From tim.peters at gmail.com Sat Aug 27 17:30:44 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 27 Aug 2005 11:30:44 -0400 Subject: [Tutor] Strange XP stdin behaviour. In-Reply-To: <009f01c5aad4$54d570b0$0201a8c0@xp> References: <009f01c5aad4$54d570b0$0201a8c0@xp> Message-ID: <1f7befae05082708305afed0fb@mail.gmail.com> [Alan Gauld] > Thanks Danny, interesting link in that it shows a solution I > didn't know about in the one-liner at the bottom of the discussion. > > But really I was hoping someone could explain *why* there is a > difference. If PATHEXT can detect that intest.py needs to be run > through Python why doesn't redirection work as expected? What > is happening to stdin/stdout in this case? Alas, only Microsoft could explain this, and AFAIK they never really have. It's not unique to Python, of course. Here's a confused MS article about it: http://support.microsoft.com/default.aspx?scid=kb;en-us;321788 _Some_ of the PATHEXT-related redirection bugs did get fixed in XP, but not all of them. I haven't tried adding the registry entry they suggest there. The HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer key doesn't even exist on my XP (Pro, SP2) box, but does exist if I start from HKEY_CURRENT_USER instead. From nick at javacat.f2s.com Sat Aug 27 18:22:30 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat, 27 Aug 2005 17:22:30 +0100 Subject: [Tutor] Should I be thinking of threads for this ? In-Reply-To: <43106F00.4060502@tds.net> Message-ID: Hi Kent, > > > > [code] > > # filewatcher.py > > from twisted.application import internet > > > > def watch(fp): > > fp.seek(fp.tell()) > > for line in fp.readlines(): > > sys.stdout.write(line) > > > > import sys > > from twisted.internet import reactor > > s = internet.TimerService(1.0, watch, file(sys.argv[1])) > > s.startService() > > reactor.run() > > s.stopService() > > [/code] > > > > What performance problems you you anticipate? I don't know much > about Twisted but my understanding is that tasks are run in a > single thread when they are ready. In your case you are > scheduling a simple task to run every second. I would think that > you could schedule several such tasks and they would each run > every second. If your task were time-consuming you might have to > worry about doing something different but in this case I think it > will be fine. Just try something like > > for name in sys.argv[1:]: > s = internet.TimerService(1.0, watch, file(name)) > s.startService() > That's one way I was thinking of doing it. I'll run it like that on about 10 active files and see how it stacks up. > twisted.protocols.basic.FileSender and > twisted.internet.stdio.StandardIO look like they may be starting points. Thanks for the twisted pointers. I've been using twisted for a little while but it's such a massive thing that it can be difficult to fully understand whats happening. Thanks for you help, Nick . From ukc802591034 at btconnect.com Sat Aug 27 20:52:04 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 27 Aug 2005 19:52:04 +0100 Subject: [Tutor] Strange XP stdin behaviour. References: <009f01c5aad4$54d570b0$0201a8c0@xp> <1f7befae05082708305afed0fb@mail.gmail.com> Message-ID: <000501c5ab38$6aa36aa0$0201a8c0@xp> >> But really I was hoping someone could explain *why* there is a >> difference. If PATHEXT can detect that intest.py needs to be run >> through Python why doesn't redirection work as expected? What >> is happening to stdin/stdout in this case? > > Alas, only Microsoft could explain this, and AFAIK they never really >have. It's not unique to Python, of course. Here's a confused MS >article about it: > > http://support.microsoft.com/default.aspx?scid=kb;en-us;321788 The timbot thus spoke. And if you don't know Tim then I guess I can feel slightly better about never having come across this bizarre "feature" before. :-) Thanks for the link. Alan G. From ukc802591034 at btconnect.com Sat Aug 27 21:37:44 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 27 Aug 2005 20:37:44 +0100 Subject: [Tutor] Strange XP stdin behaviour. References: <009f01c5aad4$54d570b0$0201a8c0@xp> <1f7befae05082708305afed0fb@mail.gmail.com> Message-ID: <002f01c5ab3e$cc083860$0201a8c0@xp> > have. It's not unique to Python, of course. Here's a confused MS > article about it: > > http://support.microsoft.com/default.aspx?scid=kb;en-us;321788 > > _Some_ of the PATHEXT-related redirection bugs did get fixed in XP, > but not all of them. I haven't tried adding the registry entry they > suggest there. The key doesn't even exist on my XP (Pro, SP2) box, > but does exist if I start from HKEY_CURRENT_USER instead. The key is indeed in the wrong place but when you apply the fix it works! Alan G. From tlinux at comcast.net Sun Aug 28 05:27:23 2005 From: tlinux at comcast.net (Tom Strickland) Date: Sat, 27 Aug 2005 22:27:23 -0500 Subject: [Tutor] Importing a List from Module Message-ID: <43112F1B.9030602@comcast.net> I have a module called "enterData" which generates a list, "close" from a data file. "close" is a list of floats. When I put a print statement in that module it will print out an individual member of the list. For example, print close[0] prints the first member of the list. In my "main" module I import "enterData" and try to read the first element of "close" as follows: import enterData xy=enterData.close print xy[0] When I do this it prints out the entire "close" list, not just the first term. What's my mistake and how do I correct it? Thank you! From kent37 at tds.net Sun Aug 28 06:15:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 28 Aug 2005 00:15:15 -0400 Subject: [Tutor] Importing a List from Module In-Reply-To: <43112F1B.9030602@comcast.net> References: <43112F1B.9030602@comcast.net> Message-ID: <43113A53.2010308@tds.net> Tom Strickland wrote: > I have a module called "enterData" which generates a list, "close" from > a data file. "close" is a list of floats. When I put a print statement > in that module it will print out an individual member of the list. For > example, > > print close[0] > > > prints the first member of the list. > > In my "main" module I import "enterData" and try to read the first > element of "close" as follows: > > import enterData > xy=enterData.close > print xy[0] > > > When I do this it prints out the entire "close" list, not just the first > term. > > What's my mistake and how do I correct it? What you have shown here looks fine to me. Can you show some more of enterData? Kent From byron at christianfreebies.com Sun Aug 28 06:25:36 2005 From: byron at christianfreebies.com (Byron) Date: Sat, 27 Aug 2005 21:25:36 -0700 Subject: [Tutor] Importing a List from Module In-Reply-To: <43112F1B.9030602@comcast.net> References: <43112F1B.9030602@comcast.net> Message-ID: <43113CC0.9050200@christianfreebies.com> Tom Strickland wrote: > In my "main" module I import "enterData" and try to read the first > element of "close" as follows: > > import enterData > xy=enterData.close > print xy[0] > > > When I do this it prints out the entire "close" list, not just the first > term. Hi Tom, I would create a function in your module that returns the list. Here's a quick, simplified example: def returnList(): newList = [] newList += [123.45] newList += [529.59] newList += [259.92] return newList aList = returnList() print aList Note the return statement... This enables assignment, as you have done in "xy=enterData.returnList()" Hope this helps, Byron --- From alan.gauld at freenet.co.uk Sun Aug 28 16:41:27 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 28 Aug 2005 15:41:27 +0100 Subject: [Tutor] New Tutorial topic Message-ID: <00c201c5abde$927ea570$0201a8c0@xp> Hi gang, I've just uploaded two new files to my tutorial. The first explains a new section in the tutor aimed at highlighting practical applications of the language, the second is the first of these and introduces databases, SQL and using the Python DBI interface. Enjoy, and as ever feedback is welcomed. Note that neither of these appears in the zip bundle as yet. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tlinux at comcast.net Sun Aug 28 17:17:29 2005 From: tlinux at comcast.net (Tom Strickland) Date: Sun, 28 Aug 2005 10:17:29 -0500 Subject: [Tutor] Importingf a List from Module In-Reply-To: References: Message-ID: <4311D589.9050508@comcast.net> Tom Strickland wrote: >>Here are the modules in question: >> >> > ####This is the main.py module > > #!/usr/bin/python2.4 > import enterData > import movAvg > smavg=[] > xy=enterData.close > print xy[0] > smavg = movAvg.sma(20,enterData.close) > emavg=[] > emavg=movAvg.ema(20,enterData.close) > import stoResults > stoResults.store(enterData.date, enterData.close,smavg,emavg) > print "Finished" > > > ######This is the enterData.py module > ##!/usr/bin/python2.4 > input = open('/home/tom/Python/Input/SPY2.csv', 'r') > s = input > date =[] > open = [] > close = [] > hi = [] > lo = [] > vol = [] > for s in input: > s = s[:-2] > y =[] > y = s.split(',') > date.append(y[0]) > open.append(float(y[1])) > hi.append(float(y[2])) > lo.append(float(y[3])) > close.append(float(y[4])) > vol.append(float(y[5])) > input.close() > for i in range(5): > print close[i] > print 'enterData.py' > > > > > *********************************************************************************************************************************** > > >>------------------------------ >> >>Message: 7 >>Date: Sat, 27 Aug 2005 22:27:23 -0500 >>From: Tom Strickland >>Subject: [Tutor] Importing a List from Module >>To: tutor at python.org >>Message-ID: <43112F1B.9030602 at comcast.net> >>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >>I have a module called "enterData" which generates a list, "close" from >>a data file. "close" is a list of floats. When I put a print statement >>in that module it will print out an individual member of the list. For >>example, >> >> print close[0] >> >> >>prints the first member of the list. >> >>In my "main" module I import "enterData" and try to read the first >>element of "close" as follows: >> >> import enterData >> xy=enterData.close >> print xy[0] >> >> >>When I do this it prints out the entire "close" list, not just the first >>term. >> >>What's my mistake and how do I correct it? >> >>Thank you! >> >> >>------------------------------ >> >>Message: 8 >>Date: Sun, 28 Aug 2005 00:15:15 -0400 >>From: Kent Johnson >>Subject: Re: [Tutor] Importing a List from Module >>Cc: tutor at python.org >>Message-ID: <43113A53.2010308 at tds.net> >>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >>Tom Strickland wrote: >> >> >>>I have a module called "enterData" which generates a list, "close" from >>>a data file. "close" is a list of floats. When I put a print statement >>>in that module it will print out an individual member of the list. For >>>example, >>> >>> print close[0] >>> >>> >>>prints the first member of the list. >>> >>>In my "main" module I import "enterData" and try to read the first >>>element of "close" as follows: >>> >>> import enterData >>> xy=enterData.close >>> print xy[0] >>> >>> >>>When I do this it prints out the entire "close" list, not just the first >>>term. >>> >>>What's my mistake and how do I correct it? >>> >>> >> >>What you have shown here looks fine to me. Can you show some more of enterData? >> >>Kent >> >> >> >>------------------------------ >> >>Message: 9 >>Date: Sat, 27 Aug 2005 21:25:36 -0700 >>From: Byron >>Subject: Re: [Tutor] Importing a List from Module >>To: Tom Strickland , tutor at python.org >>Message-ID: <43113CC0.9050200 at christianfreebies.com> >>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >>Tom Strickland wrote: >> >> >>>In my "main" module I import "enterData" and try to read the first >>>element of "close" as follows: >>> >>> import enterData >>> xy=enterData.close >>> print xy[0] >>> >>> >>>When I do this it prints out the entire "close" list, not just the first >>>term. >>> >>> >> >> >>Hi Tom, >> >>I would create a function in your module that returns the list. Here's >>a quick, simplified example: >> >>def returnList(): >> newList = [] >> newList += [123.45] >> newList += [529.59] >> newList += [259.92] >> return newList >> >>aList = returnList() >>print aList >> >> >>Note the return statement... This enables assignment, as you have done >>in "xy=enterData.returnList()" >> >>Hope this helps, >> >>Byron >>--- >> >> >> >>------------------------------ >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >>End of Tutor Digest, Vol 18, Issue 106 >>************************************** >> >> >> >> > From tlinux at comcast.net Sun Aug 28 17:23:31 2005 From: tlinux at comcast.net (Tom Strickland) Date: Sun, 28 Aug 2005 10:23:31 -0500 Subject: [Tutor] Importing a List from Module In-Reply-To: <43113CC0.9050200@christianfreebies.com> References: <43112F1B.9030602@comcast.net> <43113CC0.9050200@christianfreebies.com> Message-ID: <4311D6F3.1080500@comcast.net> Byron, I'm confused (as usual). In "def returnList():" that you write below, should the items in the newList list be close[i] and looped to fill "newList" with the contents of "close"? If so, how is "returnLost" different from "close"? Thanks! Tom Byron wrote: > Tom Strickland wrote: > >> In my "main" module I import "enterData" and try to read the first >> element of "close" as follows: >> >> import enterData >> xy=enterData.close >> print xy[0] >> >> When I do this it prints out the entire "close" list, not just the >> first term. > > > > Hi Tom, > > I would create a function in your module that returns the list. > Here's a quick, simplified example: > > def returnList(): > newList = [] > newList += [123.45] > newList += [529.59] > newList += [259.92] > return newList > > aList = returnList() > print aList > > > Note the return statement... This enables assignment, as you have > done in "xy=enterData.returnList()" > > Hope this helps, > > Byron > --- > > > From tlinux at comcast.net Sun Aug 28 17:27:52 2005 From: tlinux at comcast.net (Tom Strickland) Date: Sun, 28 Aug 2005 10:27:52 -0500 Subject: [Tutor] Importing a List from Module In-Reply-To: <20050828040607.19530.qmail@web60121.mail.yahoo.com> References: <20050828040607.19530.qmail@web60121.mail.yahoo.com> Message-ID: <4311D7F8.1010401@comcast.net> Tom Strickland wrote: > Eric, > > No, "xy" isn't used anywhere else in the program. It's just a dummy > variable I used to print out "enterData.close". I could easily have > left it out. > > Tom > > > Eric Walker wrote: > >>I am a newbie but do you have anything else named xy >>in your main module. >> >>Eric.. >> >>--- Tom Strickland wrote: >> >> >> >>>I have a module called "enterData" which generates a >>>list, "close" from >>>a data file. "close" is a list of floats. When I put >>>a print statement >>>in that module it will print out an individual >>>member of the list. For >>>example, >>> >>> print close[0] >>> >>> >>>prints the first member of the list. >>> >>>In my "main" module I import "enterData" and try to >>>read the first >>>element of "close" as follows: >>> >>> import enterData >>> xy=enterData.close >>> print xy[0] >>> >>> >>>When I do this it prints out the entire "close" >>>list, not just the first >>>term. >>> >>>What's my mistake and how do I correct it? >>> >>>Thank you! >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> >> >> >>__________________________________ >>Yahoo! Mail for Mobile >>Take Yahoo! Mail with you! Check email on your mobile phone. >>http://mobile.yahoo.com/learn/mail >> >> >> >> > From singingxduck at gmail.com Sun Aug 28 20:21:42 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 28 Aug 2005 14:21:42 -0400 Subject: [Tutor] Importingf a List from Module In-Reply-To: <4311D589.9050508@comcast.net> References: <4311D589.9050508@comcast.net> Message-ID: <3449428f05082811216eb822f9@mail.gmail.com> On 8/28/05, Tom Strickland wrote: > > Tom Strickland wrote: > > >>Here are the modules in question: > >> > ---- > > ######This is the enterData.py module > > ##!/usr/bin/python2.4 > > input = open('/home/tom/Python/Input/SPY2.csv', 'r') > > s = input > > date =[] > > open = [] > > close = [] > > hi = [] > > lo = [] > > vol = [] > > for s in input: > > s = s[:-2] > > y =[] > > y = s.split(',') > > date.append(y[0]) > > open.append(float(y[1])) > > hi.append(float(y[2])) > > lo.append(float(y[3])) > > close.append(float(y[4])) > > vol.append(float(y[5])) > > input.close() > > for i in range(5): > > print close[i] > > print 'enterData.py' I don't know if this would affect anything, but one of your lists is named "open" which isn't a good idea because that overrides the builtin "open()" (the one you use to open a new file). -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050828/13b683d2/attachment.htm From kent37 at tds.net Sun Aug 28 20:41:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 28 Aug 2005 14:41:03 -0400 Subject: [Tutor] Importingf a List from Module In-Reply-To: <4311D589.9050508@comcast.net> References: <4311D589.9050508@comcast.net> Message-ID: <4312053F.4070507@tds.net> I'm still stumped by this one. Here is a stripped-down version of your code that works fine for me: # test.py #!/usr/bin/python2.4 import enterData xy=enterData.close print xy[0] print "Finished" ######This is the enterData.py module ##!/usr/bin/python2.4 input = open('SPY2.csv', 'r') close = [] for s in input: close.append(float(s)) input.close() for i in range(5): print close[i] print 'enterData.py' # SPY2.csv 1.2 3.4 1.2 4.5 6.7 The output is 1.2 3.4 1.2 4.5 6.7 enterData.py 1.2 Finished Do you get the same results? What is in your SPY2.csv? What output do you get? Kent Tom Strickland wrote: > Tom Strickland wrote: > > >>>Here are the modules in question: >>> >>> >> >>####This is the main.py module >> >>#!/usr/bin/python2.4 >>import enterData >>import movAvg >>smavg=[] >>xy=enterData.close >>print xy[0] >>smavg = movAvg.sma(20,enterData.close) >>emavg=[] >>emavg=movAvg.ema(20,enterData.close) >>import stoResults >>stoResults.store(enterData.date, enterData.close,smavg,emavg) >>print "Finished" >> >> >>######This is the enterData.py module >>##!/usr/bin/python2.4 >>input = open('/home/tom/Python/Input/SPY2.csv', 'r') >>s = input >>date =[] >>open = [] >>close = [] >>hi = [] >>lo = [] >>vol = [] >>for s in input: >> s = s[:-2] >> y =[] >> y = s.split(',') >> date.append(y[0]) >> open.append(float(y[1])) >> hi.append(float(y[2])) >> lo.append(float(y[3])) >> close.append(float(y[4])) >> vol.append(float(y[5])) >>input.close() >>for i in range(5): >> print close[i] >>print 'enterData.py' >> >> >> >> >>*********************************************************************************************************************************** >> >> >> >>>------------------------------ >>> >>>Message: 7 >>>Date: Sat, 27 Aug 2005 22:27:23 -0500 >>>From: Tom Strickland >>>Subject: [Tutor] Importing a List from Module >>>To: tutor at python.org >>>Message-ID: <43112F1B.9030602 at comcast.net> >>>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>> >>>I have a module called "enterData" which generates a list, "close" from >>>a data file. "close" is a list of floats. When I put a print statement >>>in that module it will print out an individual member of the list. For >>>example, >>> >>> print close[0] >>> >>> >>>prints the first member of the list. >>> >>>In my "main" module I import "enterData" and try to read the first >>>element of "close" as follows: >>> >>> import enterData >>> xy=enterData.close >>> print xy[0] >>> >>> >>>When I do this it prints out the entire "close" list, not just the first >>>term. >>> >>>What's my mistake and how do I correct it? >>> >>>Thank you! >>> >>> >>>------------------------------ >>> >>>Message: 8 >>>Date: Sun, 28 Aug 2005 00:15:15 -0400 >>>From: Kent Johnson >>>Subject: Re: [Tutor] Importing a List from Module >>>Cc: tutor at python.org >>>Message-ID: <43113A53.2010308 at tds.net> >>>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>> >>>Tom Strickland wrote: >>> >>> >>> >>>>I have a module called "enterData" which generates a list, "close" from >>>>a data file. "close" is a list of floats. When I put a print statement >>>>in that module it will print out an individual member of the list. For >>>>example, >>>> >>>> print close[0] >>>> >>>> >>>>prints the first member of the list. >>>> >>>>In my "main" module I import "enterData" and try to read the first >>>>element of "close" as follows: >>>> >>>> import enterData >>>> xy=enterData.close >>>> print xy[0] >>>> >>>> >>>>When I do this it prints out the entire "close" list, not just the first >>>>term. >>>> >>>>What's my mistake and how do I correct it? >>>> >>>> >>> >>>What you have shown here looks fine to me. Can you show some more of enterData? >>> >>>Kent >>> >>> >>> >>>------------------------------ >>> >>>Message: 9 >>>Date: Sat, 27 Aug 2005 21:25:36 -0700 >>>From: Byron >>>Subject: Re: [Tutor] Importing a List from Module >>>To: Tom Strickland , tutor at python.org >>>Message-ID: <43113CC0.9050200 at christianfreebies.com> >>>Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>> >>>Tom Strickland wrote: >>> >>> >>> >>>>In my "main" module I import "enterData" and try to read the first >>>>element of "close" as follows: >>>> >>>> import enterData >>>> xy=enterData.close >>>> print xy[0] >>>> >>>> >>>>When I do this it prints out the entire "close" list, not just the first >>>>term. >>>> >>>> >>> >>> >>>Hi Tom, >>> >>>I would create a function in your module that returns the list. Here's >>>a quick, simplified example: >>> >>>def returnList(): >>> newList = [] >>> newList += [123.45] >>> newList += [529.59] >>> newList += [259.92] >>> return newList >>> >>>aList = returnList() >>>print aList >>> >>> >>>Note the return statement... This enables assignment, as you have done >>>in "xy=enterData.returnList()" >>> >>>Hope this helps, >>> >>>Byron >>>--- >>> >>> >>> >>>------------------------------ >>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>>End of Tutor Digest, Vol 18, Issue 106 >>>************************************** >>> >>> >>> >>> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lumbricus at gmx.net Sun Aug 28 21:55:52 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Sun, 28 Aug 2005 21:55:52 +0200 (MEST) Subject: [Tutor] =?iso-8859-1?q?Exceptions_and_its_error_messages?= Message-ID: <5882.1125258952@www41.gmx.net> Hello! Don't know if someone wrote this already. >But how knowing all error messages from some module? >Is there any way of knowing from python interactive line? >>> for i in dir(__builtins__): >>> if i.endswith("Error"): print i HTH and Greets, J"o! -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realita:t. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realita:t zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) GMX DSL = Maximale Leistung zum minimalen Preis! 2000 MB nur 2,99, Flatrate ab 4,99 Euro/Monat: http://www.gmx.net/de/go/dsl From lumbricus at gmx.net Sun Aug 28 21:42:26 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Sun, 28 Aug 2005 21:42:26 +0200 (MEST) Subject: [Tutor] =?iso-8859-1?q?Importingf_a_List_from_Module?= Message-ID: <4192.1125258146@www41.gmx.net> Hello! >>When I do this it prints out the entire "close" list, not just the first >>term. In your module: >for i in range(5): > print close[i] Here you tell it to do so. It does it when it gets imported. HTH and Greets, J"o! -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realita:t. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realita:t zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner From tlinux at comcast.net Sun Aug 28 23:38:50 2005 From: tlinux at comcast.net (Tom Strickland) Date: Sun, 28 Aug 2005 16:38:50 -0500 Subject: [Tutor] [Fwd: Re: Importing a List from Module] Message-ID: <43122EEA.9060305@comcast.net> -------- Original Message -------- Subject: Re: Importing a List from Module Date: Sun, 28 Aug 2005 16:37:26 -0500 From: Tom Strickland To: tutor at python.org The problem has been solved. It turned out that I made a newbie mistake that had nothing to do with importing lists. I have a function, sma, which calculates the moving average for a list of prices. I passed the "close" (subsequently changed to "cloze") list to the function as an argument. There is a "for" loop in the function that appends close to a new list.I had written this as: p.append(close) when it should have been p.append(close[i]) This mistake caused the function to append the entire "close" list to "p" instead of just "close[i]" each time through the loop which was more than 4000 times.. This mistake caused a print statement to fill the output screen with numbers. It was difficult to determine that my problem wasn't importing "close", but in how I was using it. Thanks to all who offered suggestions. While my use of "open" and "close" as list names apparently didn't cause any problems, it's bad form and I've changed those two names. Tom From Hans.Dushanthakumar at navman.com Mon Aug 29 07:32:01 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Mon, 29 Aug 2005 17:32:01 +1200 Subject: [Tutor] "Lock"ing threads Message-ID: <5667508E43F1B740BCFA57FF46E353000170C26B@nav_akl_exch_c.newton.navman.com> Hi, In a multithreaded program, how do I ensure that a block of code in a thread is always executed fully before passing control to another thread. Does "Lock" serve this purpose? The foll program is a dummy one, with 2 threads. One put a number onto a queue (of max size 1) and the other thread reads from the que. However, on running this program (Win XP, NOT via IDLE - it hangs when I run it thru IDLE) the output that I see on screen indicates that the block of code within the lock aquire and release was not run completely before the other thread started running. Note that the print messages from the 2 threads seem to be interspersed together: import threading import Queue class put_num(threading.Thread): stop_thread = 0 def __init__(self, num, que): threading.Thread.__init__(self) self.que = que self.num = num self.lock = threading.Lock() def run(self): global stop_thread for k in range (20): self.lock.acquire() print "put_num: ", self.num self.que.put(str(self.num)) print "put_num: Que size = ", self.que.qsize() self.num = self.num + 1 self.lock.release() class get_num(threading.Thread): stop_thread = 0 def __init__(self, que): threading.Thread.__init__(self) self.que = que self.lock = threading.Lock() def run(self): global stop_thread for k in range (20): self.lock.acquire() mynum = self.que.get() print "get_num: ", mynum print "get_num: Que size = ", self.que.qsize() self.lock.release() my_que = Queue.Queue(1) put_num_thread = put_num(742, my_que) get_num_thread = get_num(my_que) print "Starting threads" put_num_thread.start() get_num_thread.start() print "Waiting for threads to finish" put_num_thread.join() get_num_thread.join() print "Closing down" raw_input("\n\nPress enter to Quit: ") This is the out put of the above program: Starting threads put_num: 742 Waiting for threads to finish put_num: Que size = 1 get_num: 742 get_num: Que size = 0 put_num: 743 put_num: Que size = 1 get_num: 743 get_num: Que size = 0 put_num: 744 put_num: Que size = 1 get_num: 744 get_num: Que size = 0 put_num: 745 put_num: Que size = 1 get_num: 745 get_num: Que size = 0 put_num: 746 put_num: Que size = 1 get_num: 746 get_num: Que size = 0 put_num: 747 put_num: Que size = get_num: 747 get_num: Que size = 0 0 put_num: 748 put_num: Que size = 1 get_num: 748 get_num: Que size = 0 put_num: 749 put_num: Que size = get_num: 749 get_num: Que size = 0 0 put_num: 750 put_num: Que size = 1 get_num: 750 get_num: Que size = 0 put_num: 751 put_num: Que size = 1 get_num: 751 get_num: Que size = 0 put_num: 752 put_num: Que size = get_num: 752 get_num: Que size = 0 0 put_num: 753 put_num: Que size = 1 get_num: 753 get_num: Que size = 0 put_num: 754 put_num: Que size = 1 get_num: 754 get_num: Que size = 0 put_num: 755 put_num: Que size = get_num: 755 get_num: Que size = 0 0 put_num: 756 put_num: Que size = get_num: 756 get_num: Que size = 0 0 put_num: 757 put_num: Que size = get_num: 757 get_num: Que size = 0 0 put_num: 758 put_num: Que size = 1 get_num: 758 get_num: Que size = 0 put_num: 759 put_num: Que size = get_num: 759 get_num: Que size = 0 0 put_num: 760 put_num: Que size = 1 get_num: 760 get_num: Que size = 0 put_num: 761 put_num: Que size = get_num: 761 get_num: Que size = 0 0 Closing down Press enter to Quit: From terence_zhu78 at hotmail.com Mon Aug 29 11:12:55 2005 From: terence_zhu78 at hotmail.com (terence zhu) Date: Mon, 29 Aug 2005 09:12:55 +0000 Subject: [Tutor] How do use c/c++ methods in Python? Message-ID: Function Test(Struct A *a,int b). I want to use this function in Python,What should be the firt parameter? _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From alan.gauld at freenet.co.uk Mon Aug 29 12:24:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 29 Aug 2005 11:24:37 +0100 Subject: [Tutor] How do use c/c++ methods in Python? References: Message-ID: <013201c5ac83$dbaba680$0201a8c0@xp> > Subject: [Tutor] How do use c/c++ methods in Python? > > Function Test(Struct A *a,int b). > I want to use this function in Python,What > should be the firt parameter? I'm not sure what you are asking here. To use a C++ function/method from Python you will need to write a wrapper around the C++ code, probably using SWIG or some similar tool. Is this what you are trying to do? And if so are you asking how to map the C struct to a Python type within the wrapper? Or are you trying to call the function directly? That won't be possible, although if its a Windows function the ctypes library may help, and may provide guidance on how to translate the struct. Can you clarify what you are trying to achieve? Alan G From kent37 at tds.net Mon Aug 29 13:35:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Aug 2005 07:35:05 -0400 Subject: [Tutor] "Lock"ing threads In-Reply-To: <5667508E43F1B740BCFA57FF46E353000170C26B@nav_akl_exch_c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E353000170C26B@nav_akl_exch_c.newton.navman.com> Message-ID: <4312F2E9.8020609@tds.net> Hans Dushanthakumar wrote: > Hi, > In a multithreaded program, how do I ensure that a block of code in a > thread is always executed fully before passing control to another > thread. Does "Lock" serve this purpose? No, not exactly. It is used to prevent threading errors but not in the way you think. Acquiring a Lock, by itself, doesn't prevent another thread from running. It just prevents another thread from acquiring *the same* lock. So to prevent two bits of code from running "at the same time" you can use a *single* Lock. Change your code to use a global Lock or pass the Lock to the class constructors. You will also have to handle waiting on a full Queue; if you just use a shared lock you will deadlock if you put_num() on a full Queue. (put_num.run() will acquire the lock, then it will block waiting for room in the Queue. get_num.run() will not be able to acquire the lock so the Queue will never empty.) Take a look at Queue.py to see one way to handle this. Note that Queue is already thread-safe for insertion and removal. If you really need to read the size as you do in your code then you need another Lock but the basic Queue does not need this. You might be interested in "The Little Book of Semaphores" which is an introduction to threading using Python. http://greenteapress.com/semaphores/ Kent > > The foll program is a dummy one, with 2 threads. One put a number onto a > queue (of max size 1) and the other thread reads from the que. > > However, on running this program (Win XP, NOT via IDLE - it hangs when I > run it thru IDLE) the output that I see on screen indicates that the > block of code within the lock aquire and release was not run completely > before the other thread started running. Note that the print messages > from the 2 threads seem to be interspersed together: > > > import threading > import Queue > > class put_num(threading.Thread): > stop_thread = 0 > > def __init__(self, num, que): > threading.Thread.__init__(self) > self.que = que > self.num = num > self.lock = threading.Lock() > > def run(self): > global stop_thread > for k in range (20): > self.lock.acquire() > print "put_num: ", self.num > self.que.put(str(self.num)) > print "put_num: Que size = ", self.que.qsize() > self.num = self.num + 1 > self.lock.release() > > class get_num(threading.Thread): > stop_thread = 0 > > def __init__(self, que): > threading.Thread.__init__(self) > self.que = que > self.lock = threading.Lock() > > def run(self): > global stop_thread > for k in range (20): > self.lock.acquire() > mynum = self.que.get() > print "get_num: ", mynum > print "get_num: Que size = ", self.que.qsize() > self.lock.release() > > my_que = Queue.Queue(1) > > put_num_thread = put_num(742, my_que) > get_num_thread = get_num(my_que) > > print "Starting threads" > put_num_thread.start() > get_num_thread.start() > > print "Waiting for threads to finish" > put_num_thread.join() > get_num_thread.join() > > print "Closing down" > raw_input("\n\nPress enter to Quit: ") > > > > > This is the out put of the above program: > > > > Starting threads > put_num: 742 > Waiting for threads to finish > put_num: Que size = 1 > get_num: 742 > get_num: Que size = 0 > put_num: 743 > put_num: Que size = 1 > get_num: 743 > get_num: Que size = 0 > put_num: 744 > put_num: Que size = 1 > get_num: 744 > get_num: Que size = 0 > put_num: 745 > put_num: Que size = 1 > get_num: 745 > get_num: Que size = 0 > put_num: 746 > put_num: Que size = 1 > get_num: 746 > get_num: Que size = 0 > put_num: 747 > put_num: Que size = get_num: 747 > get_num: Que size = 0 > 0 > put_num: 748 > put_num: Que size = 1 > get_num: 748 > get_num: Que size = 0 > put_num: 749 > put_num: Que size = get_num: 749 > get_num: Que size = 0 > 0 > put_num: 750 > put_num: Que size = 1 > get_num: 750 > get_num: Que size = 0 > put_num: 751 > put_num: Que size = 1 > get_num: 751 > get_num: Que size = 0 > put_num: 752 > put_num: Que size = get_num: 752 > get_num: Que size = 0 > 0 > put_num: 753 > put_num: Que size = 1 > get_num: 753 > get_num: Que size = 0 > put_num: 754 > put_num: Que size = 1 > get_num: 754 > get_num: Que size = 0 > put_num: 755 > put_num: Que size = get_num: 755 > get_num: Que size = 0 > 0 > put_num: 756 > put_num: Que size = get_num: 756 > get_num: Que size = 0 > 0 > put_num: 757 > put_num: Que size = get_num: 757 > get_num: Que size = 0 > 0 > put_num: 758 > put_num: Que size = 1 > get_num: 758 > get_num: Que size = 0 > put_num: 759 > put_num: Que size = get_num: 759 > get_num: Que size = 0 > 0 > put_num: 760 > put_num: Que size = 1 > get_num: 760 > get_num: Que size = 0 > put_num: 761 > put_num: Que size = get_num: 761 > get_num: Que size = 0 > 0 > Closing down > > > Press enter to Quit: > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From litlfred_1 at yahoo.com Sat Aug 27 15:47:19 2005 From: litlfred_1 at yahoo.com (bobby arocha) Date: Sat, 27 Aug 2005 06:47:19 -0700 (PDT) Subject: [Tutor] hi Message-ID: <20050827134719.148.qmail@web53309.mail.yahoo.com> hello i am new to python very new as in my first time ever using it and no experience in programming at all and i woul dliek some help to understand how th eprogram works and how to use pythin to thelimits of its capabilitys and i woul dlike some help my name is bobby and i am serious about learning python so any help would be much apreciated thank u __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050827/af20e00e/attachment.html From strick_nine at comcast.net Sun Aug 28 23:37:26 2005 From: strick_nine at comcast.net (Tom Strickland) Date: Sun, 28 Aug 2005 16:37:26 -0500 Subject: [Tutor] Importing a List from Module Message-ID: <43122E96.1070704@comcast.net> The problem has been solved. It turned out that I made a newbie mistake that had nothing to do with importing lists. I have a function, sma, which calculates the moving average for a list of prices. I passed the "close" (subsequently changed to "cloze") list to the function as an argument. There is a "for" loop in the function that appends close to a new list.I had written this as: p.append(close) when it should have been p.append(close[i]) This mistake caused the function to append the entire "close" list to "p" instead of just "close[i]" each time through the loop which was more than 4000 times.. This mistake caused a print statement to fill the output screen with numbers. It was difficult to determine that my problem wasn't importing "close", but in how I was using it. Thanks to all who offered suggestions. While my use of "open" and "close" as list names apparently didn't cause any problems, it's bad form and I've changed those two names. Tom From carroll at tjc.com Mon Aug 29 22:45:48 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 29 Aug 2005 13:45:48 -0700 (PDT) Subject: [Tutor] New Tutorial topic In-Reply-To: <00c201c5abde$927ea570$0201a8c0@xp> Message-ID: On Sun, 28 Aug 2005, Alan G wrote: > I've just uploaded two new files to my tutorial.... the second is the > first of these and introduces databases, SQL and using the Python DBI > interface. Alan, thanks for this. I was just casting around for a tutorial on SQLite, and its use in Python. I've just briefly looked at your tutorial, but it looks like it's going to be invaluable. I'm also finding http://souptonuts.sourceforge.net/readme_sqlite_tutorial.html useful, but since I've never played with SQL at all, I expect your tutorial will be the best intro for me. Thanks. From dyoo at hkn.eecs.berkeley.edu Mon Aug 29 23:40:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Aug 2005 14:40:47 -0700 (PDT) Subject: [Tutor] hi In-Reply-To: <20050827134719.148.qmail@web53309.mail.yahoo.com> Message-ID: On Sat, 27 Aug 2005, bobby arocha wrote: > hello i am new to python very new as in my first time ever using it and > no experience in programming at all and i woul dliek some help to > understand how th eprogram works and how to use pythin to thelimits of > its capabilitys and i woul dlike some help my name is bobby and i am > serious about learning python so any help would be much apreciated Hi Bobby, Welcome aboard! You may want to take a look at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers and: http://wiki.python.org/moin/BeginnersGuide which should help you get started: there are a lot of good resources, like tutorials, that you can grab for free. If you have questions as you're going through a tutorial, feel free to ask here on Tutor. From alan.gauld at btinternet.com Mon Aug 29 23:50:11 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Aug 2005 22:50:11 +0100 Subject: [Tutor] hi References: <20050827134719.148.qmail@web53309.mail.yahoo.com> Message-ID: Hi Bobby, > hello i am new to python very new as in my first time ever > using > it and no experience in programming at all In that case go to the Non Programmers web page on the Python site and follow one of the non programmers tutorials there, possibly mine! :-) http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > help to understand how th eprogram works and The above tutorials will do that. If you get stuck just ask for more help here. Be sure to tell us which tutor you are using, what the problem is and any error messages you get, no matter how cryptic they may seem to you. > how to use pythin to thelimits of its capabilitys I'm not sure anyone has really got that far yet! ;-) -- Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From terence_zhu78 at hotmail.com Tue Aug 30 03:33:36 2005 From: terence_zhu78 at hotmail.com (terence zhu) Date: Tue, 30 Aug 2005 01:33:36 +0000 Subject: [Tutor] How do use c/c++ methods in Python? In-Reply-To: <013201c5ac83$dbaba680$0201a8c0@xp> Message-ID: Sorry for puzzling you! I want to know how to map the C struct to a Python type within the wrapper or other methods? >From: "Alan G" >To: "terence zhu" , >Subject: Re: [Tutor] How do use c/c++ methods in Python? >Date: Mon, 29 Aug 2005 11:24:37 +0100 > >>Subject: [Tutor] How do use c/c++ methods in Python? >> > >>Function Test(Struct A *a,int b). I want to use this function in >>Python,What should be the firt parameter? > >I'm not sure what you are asking here. >To use a C++ function/method from Python you will need to write a wrapper >around the C++ code, probably using SWIG or some similar >tool. > >Is this what you are trying to do? And if so are you asking how to map the >C struct to a Python type within the wrapper? > >Or are you trying to call the function directly? That won't be possible, >although if its a Windows function the ctypes library may help, and may >provide guidance on how to translate the struct. > >Can you clarify what you are trying to achieve? > >Alan G _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From Hans.Dushanthakumar at navman.com Tue Aug 30 04:17:52 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 30 Aug 2005 14:17:52 +1200 Subject: [Tutor] Killing a thread from main - was RE: "Lock"ing threads Message-ID: <5667508E43F1B740BCFA57FF46E3530001782C88@nav_akl_exch_c.newton.navman.com> Thanks Kent How do I send a signal from the main thread to stop execution of a child thread? I tried the foll:, but got an error: Other than by this method, is there any other mechanism to stop a thread? import threading import time class shownum(threading.Thread): def __init__(self, start_num): threading.Thread.__init__(self) self.num = start_num self.stop = 0 def run(self): for i in range(12): time.sleep(1) print "shownum: ", self.num self.num = self.num + 1 if self.stop == 1: break def stop(self): self.stop = 1 def chng(self): self.num = 1 incr_num_thread = shownum1(201) incr_num_thread.start() time.sleep(3) incr_num_thread.chng() time.sleep(3) incr_num_thread.stop() Output: shownum: 201 shownum: 202 shownum: 1 shownum: 2 shownum: 3 Traceback (most recent call last): File "H:\Docs\PyScripts\test_threads.py", line 31, in ? incr_num_thread.stop() TypeError: 'int' object is not callable shownum: 4 shownum: 5 shownum: 6 From Hans.Dushanthakumar at navman.com Tue Aug 30 04:27:55 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 30 Aug 2005 14:27:55 +1200 Subject: [Tutor] Killing a thread from main - was RE: "Lock"ing threads Message-ID: <5667508E43F1B740BCFA57FF46E3530001782CB5@nav_akl_exch_c.newton.navman.com> Oops - the error was probably due to using 'stop' as a method name. :) -----Original Message----- From: Hans Dushanthakumar Sent: Tuesday, 30 August 2005 2:18 p.m. To: tutor at python.org Subject: Killing a thread from main - was RE: [Tutor] "Lock"ing threads Thanks Kent How do I send a signal from the main thread to stop execution of a child thread? I tried the foll:, but got an error: Other than by this method, is there any other mechanism to stop a thread? import threading import time class shownum(threading.Thread): def __init__(self, start_num): threading.Thread.__init__(self) self.num = start_num self.stop = 0 def run(self): for i in range(12): time.sleep(1) print "shownum: ", self.num self.num = self.num + 1 if self.stop == 1: break def stop(self): self.stop = 1 def chng(self): self.num = 1 incr_num_thread = shownum1(201) incr_num_thread.start() time.sleep(3) incr_num_thread.chng() time.sleep(3) incr_num_thread.stop() Output: shownum: 201 shownum: 202 shownum: 1 shownum: 2 shownum: 3 Traceback (most recent call last): File "H:\Docs\PyScripts\test_threads.py", line 31, in ? incr_num_thread.stop() TypeError: 'int' object is not callable shownum: 4 shownum: 5 shownum: 6 From kent37 at tds.net Tue Aug 30 04:51:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Aug 2005 22:51:29 -0400 Subject: [Tutor] Killing a thread from main - was RE: "Lock"ing threads In-Reply-To: <5667508E43F1B740BCFA57FF46E3530001782C88@nav_akl_exch_c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530001782C88@nav_akl_exch_c.newton.navman.com> Message-ID: <4313C9B1.5010105@tds.net> Hans Dushanthakumar wrote: > Thanks Kent > > How do I send a signal from the main thread to stop execution of a child > thread? You have the right idea - set some kind of flag that the thread checks - but you reused the name 'stop' so when you execute incr_num_thread.stop() you are retrieving the 'stop' attribute of incr_num_thread (which is the integer 0) rather than the 'stop' attribute of class shownum (which is the method you want). Then you try to call the integer (by the ()) and get an error. This recipe has a more sophisticated version of the same idea: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 Kent > > I tried the foll:, but got an error: > Other than by this method, is there any other mechanism to stop a > thread? > > import threading > import time > > class shownum(threading.Thread): > > def __init__(self, start_num): > threading.Thread.__init__(self) > self.num = start_num > self.stop = 0 > > def run(self): > for i in range(12): > time.sleep(1) > print "shownum: ", self.num > self.num = self.num + 1 > if self.stop == 1: > break > > def stop(self): > self.stop = 1 > > def chng(self): > self.num = 1 > > incr_num_thread = shownum1(201) > incr_num_thread.start() > > time.sleep(3) > incr_num_thread.chng() > time.sleep(3) > incr_num_thread.stop() > > > Output: > > shownum: 201 > shownum: 202 > shownum: 1 > shownum: 2 > shownum: 3 > Traceback (most recent call last): > File "H:\Docs\PyScripts\test_threads.py", line 31, in ? > incr_num_thread.stop() > TypeError: 'int' object is not callable > shownum: 4 > shownum: 5 > shownum: 6 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sli1que at yahoo.com Tue Aug 30 05:01:12 2005 From: sli1que at yahoo.com (Eric Walker) Date: Mon, 29 Aug 2005 20:01:12 -0700 (PDT) Subject: [Tutor] MS Access...... Message-ID: <20050830030112.11884.qmail@web60122.mail.yahoo.com> I want to know what modules are available to connect and talk with MSAccess databases... Thanks.... __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From johan at accesstel.co.za Tue Aug 30 12:24:49 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 30 Aug 2005 12:24:49 +0200 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: References: Message-ID: <1125397489.6654.33.camel@KMA.accesstel> Thanks for he help, so far. I am still having some questions on writing my new string back to the xml file after I found what I was looking for and changed it. Extracts: xmlDocument = minidom.parse(file_name) # open existing file for parsing main = xmlDocument.getElementsByTagName('Config') main.getElementsByTagName('Connection') configSection = mainSection[0] for node in configSection: #Here I get the NamedNodeMap info password = node.getAttribute("password") # Do stuff to the password and I have 'newPass' node.removeAttribute('password') # I take out my old attribute and it's value node.setAttribute('password', newPass) At this stage I have my new attribute and it's new value, but how do I write that to my file in the same place? I have to get a 'writer', how do I do this? Do I have to write all the data back or can I just replace the pieces I changed? Thanks, Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050830/6bd5d473/attachment.htm -------------- next part -------------- An embedded message was scrubbed... From: Danny Yoo Subject: Re: [Tutor] Writing to XML file with minidom Date: Mon, 22 Aug 2005 10:57:36 -0700 (PDT) Size: 3127 Url: http://mail.python.org/pipermail/tutor/attachments/20050830/6bd5d473/attachment.mht From kent37 at tds.net Tue Aug 30 13:30:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 30 Aug 2005 07:30:21 -0400 Subject: [Tutor] MS Access...... In-Reply-To: <20050830030112.11884.qmail@web60122.mail.yahoo.com> References: <20050830030112.11884.qmail@web60122.mail.yahoo.com> Message-ID: <4314434D.2080500@tds.net> Eric Walker wrote: > I want to know what modules are available to connect > and talk with MSAccess databases... google 'python msaccess' You can talk to Access directly using ADO: http://www.ecp.cc/pyado.html or via DAO: http://starship.python.net/crew/bwilk/access.html adodbapi puts a Python DB-API wrapper around ADO: http://adodbapi.sourceforge.net/ Kent From kent37 at tds.net Tue Aug 30 13:40:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 30 Aug 2005 07:40:02 -0400 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: <1125397489.6654.33.camel@KMA.accesstel> References: <1125397489.6654.33.camel@KMA.accesstel> Message-ID: <43144592.4060403@tds.net> Johan Geldenhuys wrote: > Thanks for he help, so far. > > I am still having some questions on writing my new string back to the > xml file after I found what I was looking for and changed it. > > Extracts: > > xmlDocument = minidom.parse(file_name) # open existing file for parsing > main = xmlDocument.getElementsByTagName('Config') > main.getElementsByTagName('Connection') > configSection = mainSection[0] > > for node in configSection: #Here I get the NamedNodeMap info > password = node.getAttribute("password") > # Do stuff to the password and I have 'newPass' > node.removeAttribute('password') # I take out my old attribute > and it's value > node.setAttribute('password', newPass) > > > At this stage I have my new attribute and it's new value, but how do I > write that to my file in the same place? > I have to get a 'writer', how do I do this? The minidom docs say that DOM objects have a writexml() method: writexml(writer[,indent=""[,addindent=""[,newl=""]]]) Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. This is saying that 'writer' should act like a file object. So it can just be a file object obtained by calling open(). In other words something like f = open(file_name, 'w') xmlDocument.writexml(f) f.close() should do it. If you have non-ascii characters in your XML you should use codecs.open() instead of plain open() and encode your XML as desired (probably utf-8). > Do I have to write all the data back or can I just replace the pieces I > changed? You have to write it all back. Kent From johan at accesstel.co.za Tue Aug 30 13:47:31 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 30 Aug 2005 13:47:31 +0200 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: <43144592.4060403@tds.net> References: <1125397489.6654.33.camel@KMA.accesstel> <43144592.4060403@tds.net> Message-ID: <1125402452.6654.41.camel@KMA.accesstel> That means that I have to compile the whole file from scratch in Python, minidom. I am not that good, yet, but will try. will it be easier to search for the string that I look for in the file (readlines) and then just write the pieces back again? Johan On Tue, 2005-08-30 at 07:40 -0400, Kent Johnson wrote: > Johan Geldenhuys wrote: > > Thanks for he help, so far. > > > > I am still having some questions on writing my new string back to the > > xml file after I found what I was looking for and changed it. > > > > Extracts: > > > > xmlDocument = minidom.parse(file_name) # open existing file for parsing > > main = xmlDocument.getElementsByTagName('Config') > > main.getElementsByTagName('Connection') > > configSection = mainSection[0] > > > > for node in configSection: #Here I get the NamedNodeMap info > > password = node.getAttribute("password") > > # Do stuff to the password and I have 'newPass' > > node.removeAttribute('password') # I take out my old attribute > > and it's value > > node.setAttribute('password', newPass) > > > > > > At this stage I have my new attribute and it's new value, but how do I > > write that to my file in the same place? > > I have to get a 'writer', how do I do this? > > The minidom docs say that DOM objects have a writexml() method: > writexml(writer[,indent=""[,addindent=""[,newl=""]]]) > Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. > > This is saying that 'writer' should act like a file object. So it can just be a file object obtained by calling open(). In other words something like > f = open(file_name, 'w') > xmlDocument.writexml(f) > f.close() > > should do it. If you have non-ascii characters in your XML you should use codecs.open() instead of plain open() and encode your XML as desired (probably utf-8). > > > Do I have to write all the data back or can I just replace the pieces I > > changed? > > You have to write it all back. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050830/13bffdf4/attachment.html From sli1que at yahoo.com Tue Aug 30 14:20:29 2005 From: sli1que at yahoo.com (Eric Walker) Date: Tue, 30 Aug 2005 05:20:29 -0700 (PDT) Subject: [Tutor] MS Access...... In-Reply-To: <4314434D.2080500@tds.net> Message-ID: <20050830122029.76860.qmail@web60125.mail.yahoo.com> me = class Beautiful me.Crying....... Great Info, I was able to connect through DAO and create an object and coulde open, Excel,Access and Word docs but I couldn't find any documentation on methods to use to do stuff. I will try ADO tonight directly and I am sure it will work great. Eric Thanks Again... --- Kent Johnson wrote: > Eric Walker wrote: > > I want to know what modules are available to > connect > > and talk with MSAccess databases... > > google 'python msaccess' > > You can talk to Access directly using ADO: > http://www.ecp.cc/pyado.html > > or via DAO: > http://starship.python.net/crew/bwilk/access.html > > adodbapi puts a Python DB-API wrapper around ADO: > http://adodbapi.sourceforge.net/ > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From kent37 at tds.net Tue Aug 30 15:47:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 30 Aug 2005 09:47:26 -0400 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: <1125402452.6654.41.camel@KMA.accesstel> References: <1125397489.6654.33.camel@KMA.accesstel> <43144592.4060403@tds.net> <1125402452.6654.41.camel@KMA.accesstel> Message-ID: <4314636E.4080501@tds.net> Johan Geldenhuys wrote: > That means that I have to compile the whole file from scratch in Python, > minidom. > I am not that good, yet, but will try. No, not if I understand what you are trying to do - the xmlDocument you have is all the data from the file, just write it back out using the code I posted before. > will it be easier to search for the string that I look for in the file > (readlines) and then just write the pieces back again? That depends a lot on the data. If you can reliably find what you want by looking at a line at a time, that is a simple approach. But you are almost there with the minidom. Really, just add my three lines of code to what you already have. (Maybe for prudence use a different file name.) Kent > > Johan > On Tue, 2005-08-30 at 07:40 -0400, Kent Johnson wrote: > >>Johan Geldenhuys wrote: >>> Thanks for he help, so far. >>> >>> I am still having some questions on writing my new string back to the >>> xml file after I found what I was looking for and changed it. >>> >>> Extracts: >>> >>> xmlDocument = minidom.parse(file_name) # open existing file for parsing >>> main = xmlDocument.getElementsByTagName('Config') >>> main.getElementsByTagName('Connection') >>> configSection = mainSection[0] >>> >>> for node in configSection: #Here I get the NamedNodeMap info >>> password = node.getAttribute("password") >>> # Do stuff to the password and I have 'newPass' >>> node.removeAttribute('password') # I take out my old attribute >>> and it's value >>> node.setAttribute('password', newPass) >>> >>> >>> At this stage I have my new attribute and it's new value, but how do I >>> write that to my file in the same place? >>> I have to get a 'writer', how do I do this? >> >>The minidom docs say that DOM objects have a writexml() method: >>writexml(writer[,indent=""[,addindent=""[,newl=""]]]) >> Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. >> >>This is saying that 'writer' should act like a file object. So it can just be a file object obtained by calling open(). In other words something like >>f = open(file_name, 'w') >>xmlDocument.writexml(f) >>f.close() >> >>should do it. If you have non-ascii characters in your XML you should use codecs.open() instead of plain open() and encode your XML as desired (probably utf-8). >> >>> Do I have to write all the data back or can I just replace the pieces I >>> changed? >> >>You have to write it all back. >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > From STEVEN.M.FAULCONER at saic.com Tue Aug 30 22:51:51 2005 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Tue, 30 Aug 2005 16:51:51 -0400 Subject: [Tutor] Popen and Prompting Message-ID: <8A443FA5598F9545A4583F9D3BECE43F25A0F187@mcl-its-exs01.mail.saic.com> Hello all, Been digging through the web and the archives for the tutor list and can't seem to locate an answer to my question. It is probably out there, but my searching skills are failing me. I recently wrote a GUI for several command line programs using Tkinter. Everything is working quite well, until I ran into one program that actually prompts for some input. I'm currently using os.popen to make the actual calls. Something like: --------- Code ---------- input = popen( command, 'r' ) while 1: line = input.readline() if not line: break --------- Code ---------- My question for all of you python people; how can I handle programs that MAY need input from the command line. I thought about using something like pexpect, but the input requests are fairly variable, and may not show up at all. Also, I need to tie this in with the Tkinter GUI as well. The binaries we are running are written in C, and we have no way of changing that (it's in-house software, but the API we have to use does not talk to Python). I've attached the program in all it's glory, so general advice (constructive only, please) would be greatly appreciated. Target Platform is Windows (2000/XP) Python Version 2.4.x Thanks for any advice you can send along, Steven -------------- next part -------------- A non-text attachment was scrubbed... Name: GuiCheck_b.pyw Type: application/octet-stream Size: 35038 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050830/a59b0ee2/GuiCheck_b-0001.obj From john at fouhy.net Wed Aug 31 01:03:16 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 31 Aug 2005 11:03:16 +1200 Subject: [Tutor] Popen and Prompting In-Reply-To: <8A443FA5598F9545A4583F9D3BECE43F25A0F187@mcl-its-exs01.mail.saic.com> References: <8A443FA5598F9545A4583F9D3BECE43F25A0F187@mcl-its-exs01.mail.saic.com> Message-ID: <5e58f2e4050830160336c0638@mail.gmail.com> On 31/08/05, Faulconer, Steven M. wrote: > My question for all of you python people; how can I handle programs that MAY > need input from the command line. I thought about using something like > pexpect, but the input requests are fairly variable, and may not show up at > all. Also, I need to tie this in with the Tkinter GUI as well. The binaries > we are running are written in C, and we have no way of changing that (it's > in-house software, but the API we have to use does not talk to Python). Could you kludge it? eg, change the C programs so that, every time they ask for user input, they include in the prompt a certain unusual string. Then, any time your GUI detects this string in the program output, it can pop up a dialog box asking for user input. (just a suggestion ... I don't know the best way of dealing with this) -- John. From arcege at gmail.com Wed Aug 31 02:42:08 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Tue, 30 Aug 2005 20:42:08 -0400 Subject: [Tutor] Killing a thread from main - was RE: "Lock"ing threads In-Reply-To: <5667508E43F1B740BCFA57FF46E3530001782C88@nav_akl_exch_c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530001782C88@nav_akl_exch_c.newton.navman.com> Message-ID: <7e5ba922050830174240e80f27@mail.gmail.com> On 8/29/05, Hans Dushanthakumar wrote: > > Thanks Kent > > How do I send a signal from the main thread to stop execution of a child > thread? > > I tried the foll:, but got an error: > Other than by this method, is there any other mechanism to stop a > thread? > > import threading > import time > > class shownum(threading.Thread): > > def __init__(self, start_num): > threading.Thread.__init__(self) > self.num = start_num > self.stop = 0 > > def run(self): > for i in range(12): > time.sleep(1) > print "shownum: ", self.num > self.num = self.num + 1 > if self.stop == 1: > break > > def stop(self): > self.stop = 1 > > def chng(self): > self.num = 1 > > incr_num_thread = shownum1(201) > incr_num_thread.start() > > time.sleep(3) > incr_num_thread.chng() > time.sleep(3) > incr_num_thread.stop() > > > Output: > > shownum: 201 > shownum: 202 > shownum: 1 > shownum: 2 > shownum: 3 > Traceback (most recent call last): > File "H:\Docs\PyScripts\test_threads.py", line 31, in ? > incr_num_thread.stop() > TypeError: 'int' object is not callable > shownum: 4 > shownum: 5 > shownum: 6 > You would probably want to use a shared threading.Condition object. A number of threads manuals mention using this in a boss shutdown model. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050830/f1c3ec64/attachment.html From johan at accesstel.co.za Wed Aug 31 08:09:36 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 31 Aug 2005 08:09:36 +0200 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: <4314636E.4080501@tds.net> References: <1125397489.6654.33.camel@KMA.accesstel> <43144592.4060403@tds.net> <1125402452.6654.41.camel@KMA.accesstel> <4314636E.4080501@tds.net> Message-ID: <1125468576.7012.3.camel@KMA.accesstel> Kent, Thanks for the tip. I can write the changed data back to my xml file. One snag that I found is that the des encryption that I used for the data that is written back, it is not parsed correctly when the file is read again with the new data in it. There is non-printable characters or non-ascii chars in that gives errors from expat when the contents is parsed. I had to use a different encryption algorithm. I am going to do some tests on it now. Johan On Tue, 2005-08-30 at 09:47 -0400, Kent Johnson wrote: > Johan Geldenhuys wrote: > > That means that I have to compile the whole file from scratch in Python, > > minidom. > > I am not that good, yet, but will try. > > No, not if I understand what you are trying to do - the xmlDocument you have is all the data from the file, just write it back out using the code I posted before. > > > will it be easier to search for the string that I look for in the file > > (readlines) and then just write the pieces back again? > > That depends a lot on the data. If you can reliably find what you want by looking at a line at a time, that is a simple approach. But you are almost there with the minidom. Really, just add my three lines of code to what you already have. (Maybe for prudence use a different file name.) > > Kent > > > > > Johan > > On Tue, 2005-08-30 at 07:40 -0400, Kent Johnson wrote: > > > >>Johan Geldenhuys wrote: > >>> Thanks for he help, so far. > >>> > >>> I am still having some questions on writing my new string back to the > >>> xml file after I found what I was looking for and changed it. > >>> > >>> Extracts: > >>> > >>> xmlDocument = minidom.parse(file_name) # open existing file for parsing > >>> main = xmlDocument.getElementsByTagName('Config') > >>> main.getElementsByTagName('Connection') > >>> configSection = mainSection[0] > >>> > >>> for node in configSection: #Here I get the NamedNodeMap info > >>> password = node.getAttribute("password") > >>> # Do stuff to the password and I have 'newPass' > >>> node.removeAttribute('password') # I take out my old attribute > >>> and it's value > >>> node.setAttribute('password', newPass) > >>> > >>> > >>> At this stage I have my new attribute and it's new value, but how do I > >>> write that to my file in the same place? > >>> I have to get a 'writer', how do I do this? > >> > >>The minidom docs say that DOM objects have a writexml() method: > >>writexml(writer[,indent=""[,addindent=""[,newl=""]]]) > >> Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. > >> > >>This is saying that 'writer' should act like a file object. So it can just be a file object obtained by calling open(). In other words something like > >>f = open(file_name, 'w') > >>xmlDocument.writexml(f) > >>f.close() > >> > >>should do it. If you have non-ascii characters in your XML you should use codecs.open() instead of plain open() and encode your XML as desired (probably utf-8). > >> > >>> Do I have to write all the data back or can I just replace the pieces I > >>> changed? > >> > >>You have to write it all back. > >> > >>Kent > >> > >>_______________________________________________ > >>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: http://mail.python.org/pipermail/tutor/attachments/20050831/fcc3cacd/attachment.htm From davholla2002 at yahoo.co.uk Wed Aug 31 11:53:43 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 31 Aug 2005 10:53:43 +0100 (BST) Subject: [Tutor] Listbox help Message-ID: <20050831095343.34390.qmail@web25908.mail.ukl.yahoo.com> I can work out how to use most Tkinter widgets. Eg buttons like :- def create_widgets(self): #create GUI Button(self, text = "x", command = self.y).grid(row = 3, column = 3, columnspan = 3) However I am not sure how to use Listboxes. What would be the similar syntax to create a listbox. Thanks in advance. David ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From kent37 at tds.net Wed Aug 31 12:07:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Aug 2005 06:07:30 -0400 Subject: [Tutor] Listbox help In-Reply-To: <20050831095343.34390.qmail@web25908.mail.ukl.yahoo.com> References: <20050831095343.34390.qmail@web25908.mail.ukl.yahoo.com> Message-ID: <43158162.1010902@tds.net> David Holland wrote: > I can work out how to use most Tkinter widgets. Eg > buttons like :- > def create_widgets(self): > #create GUI > Button(self, text = "x", command = > self.y).grid(row = 3, column = 3, columnspan = 3) > > However I am not sure how to use Listboxes. What > would be the similar syntax to create a listbox. This page has a complete example of using a listbox: http://effbot.org/zone/tkinter-scrollbar-patterns.htm And this page has some useful snippets: http://www.pythonware.com/library/tkinter/introduction/x5453-patterns.htm Kent From travislspencer at gmail.com Wed Aug 31 16:47:12 2005 From: travislspencer at gmail.com (Travis Spencer) Date: Wed, 31 Aug 2005 07:47:12 -0700 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: <1125468576.7012.3.camel@KMA.accesstel> References: <1125397489.6654.33.camel@KMA.accesstel> <43144592.4060403@tds.net> <1125402452.6654.41.camel@KMA.accesstel> <4314636E.4080501@tds.net> <1125468576.7012.3.camel@KMA.accesstel> Message-ID: On 8/30/05, Johan Geldenhuys wrote: > One snag that I found is that the des encryption that I used for the data that is > written back, it is not parsed correctly when the file is read again with the new > data in it. There is non-printable characters or non-ascii chars in that gives errors > from expat when the contents is parsed. > I had to use a different encryption algorithm. I am going to do some tests on it > now. Put the cyphertext in a CDATA section, so the parser knows to ignore its contents: -- Regards, Travis Spencer P.S. Please don't send HTML e-mails. From STEVEN.M.FAULCONER at saic.com Wed Aug 31 20:16:02 2005 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed, 31 Aug 2005 14:16:02 -0400 Subject: [Tutor] Popen and Prompting Message-ID: <8A443FA5598F9545A4583F9D3BECE43F25AC62C7@mcl-its-exs01.mail.saic.com> John, I thought about that, but it would potentially cause other conflicts. I think our final plan is to edit the code to die on error cases instead of prompting. However, if anyone knows of a way of handling this, I'd love to know for future use. Thanks for the response. Steven -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of John Fouhy Sent: Tuesday, August 30, 2005 7:03 PM To: tutor at python.org Subject: Re: [Tutor] Popen and Prompting On 31/08/05, Faulconer, Steven M. wrote: > My question for all of you python people; how can I handle programs that MAY > need input from the command line. I thought about using something like > pexpect, but the input requests are fairly variable, and may not show up at > all. Also, I need to tie this in with the Tkinter GUI as well. The binaries > we are running are written in C, and we have no way of changing that (it's > in-house software, but the API we have to use does not talk to Python). Could you kludge it? eg, change the C programs so that, every time they ask for user input, they include in the prompt a certain unusual string. Then, any time your GUI detects this string in the program output, it can pop up a dialog box asking for user input. (just a suggestion ... I don't know the best way of dealing with this) -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From luckygoodluck at optonline.net Tue Aug 30 04:01:17 2005 From: luckygoodluck at optonline.net (luckygoodluck@optonline.net) Date: Mon, 29 Aug 2005 22:01:17 -0400 Subject: [Tutor] PYTHON???? Message-ID: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4> Dear Python, How does a calculator multiply? I want to create a computer software that can multiply. How do I program the computer to multiply? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050829/116d78b8/attachment.htm From levity at gmail.com Wed Aug 31 21:00:38 2005 From: levity at gmail.com (lawrence wang) Date: Wed, 31 Aug 2005 15:00:38 -0400 Subject: [Tutor] Closing SimpleXMLRPCServer properly Message-ID: <22e13a22050831120057776a4e@mail.gmail.com> I have a SimpleXMLRPCServer, which I've tweaked thusly: class StoppableXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): def serve_forever(self): """to stop this server: register a function in the class that uses it which sets server.stop to True.""" self.stop = False while not self.stop: self.handle_request() Here's the code where I start the server... try: self.server.serve_forever() finally: self.server.server_close() self.log('server closed') >From another thread, I set the server's stop attribute to False, so the server stops running. It exits the try block, runs server_close(), then I get the message 'server closed'... ...but when I try to use the port that the server's bound to again, it takes a very long time (while i try to use the port, catch the exception, sleep, try again) until it becomes free. Is there something else I need to call to ensure that the port is released cleanly? Is this an OS-specific thing out of my control? (I'm running Debian Linux.) Thanks in advance Lawrence -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050831/f6d5d97e/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Aug 31 21:00:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 31 Aug 2005 12:00:31 -0700 (PDT) Subject: [Tutor] Writing to XML file with minidom In-Reply-To: Message-ID: > > One snag that I found is that the des encryption that I used for the > > data that is written back, it is not parsed correctly when the file is > > read again with the new data in it. There is non-printable characters > > or non-ascii chars in that gives errors from expat when the contents > > is parsed. I had to use a different encryption algorithm. I am going > > to do some tests on it now. > > Put the cyphertext in a CDATA section, so the parser knows to ignore > its contents: > > > > ^KI^[?+?6? > ]]> > > Hi Travis, Putting pure binary bytes in an XML file has a flaw: the issue is that the binary bytes themselves might contain characters that could be interpreted as XML! Even if we wrap the content in CDATA, there's nothing that really stops the bytes from containing the characters "]]>" to prematurely close off the CDATA tag. To get around this, we can use a technique called "ascii-armor" to wrap protection around the troublesome binary text. http://en.wikipedia.org/wiki/ASCII_armor Python comes with a common ascii-armoring algorithm called "base64", and it's actually very easy to use it. Let's do a quick example. Let's say we have some binary unprintable bytes, like this: ###### >>> someBytes = open('/usr/bin/ls').read(8) >>> someBytes '\x7fELF\x01\x01\x01\x00' ###### (Hey, look, an Elf! *grin*) Anyway, this ELF will probably pass through email poorly, because the bytes surrounding it are pretty weird. But we can apply base64 encoding on those bytes: ###### >>> encodedBytes = someBytes.encode('base64') >>> encodedBytes 'f0VMRgEBAQA=\n' ###### And now it's in a form that should pass cleanly through. Decoding it is also a fairly easy task: ###### >>> encodedBytes.decode('base64') '\x7fELF\x01\x01\x01\x00' ###### And now we've got our ELF back. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Aug 31 21:02:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 31 Aug 2005 12:02:19 -0700 (PDT) Subject: [Tutor] PYTHON???? In-Reply-To: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4> Message-ID: On Mon, 29 Aug 2005 luckygoodluck at optonline.net wrote: > How does a calculator multiply? I want to create a computer software > that can multiply. How do I program the computer to multiply? Hello, Have you had a chance to look at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers There are a few tutorial there that should help you get started. Almost every one of them talks about how to get the computer to do basic arithmetic. If you have questions about the tutorials, please feel free to ask here. From dyoo at hkn.eecs.berkeley.edu Wed Aug 31 21:06:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 31 Aug 2005 12:06:22 -0700 (PDT) Subject: [Tutor] Popen and Prompting In-Reply-To: <8A443FA5598F9545A4583F9D3BECE43F25A0F187@mcl-its-exs01.mail.saic.com> Message-ID: On Tue, 30 Aug 2005, Faulconer, Steven M. wrote: > Been digging through the web and the archives for the tutor list and > can't seem to locate an answer to my question. It is probably out there, > but my searching skills are failing me. I recently wrote a GUI for > several command line programs using Tkinter. Everything is working quite > well, until I ran into one program that actually prompts for some input. Hi Steven, This is a common problem. The Unix folks have traditionally used a program called "Expect" to automate talking with interactive external processes. There's a Python equivalent to Expect: take a look at the 'pexpect' module. Here you go: http://pexpect.sourceforge.net/ The documentation on that page has a few examples that should help you get started. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Aug 31 21:21:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 31 Aug 2005 12:21:55 -0700 (PDT) Subject: [Tutor] Closing SimpleXMLRPCServer properly In-Reply-To: <22e13a22050831120057776a4e@mail.gmail.com> Message-ID: > class StoppableXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): > def serve_forever(self): > """to stop this server: register a function in the class > that uses it which sets server.stop to True.""" > self.stop = False > while not self.stop: > self.handle_request() > > Here's the code where I start the server... > > try: > self.server.serve_forever() > finally: > self.server.server_close() > self.log('server closed') > > >From another thread, I set the server's stop attribute to False, so the > server stops running. It exits the try block, runs server_close(), then I > get the message 'server closed'... > > ...but when I try to use the port that the server's bound to again, it > takes a very long time (while i try to use the port, catch the > exception, sleep, try again) until it becomes free. Is there something > else I need to call to ensure that the port is released cleanly? Is this > an OS-specific thing out of my control? (I'm running Debian Linux.) Hi Lawrence, It's TCP specific. When the server shuts down, the port is in a TIME_WAIT state that causes the port to wait until things are cleanly shut down. For more information on TIME_WAIT, see: http://www.developerweb.net/sock-faq/detail.php?id=13 Anyway, you can force the issue, get the server to "reuse" the address, by setting the "allow_reuse_address" attribute on your server. ###### class StoppableXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): """Override of TIME_WAIT""" allow_reuse_address = True def serve_forever(self): self.stop = False while not self.stop: self.handle_request() ###### See: http://www.python.org/doc/lib/module-SocketServer.html for a brief mention of allow_reuse_address. One of these days, I have to read Richard Stevens's book on TCP to better understand what exactly is going on. I have to admit that I don't understand the TCP model quite well yet. Best of wishes to you! From travislspencer at gmail.com Wed Aug 31 21:22:03 2005 From: travislspencer at gmail.com (Travis Spencer) Date: Wed, 31 Aug 2005 12:22:03 -0700 Subject: [Tutor] Writing to XML file with minidom In-Reply-To: References: Message-ID: On 8/31/05, Danny Yoo wrote: > Hi Travis, Hey Danny, > Putting pure binary bytes in an XML file has a flaw: the issue is that the > binary bytes themselves might contain characters that could be interpreted > as XML! Even if we wrap the content in CDATA, there's nothing that really > stops the bytes from containing the characters "]]>" to prematurely close > off the CDATA tag. Oh, sure. I didn't think that through, and if I had, I wouldn't have know how to work around it. > To get around this, we can use a technique called "ascii-armor" to wrap > protection around the troublesome binary text. > > http://en.wikipedia.org/wiki/ASCII_armor Brilliant. I won't forget the term "ascii-armor" if I ever find myself in Johan's shoes and I've forgotten the details. > (Hey, look, an Elf! *grin*) HA! > Hope this helps! Tremendously. Thanks, Danny! -- Regards, Travis Spencer From STEVEN.M.FAULCONER at saic.com Wed Aug 31 21:34:19 2005 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed, 31 Aug 2005 15:34:19 -0400 Subject: [Tutor] Popen and Prompting Message-ID: <8A443FA5598F9545A4583F9D3BECE43F25AC6644@mcl-its-exs01.mail.saic.com> Danny, Thanks for the response. We looked at using pexpect (I'm a UNIX guy at heart), but we have variable command prompts, that may or may not show up, with this program, so expect/pexpect would be difficult. John's suggestion was to add some sort of unique ID as a good idea, but won't work in this situation. I guess in the end, doing something with pexpect would be the way to go if I needed to. This issue has been resolved in another way (per my last message to the list). Thanks again for the response, Steven -----Original Message----- From: dyoo at hkn.eecs.berkeley.edu [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: Wednesday, August 31, 2005 3:06 PM To: Faulconer, Steven M. Cc: tutor at python.org Subject: Re: [Tutor] Popen and Prompting On Tue, 30 Aug 2005, Faulconer, Steven M. wrote: > Been digging through the web and the archives for the tutor list and > can't seem to locate an answer to my question. It is probably out there, > but my searching skills are failing me. I recently wrote a GUI for > several command line programs using Tkinter. Everything is working quite > well, until I ran into one program that actually prompts for some input. Hi Steven, This is a common problem. The Unix folks have traditionally used a program called "Expect" to automate talking with interactive external processes. There's a Python equivalent to Expect: take a look at the 'pexpect' module. Here you go: http://pexpect.sourceforge.net/ The documentation on that page has a few examples that should help you get started. Best of wishes to you! From albertito_g at hotmail.com Wed Aug 31 23:01:26 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 31 Aug 2005 21:01:26 +0000 Subject: [Tutor] Tail -f problem Message-ID: Hey I'm still working with this RADIUS system over Red Hat 9.0, mysql 3.23 and python 2.2.2 I ran to another problem.....I have a file that is written by the RADIUS server (for those who don't know RADIUS is an authentication Service). The file contains the detail of the RADIUS, the server writes the STOP and START signals to this file....below is the detail of the file. What I need to do is a program that check when the file gets an input and analyze only the text that has entered...I thought about tail-f /var/log/radacct/max/detail but this thing opens a console and I won't end but how can I get the output of the command to python.. This is one of two solutions....the other would be Upgrade the MySQL Server to version 4.1.11 which I don't have idea how to.... file desc ----------- Date User-Name NAS-IP-ADDRESS and a long list of variables ----------- end of file desc I know the second option has nothing to do with this forum but if anyone knows of any manual to upgrade MySQL over Linux Red HAt I would appreciate Thanks in advanced Alberto From nick at javacat.f2s.com Wed Aug 31 23:38:42 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed, 31 Aug 2005 22:38:42 +0100 Subject: [Tutor] Tail -f problem In-Reply-To: Message-ID: Hi Alberto, > -----Original Message----- > From: tutor-bounces+nick=javacat.f2s.com at python.org > [mailto:tutor-bounces+nick=javacat.f2s.com at python.org]On Behalf Of > Alberto Troiano > Sent: 31 August 2005 22:01 > To: tutor at python.org > Subject: [Tutor] Tail -f problem > > > Hey > I thought about tail-f > /var/log/radacct/max/detail but this thing opens a console and I > won't end > but how can I get the output of the command to python.. Have a look here for a possible solution to your tail -f problem http://twistedmatrix.com/projects/core/documentation/examples/filewatch.py > I know the second option has nothing to do with this forum but if anyone > knows of any manual to upgrade MySQL over Linux Red HAt I would appreciate If your using a recent Redhat then try this as root (im on a windows box at the moment so this is untested) $ yum upgrade mysql mysql-server Naturally this will only work if your current mysql install is an RPM. Cheers Nick . From surangasa at gmail.com Fri Aug 26 15:35:45 2005 From: surangasa at gmail.com (Suranga Sarukkali) Date: Fri, 26 Aug 2005 19:35:45 +0600 Subject: [Tutor] (no subject) Message-ID: <430F1AB1.30701@dialogsl.net> What does [sic] mean? I see it all the time. June Bakersfield, California Dear June: Us too. We always wondered why these three little letters appear next to misspellings and other mistakes. As with many grammatical issues, we learned that Latin is to blame. "Sic" is Latin for "thus." Yeah, that didn't clear it up for us either. But apparently, since the 1880s, writers have used [sic] next to quotations that include errors. This little notation means, "Hey, I know this quote looks wrong, but it was that way when I found it, so don't blame me." Maybe the original text used archaic spelling or the original writer just messed up. But the person who's quoting that text is aware of the earlier mistake and wants you to know it. [Sic] is shorthand for all that, at least to scholarly types.

' > print 'Differences %s: %s' % (htypestr, lbl1) > if html: You might want to consider some kind of template library; there are many to choose from. Generally speaking they merge a template and a data model. You would have a common data model and two templates - one for HTML and one for plain text. There are many Python template libraries to choose from; a relatively simple one is in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162292 Many more are listed here in the Templating Engines section: http://wiki.python.org/moin/WebProgramming Kent From jsmith at medplus.com Wed Aug 3 20:59:15 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 3 Aug 2005 14:59:15 -0400 Subject: [Tutor] CVS for Python Message-ID: <3B05FA2AD704244BB0CAB99D8026F5558E50@medexch2.medplus.com> If this is a Windows box then I highly recommend CVSNT (http://www.cvsnt.com/) with TortoiseCVS (http://www.tortoisecvs.org/). I've heard good things about Subversion but haven't tried it yet and don't know how its Windows installation is. There is also a TortoiseSVN (http://www.tortoisesvn.org/) for it. The Tortoise line are Windows explorer pluggins that allow you to use the Windows explorer to drive the systems. Another option is Perforce (www.perforce.com) which is free for up-to 2 users. Jeff -----Original Message----- From: Bernard Lebel [mailto:3dbernard at gmail.com] Sent: Wednesday, August 03, 2005 2:52 PM To: Python Tutor list Subject: Re: [Tutor] CVS for Python Okay sorry for not being clear. I meant CVS for my own Python scripts. Right now, when I make a change to an existing script, I copy it into an "old" directory, rename with to append the version number, and overrwrite the actual script with the new version. This works well but sometimes is a pain to handle when multiple files are involved in toolsets. Thanks Bernard On 8/3/05, Alan G wrote: > > Does anyone can recomment a good CVS for Python? > > CVS? > > What exactly do you want beyond the standard tool? > > Alan G. > > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From falcon3166 at hotmail.com Wed Aug 3 20:59:53 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 12:59:53 -0600 Subject: [Tutor] I've run into a jam on the exercise on file I/O References: <059901c59735$db8da080$8eaa8651@xp> Message-ID: Here is the latest code and error: Traceback (most recent call last): File "D:\Python24\grades.py", line 99, in -toplevel- save_grades(students,filename) File "D:\Python24\grades.py", line 51, in save_grades out_file.write(x+","+max_points[x]+"\n") TypeError: unsupported operand type(s) for +: 'int' and 'str' max_points = [25,25,50,25,100] assignments = ['hw ch 1','hw ch 2','quiz ','hw ch 3','test'] students = {1:max_points} def print_menu(): print "1. Add student" print "2. Remove student" print "3. Print grades" print "4. Record grade" print "5. Load Grades" print "6. Save Grades" print "9. Exit" def print_all_grades(): print '\t', for i in range(len(assignments)): print assignments[1],'\t', print keys = students.keys() keys.sort() for x in keys: print x,'\t', grades = students[x] print_grades(grades) def print_grades(grades): for i in range(len(grades)): print grades[i],'\t\t', print def choice(): return int(raw_input("Menu Choice: ")) def school(): return int(raw_input("Student ID: ")) def load_grades(students,filename): in_file = open(filename, "r") while 1: in_line = in_file.readline() if in_line == "": break in_line = in_line[:-1] [students,max_points] = string.split(in_line,",") max_points[students] = grade in_file.close() def save_grades(students,filename): out_file = open(filename, "w") for x in students.keys(): out_file.write(x+","+max_points[x]+"\n") out_file.close print "Grade Tracking Program." while 1: print_menu() menu_choice = choice() if menu_choice == 1: print "Add student" ID = school() students[ID] = [0]*len(max_points) elif menu_choice == 2: print "Remove student" ID = school() if students.has_key(ID): del students[ID] else: print "Student ID: ",ID," not found." elif menu_choice == 3: print_all_grades() elif menu_choice == 4: print "Record Grade" ID = school() if students.has_key(ID): grades = students[ID] print "Type in the number of the grade to record" print "Type in a 0 (zero) to exit" for i in range(len(assignments)): print i+1,' ',assignments[i],'\t', print print_grades(grades) which = 1234 while which != -1: which = int(raw_input("Change which Grade: ")) which = which-1 if 0 <= which < len(grades): grade = int(raw_input("Grade: ")) grades[which] = grade elif which != -1: print "Invalid Grade Number" else: print "Student not found" elif menu_choice == 5: filename = raw_input("Filename to load: ") load_grades(students,filename) elif menu_choice == 6: filename = raw_input("Filename to save: ") save_grades(students,filename) elif menu_choice == 9: break else: print "That's not a choice!" print "Goodbye." How can I fix it? ----- Original Message ----- From: "Nathan Pinno" To: "Alan G" ; "Yoo, Danny" ; "Bark, Adam" Cc: "Tutor" Sent: Wednesday, August 03, 2005 12:42 PM Subject: Re: [Tutor] I've run into a jam on the exercise on file I/O > I've been chatting with Albertito on MSN and came up with this solution: > int(x), and change student into student ids, and remove #Max. Will this > work, or will I need to add sequential IDs? > ----- Original Message ----- > From: "Alan G" > To: "Nathan Pinno" ; "Yoo, Danny" > ; "Bark, Adam" > Cc: "Tutor" > Sent: Tuesday, August 02, 2005 1:43 AM > Subject: Re: [Tutor] I've run into a jam on the exercise on file I/O > > >> >>> What if I were to use ID's for the students and use the ID's as the >>> sequence >>> index, and link the students and their grades to the IDs? >> >> Its not necessary for what you are doing but it's how you'd normally do >> it >> in a relational database, so if you ever needed to turn your file based >> program into a full blown database then using IDs would actually help! >> >> The other thing you could do is hold all the data for a single student >> in one structure. Thus instead of having lots of lists all linked by >> a common index (or ID) you have one collection of students (probably >> a dictionary keyed by name) each with all of its own data. This >> involves a more complex data structure and is a move in the direction >> of object oriented programming but without actual classes and objects >> being involved. This might also allow you to use the shelve moduile >> to save/restore your data to file easily. >> >> Just a thought, >> >> Alan G. >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jeffpeery at yahoo.com Wed Aug 3 21:04:05 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 3 Aug 2005 12:04:05 -0700 (PDT) Subject: [Tutor] imbedding python into another program? In-Reply-To: Message-ID: <20050803190405.92453.qmail@web30515.mail.mud.yahoo.com> Andre, thanks for the help with this. I put it to work yesterday and it works perfectly. was wondering if it is possible to import modules without a users having to type 'import whatever'. for example in my application I would like the user to just start operating on arrays that exist in my program. But I have to load both the arrays and Numeric into the python shell that I created. how can I do this? thanks. Andr? Roberge wrote: Jeff Peery wrote: > hello, is it possible to add something like the python IDLE into > another program, say if I wanted to simply run scripts from within a > wxPython program? Could someone point me to the correct reference? > thanks. > Hi Jeff, you may want to have a look at PyCrust, PyShell and the like. I do something like this in my rur-ple app (on sourceforge). The relevant lines of code are: import wx.py as py [inside a wx.Notebook] win = py.shell.Shell(self.window, -1, introText = tr.INTERPRETER_INTRO_TEXT) self.window.AddPage(win, tr.PYTHON_INTERPRETER) ============ HTH, Andr? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/08f0dfff/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Aug 3 21:05:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 12:05:59 -0700 (PDT) Subject: [Tutor] CVS for Python In-Reply-To: <61d0e2b405080311521216b102@mail.gmail.com> Message-ID: > I meant CVS for my own Python scripts. Right now, when I make a change > to an existing script, I copy it into an "old" directory, rename with to > append the version number, and overrwrite the actual script with the new > version. This works well but sometimes is a pain to handle when multiple > files are involved in toolsets. Hi Bernard, Ok, I see. You're using CVS as a general term for a revision (version) control system. I'd recommend not doing that, just because "CVS" is itself the name of an implementation of a revision control system. In programming terms: it's confusing interface with implementation. *grin* Anyway, definitely check out something like Subversion. It does exactly what you're doing by hand, but in a much more sane way than manual file copying. The Subversion folks have written a very nice tutorial introduction into the concept of revision control as a part of their book. For more details, see: http://svnbook.red-bean.com/en/1.1/svn-book.html Their tool is not really Python specific, but I find it invaluable in doing any kind of programming. Good luck to you! From bgailer at sbcglobal.net Wed Aug 3 21:03:25 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 03 Aug 2005 12:03:25 -0700 Subject: [Tutor] I need advice about which way to go. In-Reply-To: References: <06cc01c597fb$0d07af00$8eaa8651@xp> <6.1.2.0.0.20050803112700.0330f470@pop.sbcglobal.yahoo.com> Message-ID: <6.1.2.0.0.20050803114912.032dc918@pop.sbcglobal.yahoo.com> At 11:36 AM 8/3/2005, Nathan Pinno wrote: >Here is the code then: I'll throw in some suggestions. 1 - check for balanced parentheses. This has bit you before and you have several lines below with unbalanced parentheses. 2 - since Python indexes start at 0, take advantage of this. Use random.choice(range(13) and use the value to index the cards list. >#This is code for a blackjack game. >import random >cash = 0 >new_cash = 100 >cards = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", >"Nine", "Ten", "Jack", "Queen", "King"} >card_types = {"Diamond", "Heart", "Spade", "Club"} >bet = 0 >playertotal = 0 >comp_total = 0 > >def menu(): > print "1. Bet and play." > print "2. Cash out and Exit" > >def option(): > return int(raw_input("Menu choice: ")) > >def card_choice(): > return random.choice(range(1,14) This will return one number. The statement below (a,b = card_choice()) expects a tuple of 2 numbers to be returned. > def types(): > return random.choice(range(1,5) > >def player_cards(): > print a," of ",t1 > print b," of ",t2 > >print "Blackjack" >print "By Nathan Pinno" >while 1: > menu() > choice = option() > if choice == 1: > bet = int(raw_input("How much do you want to bet: ") Something is wrong with the indentation below. Assuming the if and else following the while are indented more, you have a BIG problem. What will happen if bet > new_cash? Endless loop printing the Sorry... forever > while 1: > if bet > new_cash: > print "Sorry, you don't have that much cash! Your total > cash is: $",new_cash > else: > break > a,b = card_choice() > t1,t2 = types() > if t1 == 1: > t1 = card_types[0] > elif t1 == 2: > t1 = cardtypes[1] > elif t1 == 3: > t1 = cardtypes[2] > else: > t1 = cardtypes[3] Why not just use the random integer as an index? If you use range(13) these if/elifs become t1 = cardtypes[t1] > if a == 1: > a = cards[0] > playertotal = playertotal + 1 > elif a == 2: > a = cards[1] > playertotal = playertotal + 2 Same thing here. What are the functions of b, t2, and playertotal? Especially for those of us who don't know blackjack. Does that help? Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/0349a176/attachment.htm From falcon3166 at hotmail.com Wed Aug 3 21:23:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 13:23:40 -0600 Subject: [Tutor] I need advice about which way to go. References: <06cc01c597fb$0d07af00$8eaa8651@xp> <6.1.2.0.0.20050803112700.0330f470@pop.sbcglobal.yahoo.com> <6.1.2.0.0.20050803114912.032dc918@pop.sbcglobal.yahoo.com> Message-ID: Playertotal is for calculating the total of the player's hand. This is important, because if the player's total is greater than 21, he loses in Blackjack. B is for the second card in the player's hand and t2 was for the second card's type (i.e Heart, Diamond, Club, or Spade) ----- Original Message ----- From: Bob Gailer To: Nathan Pinno ; Tutor mailing list ; Yoo, Danny Sent: Wednesday, August 03, 2005 1:03 PM Subject: Re: [Tutor] I need advice about which way to go. At 11:36 AM 8/3/2005, Nathan Pinno wrote: Here is the code then: I'll throw in some suggestions. 1 - check for balanced parentheses. This has bit you before and you have several lines below with unbalanced parentheses. 2 - since Python indexes start at 0, take advantage of this. Use random.choice(range(13) and use the value to index the cards list. #This is code for a blackjack game. import random cash = 0 new_cash = 100 cards = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"} card_types = {"Diamond", "Heart", "Spade", "Club"} bet = 0 playertotal = 0 comp_total = 0 def menu(): print "1. Bet and play." print "2. Cash out and Exit" def option(): return int(raw_input("Menu choice: ")) def card_choice(): return random.choice(range(1,14) >This will return one number. The statement below (a,b = card_choice()) expects a tuple of 2 numbers to be returned. How do I make it return two numbers? def types(): return random.choice(range(1,5) def player_cards(): print a," of ",t1 print b," of ",t2 print "Blackjack" print "By Nathan Pinno" while 1: menu() choice = option() if choice == 1: bet = int(raw_input("How much do you want to bet: ") Something is wrong with the indentation below. Assuming the if and else following the while are indented more, you have a BIG problem. What will happen if bet > new_cash? Endless loop printing the Sorry... forever Thanks, I forgot about that. I have to add bet = int(raw_input("Bet: ")) while 1: if bet > new_cash: print "Sorry, you don't have that much cash! Your total cash is: $",new_cash else: break a,b = card_choice() t1,t2 = types() if t1 == 1: t1 = card_types[0] elif t1 == 2: t1 = cardtypes[1] elif t1 == 3: t1 = cardtypes[2] else: t1 = cardtypes[3] Why not just use the random integer as an index? If you use range(13) these if/elifs become t1 = cardtypes[t1] if a == 1: a = cards[0] playertotal = playertotal + 1 elif a == 2: a = cards[1] playertotal = playertotal + 2 Same thing here. What are the functions of b, t2, and playertotal? Especially for those of us who don't know blackjack. Does that help? It helps some, but if you could answer my question above about how to return two random numbers, it would be appreciated. Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/c4000bd7/attachment.htm From cpu.crazy at gmail.com Wed Aug 3 21:06:04 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 03 Aug 2005 13:06:04 -0600 Subject: [Tutor] More Q's on Socket Programming Message-ID: <42F1159C.5060408@gmail.com> Hi, I changed my mind. After I got interested in socket programming I decided to make a bot. But then I got an idea to make a chatting program. It worked nicely on our home network but it had a small problem.... you can't type anything and send it to the person you are chatting with untill they reply!! I also have one computer as the server and another as the client.... can I have a dedicated server program that handles two clients instead of having a direct connect? If you have any examples please send them too me.. it would be very much appreciated!! Thanks, Joe From tegmine at gmail.com Wed Aug 3 22:52:43 2005 From: tegmine at gmail.com (Luis N) Date: Wed, 3 Aug 2005 13:52:43 -0700 Subject: [Tutor] Zope/Python web devel In-Reply-To: <200508031249.44227.python@jayloden.com> References: <200508031249.44227.python@jayloden.com> Message-ID: <77bfa81a05080313521c39f710@mail.gmail.com> On 8/3/05, Jay Loden wrote: > I've been considering some web projects recently, but I have some concerns > about selecting the tools I plan to use. I like Python, and I was immediately > thinking of using Zope to build on. > > However, I am concerned about performance, resource usage, and scalability. > Does anyone here have any experience with Zope or any other application > frameworks like CherryPy used in a large/enterprise environment? Is Zope > overly memory hungry or slow? If performance is a key point, am I better off > growing my own solution from the ground up? > > Second, and more specific to Python itself - does anyone here have first hand > knowledge of how Python compares with other solutions for server side web > development? I'm specifically interested in comparisons to PHP, but Ruby, > Perl, Java, C/C++ and Lisp, etc. observations would be welcome. Basically, > I'm trying to get a feel for what kind of performance and resource usage I'd > see out of Python versus other options. I realize this is heavily dependent > on what exactly I end up doing, but just as a general observation, I'd like > to know what others have experienced. I know that some large web applications > are built on Python (Yahoo Mail, Google), but there's certainly less being > done in Python on the web than in Perl or PHP. I just want to make sure this > isn't because of Python disadvantages as opposed to simple market share. > > All responses are welcome. If anyone has links to some benchmarking studies > comparing the two for web development I'd be grateful for those as well. > > -Jay I don't have any particular experience with the various web frameworks, but have experimented with most of them. Benchmarks are more or less useless in this arena (it depends on what you are doing, and how you intend to do it), and as they say there exists three kinds of lies: lies, damn lies, and statistics! Zope2.x is a bit of a bear IMO, but has a great number of packages to use. The most compelling reasons to use Zope2 might be Plone or Silva. I didn't pay much attention to CPU usage (usually 0 anyway, unless a request is firing), but ram for Zope2 from my VPS on a FreeBSD box, basic functionality, no additional packages, was approximately 24mb; with Silva, 30mb; and with Plone+Psyco, 50mb. This is just the beginning of course. If you want a community site, use Plone, if you want to grok Zope use Silva. Zope scales http://www.enfoldsystems.com/About/News/oxfam Zope3 is interesting, but is fairly fresh. Ram usage tends towards 30mb with no additional packages. Twisted is an excellent framework, with the downside that your code becomes somewhat tied to Twisted (although this is true with any framework), and single thread methodology. Nevow+Livepage looks interesting, but I've never really experimented. Livepage seems to fail if Twisted is proxied by another server, such as Apache. Ram usage begins at 10mb, with a fully loaded site, including database access via an adapter such as pgasync, requiring about 20mb. The most compelling feature of Twisted is its breadth of protocols i.e. http server, with xmlrpc and soap, in almost 0 lines of code (provided you understand the libraries :^) CherryPy2 is the most interesting in my opinion, the builtin server tends towards 16mb of ram out of the box. Your code is pure python, without requiring you to learn many cherrpyism's, which also means your code will be more portable, say if you wished to create a tk/wx gui front, in addition to the web. I beleive that the builtin cherry server is to be depracated in some future release, in favor of WSGI. I have been writing a rather long CGI, and am intending to port the code to cherrypy. Not certain about cherrypy's enterprise applicability, and starting/stopping the server when your code changes can be annoying, however, it seems to work... As to the rest of your question, coffee's waiting, and my fingers are tired... You may get a greater response on the comp.lang.python newsgroup. Luis. From falcon3166 at hotmail.com Wed Aug 3 23:13:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 15:13:33 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> <033601c5962e$ba308090$8eaa8651@xp> Message-ID: When I ran my new password program, using getpass, it warned me that passwords might be echoed, because there was a problem with getpass. How do I fix this? ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Alberto Troiano" ; "Danny Yoo" ; "luke" Cc: Sent: Sunday, July 31, 2005 6:19 PM Subject: Re: [Tutor] Help with file I/O. >>> You might find the getpass module useful for that... >>> It provides a raw_input style prompt that doesn't >>> display what the user types... > >> Does it display stars instead? > > No, its more secure than that, it doesn't display anything. > > But like anything in Python the esiest way to find out is just to try it > at the >>> prompt. > >>>> import getpass >>>> pw = getpass.getpass('Password: ') > Password: >>>> print pw > mysecret >>>> > > HTH > > Alan G > From alan.gauld at freenet.co.uk Wed Aug 3 23:36:55 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 22:36:55 +0100 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> <033601c5962e$ba308090$8eaa8651@xp> Message-ID: <07da01c59873$7871c4b0$8eaa8651@xp> > When I ran my new password program, using getpass, it warned me that > passwords might be echoed, because there was a problem with getpass. > How do I fix this? Can we see the code and error message. Otherwise we'd just be guessing... The Python error messages usually tell you as much as you need to fix it, like roughly where to look and what the nature of problem is. If its not really an error what happens when you run your program? Does getpass import? (Try it at the >>> prompt) If so does it in fact echo? Alan G. From falcon3166 at hotmail.com Wed Aug 3 23:42:00 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 15:42:00 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> <033601c5962e$ba308090$8eaa8651@xp> <07da01c59873$7871c4b0$8eaa8651@xp> Message-ID: The error was: Warning: Problem with getpass. Passwords may be echoed. My code is: #This is for a password protected program to store passwords. import getpass password = "hello" sitelist = {} def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "9) Exit" def add_site(): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = getpass.getpass("Password: ") sitelist[site] = [id,passcard] def lookup_site(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitlist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_site(): print "Remove a login info card" site = raw_input("Site: ") if sitelist.has_key(site): del sitelist[site] else: print site," was not found." def print_login_info(): print "Login Info" for x in sitelist.keys(): print "Site: ",x," \tID: ",sitelist[x][0]," \tPassword: ",sitelist[x][1],"\n" print "The Password Program" print "By Nathan Pinno" print answer = getpass.getpass("What is the password? ") while password != answer: print "The password is incorrect." answer = getpass.getpass("What is the password? ") print "Welcome to the second half of the program." while 1: main_menu() menu_choice = int(raw_input("Choose an option: ")) if menu_choice == 1: add_site() elif menu_choice == 2: lookup_site() elif menu_choice == 3: remove_site() elif menu_choice == 4: print_login_info() elif menu_choice == 9: break else: print "That's not an option!" print "Have a nice day!" Thanks for the help! Nathan Pinno ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Alberto Troiano" ; "Danny Yoo" ; "luke" Cc: Sent: Wednesday, August 03, 2005 3:36 PM Subject: Re: [Tutor] Help with file I/O. > >> When I ran my new password program, using getpass, it warned me that >> passwords might be echoed, because there was a problem with getpass. How >> do I fix this? > > Can we see the code and error message. Otherwise we'd just be guessing... > > The Python error messages usually tell you as much as you need to fix > it, like roughly where to look and what the nature of problem is. > > If its not really an error what happens when you run your program? > Does getpass import? (Try it at the >>> prompt) > > If so does it in fact echo? > > Alan G. > > From alan.gauld at freenet.co.uk Wed Aug 3 23:45:46 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 22:45:46 +0100 Subject: [Tutor] I need advice about which way to go. References: <06cc01c597fb$0d07af00$8eaa8651@xp><6.1.2.0.0.20050803112700.0330f470@pop.sbcglobal.yahoo.com> Message-ID: <07f201c59874$b4cae030$8eaa8651@xp> > cards = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", > "Eight", > "Nine", "Ten", "Jack", "Queen", "King"} > card_types = {"Diamond", "Heart", "Spade", "Club"} {} means they are dictionaries but you don;t provide key:value pairs. You probably want lists here not dictionaries. You can read about the differences in the Raw Materials topic of my tutorial. > if t1 == 1: > t1 = card_types[0] And you don't have a '0' key in your dictionaries so this will fail. > Now do you have an idea of what I'm pointing to? I think we get the idea but you need to think about what exactly your data looks like. Why not break the program into bits, just write a small program that draws cards, or deals a small hand - two cards for blackjack! Once you have that working just get the basic rules sorted out so you can play the game. Then add the money bits once you have a working game. This kind of evolutionary development is how most programmers build up their code. Try sometjing oin the interpreter, turn it into a simple program that does one key thing right. Test it. Once it works go back to the interpreter and try the next bit, write it into the program. Test it and get it working. Check the oroiginal stuff still works too. Repeat until done. Its this interpreter/editor/test loop that makes Python such a powerful development tool. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Aug 3 23:49:32 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 22:49:32 +0100 Subject: [Tutor] CVS for Python References: <61d0e2b40508031100174399bb@mail.gmail.com><07c601c5985b$7f36a260$8eaa8651@xp> <61d0e2b405080311521216b102@mail.gmail.com> Message-ID: <080601c59875$3b4dfed0$8eaa8651@xp> > I meant CVS for my own Python scripts. Yep, but that's just standard CVS functionality. You set up a CVS repository and load your scripts into them using normal CVS commands. Actually I don't use CVS for this but rather the simpler RCS, upon which CVS is built. But there is nothing special about Python scripts, any version control tool will work. At work I use Borland StarTeam, but then I don't have to pay for it! Alan G. From alan.gauld at freenet.co.uk Wed Aug 3 23:56:05 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 3 Aug 2005 22:56:05 +0100 Subject: [Tutor] More Q's on Socket Programming References: <42F1159C.5060408@gmail.com> Message-ID: <082101c59876$25dd4c30$8eaa8651@xp> > chatting with untill they reply!! I also have one computer as the > server and another as the client.... can I have a dedicated server > program that handles two clients instead of having a direct connect? Yes, but usually the way to do that is to have the server listening for requests and then spawning either another process to handle the request (typically using fork() ) or to start a separate thread. Forking is slightly easier IMHO but threading is more efficient. That way you can support multiple clients at once. Thats pretty much how most web srvers work, they listen for http requests, spawn a thread/process to respond with the html and carry on listening for the next request on port 80. Alan G. From rog55555 at cpinternet.com Thu Aug 4 01:05:07 2005 From: rog55555 at cpinternet.com (Roger Sell) Date: Wed, 03 Aug 2005 18:05:07 -0500 Subject: [Tutor] removal Message-ID: <42F14DA3.4080705@cpinternet.com> Please remove from the Tutor recipient list. Thanks, Roger Sell From falcon3166 at hotmail.com Thu Aug 4 03:21:59 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:21:59 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied Message-ID: Hey all, What wrong with the following syntax? def save_file(sitelist,filename): out_file = open(filename,"w") for site in sitelist.keys(): out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") out_file.close() It highlighted the last " if that will help any. I can't show you the error due to the fact that the error appeared in a separate box, instead of in the IDLE window. If you need the rest of the code, just ask. It ran perfect before I added file I/O. Thanks in advance, Nathan Pinno Crew, Camrose McDonalds and owner/operator of Woffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/a07a8d26/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050803/a07a8d26/PinnoNathanPaul-0001.vcf From falcon3166 at hotmail.com Thu Aug 4 03:27:44 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:27:44 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke><030701c59629$ebd35b90$8eaa8651@xp><033601c5962e$ba308090$8eaa8651@xp><07da01c59873$7871c4b0$8eaa8651@xp> Message-ID: It does indeed echo. I forgot to add that. ----- Original Message ----- From: "Nathan Pinno" To: "Alan G" ; "Alberto Troiano" ; "Danny Yoo" ; "luke" Cc: Sent: Wednesday, August 03, 2005 3:42 PM Subject: Re: [Tutor] Help with file I/O. > The error was: > Warning: Problem with getpass. Passwords may be echoed. > > > > My code is: > > #This is for a password protected program to store passwords. > import getpass > password = "hello" > sitelist = {} > > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "9) Exit" > > def add_site(): > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = getpass.getpass("Password: ") > sitelist[site] = [id,passcard] > > def lookup_site(): > print "Lookup a login info card" > site = raw_input("Site: ") > if sitelist.has_key(site): > print "The ID is: ",sitlist[site][0] > print "The password is: ",sitelist[site][1] > else: > print site," was not found." > > def remove_site(): > print "Remove a login info card" > site = raw_input("Site: ") > if sitelist.has_key(site): > del sitelist[site] > else: > print site," was not found." > > def print_login_info(): > print "Login Info" > for x in sitelist.keys(): > print "Site: ",x," \tID: ",sitelist[x][0]," \tPassword: > ",sitelist[x][1],"\n" > > print "The Password Program" > print "By Nathan Pinno" > print > answer = getpass.getpass("What is the password? ") > while password != answer: > print "The password is incorrect." > answer = getpass.getpass("What is the password? ") > > print "Welcome to the second half of the program." > while 1: > main_menu() > menu_choice = int(raw_input("Choose an option: ")) > if menu_choice == 1: > add_site() > elif menu_choice == 2: > lookup_site() > elif menu_choice == 3: > remove_site() > elif menu_choice == 4: > print_login_info() > elif menu_choice == 9: > break > else: > print "That's not an option!" > print "Have a nice day!" > > > > Thanks for the help! > > Nathan Pinno > > ----- Original Message ----- > From: "Alan G" > To: "Nathan Pinno" ; "Alberto Troiano" > ; "Danny Yoo" ; > "luke" > > Cc: > Sent: Wednesday, August 03, 2005 3:36 PM > Subject: Re: [Tutor] Help with file I/O. > > >> >>> When I ran my new password program, using getpass, it warned me that >>> passwords might be echoed, because there was a problem with getpass. How >>> do I fix this? >> >> Can we see the code and error message. Otherwise we'd just be guessing... >> >> The Python error messages usually tell you as much as you need to fix >> it, like roughly where to look and what the nature of problem is. >> >> If its not really an error what happens when you run your program? >> Does getpass import? (Try it at the >>> prompt) >> >> If so does it in fact echo? >> >> Alan G. >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 03:36:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 18:36:36 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > What wrong with the following syntax? > > out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") [text cut] > It highlighted the last " if that will help any. Take a close look at the end of the line. Here, I'll underline it: out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") ^^^^^^^^^^^^^^^^^^^^^ Do you see anything unusual there? From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 03:41:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 18:41:57 -0700 (PDT) Subject: [Tutor] Help with file I/O. In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > > Warning: Problem with getpass. Passwords may be echoed. > It does indeed echo. I forgot to add that. Hi Nathan, If you're running your program under IDLE, we shouldn't expect too much: getpass depends on running under a console environment, and probably will not work under IDLE. If you're running under a console window, getpass should do the right thing. If this explains what's going on, then I wouldn't worry too much about this. The reason is because if you ever do deploy your programs to other people, you will almost certainly have them running standalone, outside of IDLE, since IDLE's there just to help you program interactively. From kristian.zoerhoff at gmail.com Thu Aug 4 03:42:08 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Wed, 3 Aug 2005 20:42:08 -0500 Subject: [Tutor] Help with file I/O. In-Reply-To: References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke> <030701c59629$ebd35b90$8eaa8651@xp> <033601c5962e$ba308090$8eaa8651@xp> <07da01c59873$7871c4b0$8eaa8651@xp> Message-ID: <3511dc7505080318426544de35@mail.gmail.com> On 8/3/05, Nathan Pinno wrote: > The error was: > Warning: Problem with getpass. Passwords may be echoed. This sounds like a problem with your terminal. What OS are you running this on? It appears to be some variant of Windows, based on your earlier posts, but the particular version may be germane to this discussion. -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From falcon3166 at hotmail.com Thu Aug 4 03:45:19 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:45:19 -0600 Subject: [Tutor] Help with file I/O. References: Message-ID: Thanks Danny. Albertito and me thought there might be a bug there. I see that guess was wrong. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor" Sent: Wednesday, August 03, 2005 7:41 PM Subject: Re: [Tutor] Help with file I/O. > > > On Wed, 3 Aug 2005, Nathan Pinno wrote: > >> > Warning: Problem with getpass. Passwords may be echoed. > >> It does indeed echo. I forgot to add that. > > > Hi Nathan, > > If you're running your program under IDLE, we shouldn't expect too much: > getpass depends on running under a console environment, and probably will > not work under IDLE. If you're running under a console window, getpass > should do the right thing. > > If this explains what's going on, then I wouldn't worry too much about > this. The reason is because if you ever do deploy your programs to other > people, you will almost certainly have them running standalone, outside of > IDLE, since IDLE's there just to help you program interactively. > > From falcon3166 at hotmail.com Thu Aug 4 03:48:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:48:40 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: The only thing I see there is [0] and [1]. Should that be passcard instead? ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 7:36 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > > On Wed, 3 Aug 2005, Nathan Pinno wrote: > >> What wrong with the following syntax? >> >> >> out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") > [text cut] >> It highlighted the last " if that will help any. > > > Take a close look at the end of the line. Here, I'll underline it: > > out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") > ^^^^^^^^^^^^^^^^^^^^^ > > Do you see anything unusual there? > > From falcon3166 at hotmail.com Thu Aug 4 03:49:45 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:49:45 -0600 Subject: [Tutor] Help with file I/O. References: <001c01c5961b$e3aa4f40$aa0ca8c0@luke><030701c59629$ebd35b90$8eaa8651@xp><033601c5962e$ba308090$8eaa8651@xp><07da01c59873$7871c4b0$8eaa8651@xp> <3511dc7505080318426544de35@mail.gmail.com> Message-ID: I'm running Windows XP Home, but Albertito tried the same code on XP Pro, and got the same response. ----- Original Message ----- From: "Kristian Zoerhoff" To: Sent: Wednesday, August 03, 2005 7:42 PM Subject: Re: [Tutor] Help with file I/O. > On 8/3/05, Nathan Pinno wrote: >> The error was: >> Warning: Problem with getpass. Passwords may be echoed. > > This sounds like a problem with your terminal. What OS are you running > this on? It appears to be some variant of Windows, based on your > earlier posts, but the particular version may be germane to this > discussion. > > -- > Kristian > > kristian.zoerhoff(AT)gmail.com > zoerhoff(AT)freeshell.org > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Thu Aug 4 03:51:43 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:51:43 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: <6.1.2.0.0.20050803183953.034665b0@pop.sbcglobal.yahoo.com> Message-ID: That's part of my signature. It describes who I am. ----- Original Message ----- From: Bob Gailer To: Nathan Pinno ; Tutor mailing list Sent: Wednesday, August 03, 2005 7:48 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied At 06:21 PM 8/3/2005, Nathan Pinno wrote: Hey all, What wrong with the following syntax? def save_file(sitelist,filename): out_file = open(filename,"w") for site in sitelist.keys(): out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") sitelist[site][1]"\n" is not valid. I think you want sitelist[site][1] + "\n" out_file.close() You can simplify things by using items(): for key, value in sitelist.items(): out_file.write(key +","+value[0] +","+value[1]+"\n") % formatting can make it even nicer: out_file.write("%s,%s,%s\n" % (key, value[0], value[1]) It highlighted the last " if that will help any. I can't show you the error due to the fact that the error appeared in a separate box, instead of in the IDLE window. If you need the rest of the code, just ask. It ran perfect before I added file I/O. Thanks in advance, Nathan Pinno Crew, Camrose McDonalds and owner/operator of Woffee Just out of curiosity, would you explain "Crew, Camrose McDonalds and owner/operator of Woffee" Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/6fa93d2a/attachment-0001.htm From falcon3166 at hotmail.com Thu Aug 4 03:58:38 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:58:38 -0600 Subject: [Tutor] How do I fix the following error? Code and error message supplied. Message-ID: Hey all, How do I fix the following error: File to load: passcard.txt Traceback (most recent call last): File "D:\Python24\password.py", line 82, in -toplevel- load_file(sitelist,filename) File "D:\Python24\password.py", line 51, in load_file [site,ID,passcard] = string.split(in_line,",") File "D:\Python24\lib\string.py", line 292, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' #This is for a password protected program to store passwords. import string password = "hello" sitelist = {} def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Load info" print "6) Save info" print "9) Exit" def add_site(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [ID,passcard] def lookup_site(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitlist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_site(): print "Remove a login info card" site = raw_input("Site: ") if sitelist.has_key(site): del sitelist[site] else: print site," was not found." def print_login_info(): print "Login Info" for site in sitelist.keys(): print "Site: ",site," \tID: ",sitelist[site][0]," \tPassword: ",sitelist[site][1],"\n" def load_file(sitelist,filename): in_file = open(filename,"r") while 1: in_line = in_file.readlines() if in_line == "": break in_line = in_line[:-1] [site,ID,passcard] = string.split(in_line,",") sitelist[site] = sitelist def save_file(sitelist,filename): out_file = open(filename,"w") for site in sitelist.keys(): out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]+"\n") out_file.close() print "The Password Program" print "By Nathan Pinno" print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") print "Welcome to the second half of the program." while 1: main_menu() menu_choice = int(raw_input("Choose an option (1-6, or 9: ")) if menu_choice == 1: add_site() elif menu_choice == 2: lookup_site() elif menu_choice == 3: remove_site() elif menu_choice == 4: print_login_info() elif menu_choice == 5: filename = raw_input("File to load: ") load_file(sitelist,filename) elif menu_choice == 6: filename = raw_input("Filename to save as: ") save_file(sitelist,filename) elif menu_choice == 9: break else: print "That's not an option!" print "Have a nice day!" Thanks in advance, Nathan Pinno, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/7cca3b12/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 630 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050803/7cca3b12/PinnoNathanPaul.vcf From falcon3166 at hotmail.com Thu Aug 4 03:59:24 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 19:59:24 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: See my latest message for how I fixed this error and got another in its place. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 7:48 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > The only thing I see there is [0] and [1]. Should that be passcard > instead? > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Wednesday, August 03, 2005 7:36 PM > Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > >> >> >> On Wed, 3 Aug 2005, Nathan Pinno wrote: >> >>> What wrong with the following syntax? >>> >>> >>> out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") >> [text cut] >>> It highlighted the last " if that will help any. >> >> >> Take a close look at the end of the line. Here, I'll underline it: >> >> out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") >> ^^^^^^^^^^^^^^^^^^^^^ >> >> Do you see anything unusual there? >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at sbcglobal.net Thu Aug 4 03:48:29 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 03 Aug 2005 18:48:29 -0700 Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: References: Message-ID: <6.1.2.0.0.20050803183953.034665b0@pop.sbcglobal.yahoo.com> At 06:21 PM 8/3/2005, Nathan Pinno wrote: >Hey all, > >What wrong with the following syntax? > >def save_file(sitelist,filename): > out_file = open(filename,"w") > for site in sitelist.keys(): > out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") sitelist[site][1]"\n" is not valid. I think you want sitelist[site][1] + "\n" > out_file.close() You can simplify things by using items(): for key, value in sitelist.items(): out_file.write(key +","+value[0] +","+value[1]+"\n") % formatting can make it even nicer: out_file.write("%s,%s,%s\n" % (key, value[0], value[1]) >It highlighted the last " if that will help any. > >I can't show you the error due to the fact that the error appeared in a >separate box, instead of in the IDLE window. > >If you need the rest of the code, just ask. It ran perfect before I added >file I/O. > >Thanks in advance, >Nathan Pinno >Crew, Camrose McDonalds and owner/operator of Woffee Just out of curiosity, would you explain "Crew, Camrose McDonalds and owner/operator of Woffee" Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/3862e8ca/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 04:31:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 19:31:35 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > See my latest message for how I fixed this error and got another in its > place. Wait, wait, before we go on: can you explain in your own words why there was something wrong, what the correction was, and why the correction works? The reason I ask is because I want to avoid the situation where you just copy-and-paste a solution and don't understand why it fixes things. I guess I'm being annoying in trying to make sure you're actually learning from your mistakes. *grin* From falcon3166 at hotmail.com Thu Aug 4 04:35:53 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 20:35:53 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: Sure, the problem was that I had forgotten a comma before the "\n". I added a comma and it came up with another error that I fixed on my own, then the current error came up. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 8:31 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > > On Wed, 3 Aug 2005, Nathan Pinno wrote: > >> See my latest message for how I fixed this error and got another in its >> place. > > Wait, wait, before we go on: can you explain in your own words why there > was something wrong, what the correction was, and why the correction > works? > > The reason I ask is because I want to avoid the situation where you just > copy-and-paste a solution and don't understand why it fixes things. > > I guess I'm being annoying in trying to make sure you're actually learning > from your mistakes. *grin* > > From jeffpeery at yahoo.com Thu Aug 4 04:36:57 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 3 Aug 2005 19:36:57 -0700 (PDT) Subject: [Tutor] commercial use of python? Message-ID: <20050804023657.31585.qmail@web30501.mail.mud.yahoo.com> hello, I was wondering about the license agreement for python. if I use python to create an application that is intended to sell commercially for profit is that violating the agreement listed in www.opensource.com? Or is that only for the interpreter? for example if I embed the python interpreter into a application written in pthon that is intended to be sold for profit is that violating the license agreement? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/b5e06e87/attachment.htm From falcon3166 at hotmail.com Thu Aug 4 04:40:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 20:40:28 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: I forgot to add that it works because commas separate it into groups so that when the reads the file it has output, the program can split it into the site, ID, and passcard. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 8:35 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > Sure, the problem was that I had forgotten a comma before the "\n". I > added > a comma and it came up with another error that I fixed on my own, then the > current error came up. > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Wednesday, August 03, 2005 8:31 PM > Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > >> >> >> On Wed, 3 Aug 2005, Nathan Pinno wrote: >> >>> See my latest message for how I fixed this error and got another in its >>> place. >> >> Wait, wait, before we go on: can you explain in your own words why there >> was something wrong, what the correction was, and why the correction >> works? >> >> The reason I ask is because I want to avoid the situation where you just >> copy-and-paste a solution and don't understand why it fixes things. >> >> I guess I'm being annoying in trying to make sure you're actually >> learning >> from your mistakes. *grin* >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 04:45:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 19:45:41 -0700 (PDT) Subject: [Tutor] How do I fix the following error? Code and error message supplied. In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > Traceback (most recent call last): > File "D:\Python24\password.py", line 82, in -toplevel- > load_file(sitelist,filename) > File "D:\Python24\password.py", line 51, in load_file > [site,ID,passcard] = string.split(in_line,",") > File "D:\Python24\lib\string.py", line 292, in split > return s.split(sep, maxsplit) > AttributeError: 'list' object has no attribute 'split' Hi Nathan, Let's pay attention to the line 51 in your file: > [site,ID,passcard] = string.split(in_line,",") string.split() will fail if it is being given a set of arguments that it doesn't understand. string.split() works only if in_line is a string. But in the function load_file(), in_line is a list of strings. So there's definitely a bug in load_file, in confusing the list of lines with a particular single line. Actuallly, a lot of load_file() needs some rework. We strongly recommend you go through: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm because the code that you're writing to handle the reading of files is using a very old style of Python that hasn't been seen since the Python 1.52 days; I suspect that you are learning from a very deprecated tutorial! The approach that Alan takes in his "Learning How to Program" tutorial uses a more modern, less bug-prone style of reading files. From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 04:53:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 19:53:28 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > I forgot to add that it works because commas separate it into groups so that > when the reads the file it has output, the program can split it into the > site, ID, and passcard. Hi Nathan, Ok, it's good that we're looking back, because that's not right; commas did not have to do with what was causing problems. Let's look at the buggy statement again. out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") With fresh eyse, can you look back at how you corrected this? If you think this my insisting on you seeing why things weren't working, consider this: if it's an easy error to make (and it is an easy mistake to make), you may want to spend some time to learn how to recognize the error and its correction. That way, you don't have to wait for folks on Tutor to point things out for you. From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 04:57:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 19:57:22 -0700 (PDT) Subject: [Tutor] commercial use of python? In-Reply-To: <20050804023657.31585.qmail@web30501.mail.mud.yahoo.com> Message-ID: On Wed, 3 Aug 2005, Jeff Peery wrote: > hello, I was wondering about the license agreement for python. if I use > python to create an application that is intended to sell commercially > for profit is that violating the agreement listed in www.opensource.com? > Or is that only for the interpreter? for example if I embed the python > interpreter into a application written in pthon that is intended to be > sold for profit is that violating the license agreement? Hi Jeff, No, you should be fine. For the gory details, see: http://python.org/psf/license.html and: http://python.org/doc/faq/general.html#are-there-copyright-restrictions-on-the-use-of-python From falcon3166 at hotmail.com Thu Aug 4 05:03:25 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 21:03:25 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: I added a plus sign to show Python to add "\n" or a new line to end of the file. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 8:53 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > > On Wed, 3 Aug 2005, Nathan Pinno wrote: > >> I forgot to add that it works because commas separate it into groups so >> that >> when the reads the file it has output, the program can split it into the >> site, ID, and passcard. > > > Hi Nathan, > > Ok, it's good that we're looking back, because that's not right; commas > did not have to do with what was causing problems. Let's look at the > buggy statement again. > > out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") > > With fresh eyse, can you look back at how you corrected this? > > > If you think this my insisting on you seeing why things weren't working, > consider this: if it's an easy error to make (and it is an easy mistake to > make), you may want to spend some time to learn how to recognize the error > and its correction. That way, you don't have to wait for folks on Tutor > to point things out for you. > > From falcon3166 at hotmail.com Thu Aug 4 05:09:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 21:09:33 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: At least I know the basics of file I/O for here is my filereader and filewriter programs: Filereader: filename = raw_input("File name please: ") f = file(filename, "r") for line in f.readlines(): print line f.close() Filewriter: text = raw_input("Enter some text to export: ") filename = raw_input("File to write to: ") out_file = open(filename,"w") out_file.write(text) out_file.close() ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 9:03 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied >I added a plus sign to show Python to add "\n" or a new line to end of the > file. > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Wednesday, August 03, 2005 8:53 PM > Subject: Re: [Tutor] What's the invalid syntax? Code supplied > > >> >> >> On Wed, 3 Aug 2005, Nathan Pinno wrote: >> >>> I forgot to add that it works because commas separate it into groups so >>> that >>> when the reads the file it has output, the program can split it into the >>> site, ID, and passcard. >> >> >> Hi Nathan, >> >> Ok, it's good that we're looking back, because that's not right; commas >> did not have to do with what was causing problems. Let's look at the >> buggy statement again. >> >> out_file.write(site+","+sitelist[site][0]+","+sitelist[site][1]"\n") >> >> With fresh eyse, can you look back at how you corrected this? >> >> >> If you think this my insisting on you seeing why things weren't working, >> consider this: if it's an easy error to make (and it is an easy mistake >> to >> make), you may want to spend some time to learn how to recognize the >> error >> and its correction. That way, you don't have to wait for folks on Tutor >> to point things out for you. >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 05:10:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 20:10:45 -0700 (PDT) Subject: [Tutor] More Q's on Socket Programming In-Reply-To: <42F1159C.5060408@gmail.com> Message-ID: On Wed, 3 Aug 2005, Joseph Quigley wrote: > decided to make a bot. But then I got an idea to make a chatting > program. It worked nicely on our home network but it had a small > problem.... you can't type anything and send it to the person you are > chatting with untill they reply!! Hi Joseph, Can you show us the code? We might be able to identify the issue here. I suspect, though, that it has to do with the asynchronous nature of sockets, and how you might be doing something like: next_line = raw_input(">> ") which prevents you from checking the socket for input. Basically, your program is trying to do two things at once: read input from the user at the console, and read input from the socket. There are two main approaches that people have used to do two things at once: threads, and event-driven programming. We can talk about either in more detail if you want. > I also have one computer as the server and another as the client.... can > I have a dedicated server program that handles two clients instead of > having a direct connect? If you have any examples please send them too > me.. it would be very much appreciated!! Yes, check Section 5 in the Socket HOWTO on "Non-blocking Sockets": http://www.amk.ca/python/howto/sockets/ They mention 'select', which is at the heart of doing an event-driven socket program. The idea is to pass control off to 'select()', and it'll tell you whenever something's ready for processing, be it text from the user or text from your network socket. Here are a few thread tutorials: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python http://linuxgazette.net/107/pai.html http://starship.python.net/crew/aahz/IPC9/index.html Finally, if you're really getting into socket programming, you may want to consider looking into the Twisted framework: http://twistedmatrix.com/projects/twisted/ http://twistedmatrix.com/projects/twisted/documentation/howto/index.html because the Twisted folks have done a lot of framework-building to simplify socket programming issues. On the downside, this means learning Twisted. But on the upside, this isn't as bad as it sounds. *grin* Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 05:26:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 Aug 2005 20:26:13 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: On Wed, 3 Aug 2005, Nathan Pinno wrote: > I added a plus sign to show Python to add "\n" or a new line to end of > the file. Ok, better. So the plus sign was necessary in between: sitelist[site][1] and "\n" in order to glue them together into one string. Just for kicks, let's look at another example of a SyntaxError: ###### >>> def square(x): ... return x * x ... >>> >>> square 42 File "", line 1 square 42 ^ SyntaxError: invalid syntax ###### The problematic line: square 42 is invalid syntax in the Python language. (Off-topic tangent: it might not be necessarily one in a different programming language.) We know what the problem is: we're missing parens, and in an magical ideal world, Python would also recognize what we meant, and would say something like: SyntaxError: you're missing parentheses when you're trying to call the function. Try square(42) instead. But too bad Python's error message aren't as helpful. *grin* The best that Python can do, though, is say: SyntaxError: invalid syntax which is sad, but oh well. But at least Python says that there's a problem, and points at the '42' to say "I didn't expect that there. Can you check around that area?" which is usually enough of a hint. I guess I'm trying to say: whenever you see a SyntaxError and apply a fix to it, also take a retrospective moment to also think about what you can do next time to avoid it, or how to recognize it if it shows its ugly head again. Best of wishes! From shitizb at yahoo.com Thu Aug 4 06:44:09 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed, 3 Aug 2005 21:44:09 -0700 (PDT) Subject: [Tutor] Web Browser in Python In-Reply-To: <42F0C2CF.9070703@tds.net> Message-ID: <20050804044410.73325.qmail@web53809.mail.yahoo.com> Hi, I actually want to create a web-browser on my own. There are so many changes i would like to see in my browser that i felt that i would be better of creating my own rather than trying to modify the existing ones.As for the size of project, I have been pursuing programming as a hobby for years and really enjoy it.I dont have any specific timeframe or deadline in mind so the size doesnt matter :). Cheers, Shitiz Kent Johnson wrote: R. Alan Monroe wrote: >>>I need to program a web browser in python.I dont have any idea of how to >>>start, what i do have is time and willingness to learn.Could anyone direct >>>me to some suitable reference? >>>Shitiz >>> > > >>How about Grail http://grail.sourceforge.net/ ? > > > Looks neat, but it doesn't run on my box: Grail is pretty much dead, I think. If you look at the checkin mailing list the last activity was in 2001. If you really want to write a web browser it might be a good starting point though. wxPython has an HTML widget that could also be a starting point. I hope you realize that creating a browser on the scale of Firefox or IE is a massive and difficult project. Is that your goal or did you have something more modest in mind? Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Start your day with Yahoo! - make it your home page -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050803/c7f96643/attachment.htm From falcon3166 at hotmail.com Thu Aug 4 06:47:55 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 3 Aug 2005 22:47:55 -0600 Subject: [Tutor] How do I fix the following error? Code and error message supplied. References: Message-ID: Hey Danny and all, Alan's tutorial did help me, and showed me how to correctly load a file upon entry, and save upon exit. It should be smooth sailing from here on it. Thank again, Nathan --- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 8:45 PM Subject: Re: [Tutor] How do I fix the following error? Code and error message supplied. > > > On Wed, 3 Aug 2005, Nathan Pinno wrote: > >> Traceback (most recent call last): >> File "D:\Python24\password.py", line 82, in -toplevel- >> load_file(sitelist,filename) >> File "D:\Python24\password.py", line 51, in load_file >> [site,ID,passcard] = string.split(in_line,",") >> File "D:\Python24\lib\string.py", line 292, in split >> return s.split(sep, maxsplit) >> AttributeError: 'list' object has no attribute 'split' > > > Hi Nathan, > > Let's pay attention to the line 51 in your file: > >> [site,ID,passcard] = string.split(in_line,",") > > string.split() will fail if it is being given a set of arguments that it > doesn't understand. string.split() works only if in_line is a string. > > > But in the function load_file(), in_line is a list of strings. So there's > definitely a bug in load_file, in confusing the list of lines with a > particular single line. Actuallly, a lot of load_file() needs some > rework. > > > We strongly recommend you go through: > > http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm > > because the code that you're writing to handle the reading of files is > using a very old style of Python that hasn't been seen since the Python > 1.52 days; I suspect that you are learning from a very deprecated > tutorial! The approach that Alan takes in his "Learning How to Program" > tutorial uses a more modern, less bug-prone style of reading files. > > From alan.gauld at freenet.co.uk Thu Aug 4 09:05:27 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 4 Aug 2005 08:05:27 +0100 Subject: [Tutor] How do I fix the following error? Code and error messagesupplied. References: Message-ID: <089701c598c2$e4d5c760$8eaa8651@xp> > How do I fix the following error: Traceback (most recent call last): File "D:\Python24\password.py", line 51, in load_file [site,ID,passcard] = string.split(in_line,",") File "D:\Python24\lib\string.py", line 292, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' So it tells us that s is a list which has no split attribute. Looking at the line in your code that suggests that in_line is a list. def load_file(sitelist,filename): in_file = open(filename,"r") while 1: in_line = in_file.readlines() And so it is, readlines returns all of the lines in the file as a list. if in_line == "": break BTW The above section of code would be much easier if you used a for loop: for line in in_file: that's it, that's all you need to process each line of the file in turn. in_line = in_line[:-1] This strange line returns a list containing the last line of the file. The rest of the file having been thrown away! But its still a list. [site,ID,passcard] = string.split(in_line,",") So we get a problem here. sitelist[site] = sitelist You need to convert in_line to a string. (Or more exactly extract the string from within in_line). The answer to most of your questions is given inthe error messages Nathan, just look at what it tells you and the approximate location of the error in your code. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Aug 4 09:22:49 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 4 Aug 2005 08:22:49 +0100 Subject: [Tutor] Web Browser in Python References: <20050804044410.73325.qmail@web53809.mail.yahoo.com> Message-ID: <08d601c598c5$51fe0b70$8eaa8651@xp> > As for the size of project, I have been pursuing programming as > a hobby for years and really enjoy it.I dont have any specific > timeframe or deadline in mind so the size doesnt matter :). In that case go to it! :-) But you might like to consider using wxPython because as someone else mentined it does at least have an HTML rendering control to start from, I assume you don't really want to have to write a complete rendering engine too?! Although if you do at least Python has its HTMLparser module to help... Alan g From davholla2002 at yahoo.co.uk Thu Aug 4 14:43:28 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 4 Aug 2005 13:43:28 +0100 (BST) Subject: [Tutor] Extract information from an HTML table In-Reply-To: Message-ID: <20050804124328.78879.qmail@web25408.mail.ukl.yahoo.com> Danny, Thanks for that I will give a go and see how it works. David --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050804/e3c7c83e/attachment.htm From reed at intersiege.com Thu Aug 4 17:46:08 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Thu, 04 Aug 2005 11:46:08 -0400 Subject: [Tutor] removal In-Reply-To: <42F14DA3.4080705@cpinternet.com> References: <42F14DA3.4080705@cpinternet.com> Message-ID: <42F23840.5050203@intersiege.com> Roger Sell wrote: >Please remove from the Tutor recipient list. > >Thanks, > >Roger Sell > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Unsubscribe yourself. Don't be lazy. You got on , you can get off. Hint try the link that comes with ****each and every**** email... ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From davholla2002 at yahoo.co.uk Thu Aug 4 19:08:29 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 4 Aug 2005 18:08:29 +0100 (BST) Subject: [Tutor] Getting web pages and formatting text Message-ID: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> I am trying to make a report I do easier (ie via a program not manually). Two questions :- 1) Is it possible to download to your hard drive using python various web pages ie if the pages have the structure http://address/node=xxx&pagretree=&fromdid=nx&objectid=ny So you can download objectid=ny where ny=1,2,3,4 etc up to 20 for example 2) Is it possible to use python to put text into a table I don't mean an sql table I mean a text table. When/if I get this to work I will show the results of my effort. Thanks in advance David --------------------------------- How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos. Get Yahoo! Photos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050804/1ca4fce9/attachment.htm From falcon3166 at hotmail.com Thu Aug 4 19:31:47 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 4 Aug 2005 11:31:47 -0600 Subject: [Tutor] How do I fix the following error? Code and errormessage supplied. References: Message-ID: Thank you to all. The Password Program works perfectly. Time for me to relax and finish up my other loose project ends, and then I'll be able to start another major project. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: "Tutor mailing list" Sent: Wednesday, August 03, 2005 10:47 PM Subject: Re: [Tutor] How do I fix the following error? Code and errormessage supplied. > Hey Danny and all, > > Alan's tutorial did help me, and showed me how to correctly load a file > upon > entry, and save upon exit. It should be smooth sailing from here on it. > > Thank again, > Nathan > --- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Wednesday, August 03, 2005 8:45 PM > Subject: Re: [Tutor] How do I fix the following error? Code and error > message supplied. > > >> >> >> On Wed, 3 Aug 2005, Nathan Pinno wrote: >> >>> Traceback (most recent call last): >>> File "D:\Python24\password.py", line 82, in -toplevel- >>> load_file(sitelist,filename) >>> File "D:\Python24\password.py", line 51, in load_file >>> [site,ID,passcard] = string.split(in_line,",") >>> File "D:\Python24\lib\string.py", line 292, in split >>> return s.split(sep, maxsplit) >>> AttributeError: 'list' object has no attribute 'split' >> >> >> Hi Nathan, >> >> Let's pay attention to the line 51 in your file: >> >>> [site,ID,passcard] = string.split(in_line,",") >> >> string.split() will fail if it is being given a set of arguments that it >> doesn't understand. string.split() works only if in_line is a string. >> >> >> But in the function load_file(), in_line is a list of strings. So >> there's >> definitely a bug in load_file, in confusing the list of lines with a >> particular single line. Actuallly, a lot of load_file() needs some >> rework. >> >> >> We strongly recommend you go through: >> >> http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm >> >> because the code that you're writing to handle the reading of files is >> using a very old style of Python that hasn't been seen since the Python >> 1.52 days; I suspect that you are learning from a very deprecated >> tutorial! The approach that Alan takes in his "Learning How to Program" >> tutorial uses a more modern, less bug-prone style of reading files. >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Aug 4 19:33:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Aug 2005 13:33:55 -0400 Subject: [Tutor] Getting web pages and formatting text In-Reply-To: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> References: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <42F25183.5050900@tds.net> David Holland wrote: > I am trying to make a report I do easier (ie via a program not manually). > Two questions :- > 1) Is it possible to download to your hard drive using python various > web pages ie if the pages have the structure > http://address/node=xxx&pagretree=&fromdid=nx&objectid=ny > > So you can download objectid=ny where ny=1,2,3,4 etc up to 20 for example Sure, just use urllib.urlretrieve(), or, if you need to deal with things like proxies and authentication, urllib2. > 2) Is it possible to use python to put text into a table I don't mean > an sql table I mean a text table. There is a nice recipe in the online Python Cookbook for formatting tabular data. Unfortunately I can't access the cookbook right now; try searching for 'table' at http://aspn.activestate.com/ASPN/Cookbook/Python Kent From srini_iyyer_bio at yahoo.com Thu Aug 4 19:34:00 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 4 Aug 2005 10:34:00 -0700 (PDT) Subject: [Tutor] a dictionary method good for this process In-Reply-To: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <20050804173400.96062.qmail@web53507.mail.yahoo.com> Dear group: I have two lists and I have to match the element in the first list to element in second list and print the line from second list: Example: listA =['apple','baby','cat'] listB =['fruit\tapple','tree\tapple','fruit\tmango', 'human\tbaby' 'infant\tbaby' 'human\tAlbert' 'animal\tcat' 'tiger\tcat' 'animan\tdog'] I have to take apple, search in listB and print fruit apple tree apple infant baby human baby animal cat tiger cat I am doing it this way: for i in listA: for m in listB: cols = m.split('\t') term = cols[2] if i == term: print m this is very time consuming. Because the two columns in listB are redundant I am unable to do a dict method. The other way could be using a reg.ex method (which I did not try yet because the script written based on equality is still running. for i in listA: pat = re.compile(i) for m in listB: cols = m.split('\t') terms = cols[1] if pat.match(terms): print m Experts, could you please suggest any other method which is fast and does the job correctly. Thank you. Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Thu Aug 4 20:01:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Aug 2005 14:01:41 -0400 Subject: [Tutor] a dictionary method good for this process In-Reply-To: <20050804173400.96062.qmail@web53507.mail.yahoo.com> References: <20050804173400.96062.qmail@web53507.mail.yahoo.com> Message-ID: <42F25805.5020904@tds.net> Srinivas Iyyer wrote: > Dear group: > > I have two lists and I have to match the element in > the first list to element in second list and print the > line from second list: > > Example: > listA =['apple','baby','cat'] > listB =['fruit\tapple','tree\tapple','fruit\tmango', > 'human\tbaby' > 'infant\tbaby' > 'human\tAlbert' > 'animal\tcat' > 'tiger\tcat' > 'animan\tdog'] > > > I have to take apple, search in listB and print > > fruit apple > tree apple > infant baby > human baby > animal cat > tiger cat Presumably that is the results from searching for 'apple', 'baby' and 'cat'... I would make a helper dictionary that maps from the second element in listB to a list of listB entries containing that element. This way you make just one pass over listB: listA =['apple','baby','cat'] listB =['fruit\tapple','tree\tapple','fruit\tmango', 'human\tbaby', 'infant\tbaby', 'human\tAlbert', 'animal\tcat', 'tiger\tcat', 'animan\tdog'] # Make a helper dict that maps the second element of listB to a list of elements d={} for m in listB: cols = m.split('\t') term = cols[1] d.setdefault(term, []).append(m) for i in listA: items = d.get(i) for item in items: print item The only tricky part is the line d.setdefault(term, []).append(m) This is just a shortcut for something like try: data = d[term] except KeyError: d[term] = data = [] data.append(m) Kent > > > I am doing it this way: > > for i in listA: > for m in listB: > cols = m.split('\t') > term = cols[2] > if i == term: > print m > > this is very time consuming. > > Because the two columns in listB are redundant I am > unable to do a dict method. > > The other way could be using a reg.ex method (which I > did not try yet because the script written based on > equality is still running. > > for i in listA: > pat = re.compile(i) > for m in listB: > cols = m.split('\t') > terms = cols[1] > if pat.match(terms): > print m > > Experts, could you please suggest any other method > which is fast and does the job correctly. > > Thank you. > > Srini > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tegmine at gmail.com Thu Aug 4 20:42:23 2005 From: tegmine at gmail.com (Luis N) Date: Thu, 4 Aug 2005 11:42:23 -0700 Subject: [Tutor] [Metakit] Mk4py In-Reply-To: References: <77bfa81a0508020136518e7734@mail.gmail.com> <77bfa81a05080300294eaba568@mail.gmail.com> <42F0B7AA.5050407@harvee.org> Message-ID: <77bfa81a050804114276c28fed@mail.gmail.com> On 8/4/05, Brian Kelley wrote: > Yeah the spaces kill me as well sometimes, and then I think that the > spaces are okay sometimes. > > The real issue is that a metakit column name can include any printable > character except a comma ",". > > So, now you know :) > > Here is another gotcha for you. Never, ever delete a column and then > add a column with the same name and a different type. This will drive > you bananas, I guarantee. > > To safely do this, delete the column, write out the db to a new file. > delete the database, repoen it and then add the new column. > > At some point I had an enhanced python metakit tutorial, but I just > noticed that it was gone. I'll dig it up and repost it on my new web > site. > > Brian Thanks for the warning, I had downloaded your tutorial in http://www.equi4.com/pipermail/metakit/2003-March/001091.html , which helped me get started, and is still relevant as I better understand metakit. Luis. From John.Gooch at echostar.com Thu Aug 4 21:07:05 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Thu, 4 Aug 2005 13:07:05 -0600 Subject: [Tutor] ASP And Python - Calling Python Scripts from within the web page Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D5DA@riv-excha5.echostar.com> I have basic Python functions working within ASP pages, but I am having problems passing arguments to python scripts when they are called. Here is what I have so far: --------------------------------- <%@ Language = Python%> <% import os import sys sys.path.append("d:/batch2000") import chgpwd_enq import chgpwd def initialize(): global arUserNames global strUserNames arUserNames = Request.QueryString("u") strUserNames = ",".join(arUserNames) return None def main(): try: error = initialize() if ( not error ): #transid = Server.Execute( "d:\batch2000\chgpwd_enq.py -u " & strUserNames ) for name in arUserNames: Response.write( name + "
" ) except Exception,error: Response.write( "Error Occured." + str(error)) sys.argv = [ 'junk', '-u jgooch.admin' ] #os.system( "d:/python/python.exe d:/batch2000/chgpwd_enq.py -u jgooch.test" ) transid = chgpwd_enq.main() # enqueue users and get the transaction id Response.write( "Transactionid=" + str(transid) + "
" ) return 0 main() ------------------------------------------ Transaction ID is None. If I run the "chgpwd_enq.py" script in a command window, it works fine. But it is not doing anything when run as from the ASP page. I am guessing that the sys.argv is not working as intended, but it is hard to tell as I am not getting any response from the called Python script. Any ideas? From dyoo at hkn.eecs.berkeley.edu Thu Aug 4 21:49:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 Aug 2005 12:49:56 -0700 (PDT) Subject: [Tutor] ASP And Python - Calling Python Scripts from within the web page In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D5DA@riv-excha5.echostar.com> Message-ID: > sys.argv = [ 'junk', '-u jgooch.admin' ] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Hi John, The code highlighted above looks unusual. Can you explain why the code assigns to sys.argv? Ah, ok, I assume that you're trying to pass state with the 'chgpwd_enq' program: > transid = chgpwd_enq.main() If so, you may want to do this more directly, by modifying chgpwd_enq.main() to take in arguments. For example, something like this: chgpwd_enq.main('junk', user='jgooch.admin') Using sys.argv to pass state between the two Python programs is slightly weird because there are easier mechanisms such as direct parameter passing between functions. > Transaction ID is None. If I run the "chgpwd_enq.py" script in a command > window, it works fine. But it is not doing anything when run as from the > ASP page. > > I am guessing that the sys.argv is not working as intended, but it is > hard to tell as I am not getting any response from the called Python > script. The bug here is that sys.argv should contain three arguments: sys.argv = [ 'junk', '-u', 'jgooch.admin' ] But even so, the whole mechanism of passing state between the ASP page and the chgpwd_enq program with sys.argv sounds weird: it may be more direct to call chgpwd_enq.main() with those arguments instead. Good luck! From bgailer at sbcglobal.net Thu Aug 4 22:04:50 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Thu, 04 Aug 2005 13:04:50 -0700 Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: References: <6.1.2.0.0.20050803183953.034665b0@pop.sbcglobal.yahoo.com> Message-ID: <6.1.2.0.0.20050804125904.030e89b8@pop.sbcglobal.yahoo.com> At 06:51 PM 8/3/2005, Nathan Pinno wrote: >That's part of my signature. It describes who I am. I would like to know who you are, but the signature does not convey enough information. My guess is that you are on the crew of a MacDonald's restaurant in Camrose, Alberta (thanks to Google) but what is "Woffee"? Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050804/049970c7/attachment.htm From jeffpeery at yahoo.com Thu Aug 4 22:43:20 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 4 Aug 2005 13:43:20 -0700 (PDT) Subject: [Tutor] fftpack Message-ID: <20050804204320.66723.qmail@web30508.mail.mud.yahoo.com> Hello, does anyone know how to open the fft function? I want to view it in the IDLE although the only file i have is the fftpack.pyd which I beleive is a compiled file and it looks like mush. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050804/c59e24fe/attachment.htm From jeffpeery at yahoo.com Thu Aug 4 22:48:31 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 4 Aug 2005 13:48:31 -0700 (PDT) Subject: [Tutor] fyi - re: fft Message-ID: <20050804204831.67921.qmail@web30508.mail.mud.yahoo.com> hello, thought I'd post my progress with fiddling with the FFT. import FFT I've been using fft by taking the real part with: myFFT = abs(FFT.fft()) the returned values are the fourier coefficients starting with a0 the old thing is that the output is symmetrical about N/2 where n>N/2 is the negative frequencies. also all outputs are multiplied by N, so to get anything meaningful (at least in my case) you must divide the output by N. so to get a0 you want myFFT[0]/float(N). I compared several inputs with the output and I also used the output to calculate the fourier series and it all looks like it should. thanks for those that had input. Jeff thats all I got. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050804/a7e95cda/attachment.htm From alan.gauld at freenet.co.uk Thu Aug 4 23:01:14 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 4 Aug 2005 22:01:14 +0100 Subject: [Tutor] Getting web pages and formatting text References: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <002801c59937$a673dff0$ab8e8651@xp> > Two questions :- > 1) Is it possible to download to your hard drive using python > various web pages ie if the pages have the structure > http://address/node=xxx&pagretree=&fromdid=nx&objectid=ny YEs, look at the urlib module documentation. > 2) Is it possible to use python to put text into a table I don't > mean an sql table I mean a text table. An HTML table sure, otherwise its a formatted text string - using tabs probably. If you mean a table as in MS Word - with lines and bold headers etc - then thats a whole heap harder. HTML is my preferred option there. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Aug 4 23:05:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Aug 2005 17:05:22 -0400 Subject: [Tutor] fftpack In-Reply-To: <20050804204320.66723.qmail@web30508.mail.mud.yahoo.com> References: <20050804204320.66723.qmail@web30508.mail.mud.yahoo.com> Message-ID: <42F28312.5010206@tds.net> Jeff Peery wrote: > Hello, does anyone know how to open the fft function? I want to view it > in the IDLE although the only file i have is the fftpack.pyd which I > beleive is a compiled file and it looks like mush. It is compiled from C. The comment in fft.py says, "The underlying code for these functions is an f2c translated and modified version of the FFTPACK routines." f2c is FORTRAN to C. So you will have to look at the source for Numeric or numarry to find the source for fftpack. For Numeric you can look here: http://www.scipy.org/cvs/viewcvs/map?rmurl=http%3A//scipy.net/cgi-bin/viewcvsx.cgi/scipy/Lib/fftpack/ which seems to have the fortran files. Kent From alan.gauld at freenet.co.uk Thu Aug 4 23:04:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 4 Aug 2005 22:04:43 +0100 Subject: [Tutor] How do I fix the following error? Code and errormessagesupplied. References: Message-ID: <002e01c59938$24dbf3a0$ab8e8651@xp> > Thank you to all. The Password Program works perfectly. Time for me > to relax > and finish up my other loose project ends, and then I'll be able to > start another major project. That's great Nathan. Maybe now would be a good time to revisit some of the tutorials to pick up some of the basic concepts more thoroughly now that you;ve put them into practice. Programming is like driving, if you get into good habits early it makes for a better programmer later. Many of the questions you've been asking are answered in the tutorials, along with a lot more besides. A few hours spent now might save a lot of time later. Well done in getting password finished though. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Aug 4 23:16:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Aug 2005 17:16:02 -0400 Subject: [Tutor] Getting web pages and formatting text In-Reply-To: <42F25183.5050900@tds.net> References: <20050804170829.54107.qmail@web25402.mail.ukl.yahoo.com> <42F25183.5050900@tds.net> Message-ID: <42F28592.6000602@tds.net> Kent Johnson wrote: > There is a nice recipe in the online Python Cookbook for formatting > tabular data. Here it is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent From carroll at tjc.com Fri Aug 5 00:26:32 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 4 Aug 2005 15:26:32 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: <6.1.2.0.0.20050804125904.030e89b8@pop.sbcglobal.yahoo.com> Message-ID: On Thu, 4 Aug 2005, Bob Gailer wrote: > At 06:51 PM 8/3/2005, Nathan Pinno wrote: > >That's part of my signature. It describes who I am. > > I would like to know who you are, but the signature does not convey enough > information. My guess is that you are on the crew of a MacDonald's > restaurant in Camrose, Alberta (thanks to Google) but what is "Woffee"? See, I figured he worked at the accounting firm of Crew Camrose McDonalds. :-) From andre.roberge at gmail.com Fri Aug 5 04:40:03 2005 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 4 Aug 2005 23:40:03 -0300 Subject: [Tutor] imbedding python into another program? In-Reply-To: <20050803190405.92453.qmail@web30515.mail.mud.yahoo.com> References: <20050803190405.92453.qmail@web30515.mail.mud.yahoo.com> Message-ID: <7528bcdd050804194055d682f4@mail.gmail.com> On 8/3/05, Jeff Peery wrote: > Andre, thanks for the help with this. I put it to work yesterday and it > works perfectly. > > was wondering if it is possible to import modules without a users having to > type 'import whatever'. for example in my application I would like the user > to just start operating on arrays that exist in my program. But I have to > load both the arrays and Numeric into the python shell that I created. how > can I do this? thanks. > > Andr? Roberge wrote: > Jeff Peery wrote: > > hello, is it possible to add something like the python IDLE into > > another program, say if I wanted to simply run scripts from within a > > wxPython program? Could someone point me to the correct reference? > > thanks. > > > Hi Jeff, > > you may want to have a look at PyCrust, PyShell and the like. > I do something like this in my rur-ple app (on sourceforge). > > The relevant lines of code are: > > import wx.py as py > > [inside a wx.Notebook] > win = py.shell.Shell(self.window, -1, > introText = tr.INTERPRETER_INTRO_TEXT) > self.window.AddPage(win, tr.PYTHON_INTERPRETER) > ============ Just use "push". Here's how I did a similar automatic import in that same program: win = py.shell.Shell(self.window, -1, introText = tr.INTERPRETER_INTRO_TEXT) cmd = "from __future__ import division" # so that 1/2 = 0.5 [irrelevant stuff deleted] win.push(cmd) HTH, Andr? From davholla2002 at yahoo.co.uk Fri Aug 5 10:02:33 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri, 5 Aug 2005 09:02:33 +0100 (BST) Subject: [Tutor] Getting web pages and formatting text In-Reply-To: <002801c59937$a673dff0$ab8e8651@xp> Message-ID: <20050805080234.23991.qmail@web25403.mail.ukl.yahoo.com> Alan, Kent, Thanks for that I will have a look and hopefully come back with a complete script next week. David Alan G wrote: > Two questions :- > 1) Is it possible to download to your hard drive using python > various web pages ie if the pages have the structure > http://address/node=xxx&pagretree=&fromdid=nx&objectid=ny YEs, look at the urlib module documentation. > 2) Is it possible to use python to put text into a table I don't > mean an sql table I mean a text table. An HTML table sure, otherwise its a formatted text string - using tabs probably. If you mean a table as in MS Word - with lines and bold headers etc - then thats a whole heap harder. HTML is my preferred option there. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050805/9fdec805/attachment-0001.htm From lonetwin at gmail.com Fri Aug 5 16:13:20 2005 From: lonetwin at gmail.com (Steve) Date: Fri, 5 Aug 2005 19:43:20 +0530 Subject: [Tutor] An editable buffer for the Python shell (similar to '\e' on sql prompts) Message-ID: <5a309bd305080507132e1cba43@mail.gmail.com> Hi, When working in the python command shell, I often end up writing more than 10+ lines of indented code before making a stupid typo. This got irritating enough for me to do something about it. So, here's an 'InteractiveConsole with an editable buffer'. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438813 Just thought some one else also would find this useful. Regards Steve From falcon3166 at hotmail.com Fri Aug 5 19:14:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 5 Aug 2005 11:14:28 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: Hi all, It's Zoffee now, thanks to a Google search. Don't want to confuse customers. :) For your info, Zoffee is a company where I sell computer programs online which I write. Simple enough, eh? G2G, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Zoffee ----- Original Message ----- From: "Terry Carroll" To: "Tutor mailing list" Sent: Thursday, August 04, 2005 4:26 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > On Thu, 4 Aug 2005, Bob Gailer wrote: > >> At 06:51 PM 8/3/2005, Nathan Pinno wrote: >> >That's part of my signature. It describes who I am. >> >> I would like to know who you are, but the signature does not convey >> enough >> information. My guess is that you are on the crew of a MacDonald's >> restaurant in Camrose, Alberta (thanks to Google) but what is "Woffee"? > > See, I figured he worked at the accounting firm of Crew Camrose McDonalds. > :-) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From surangasa at gmail.com Fri Aug 5 10:48:48 2005 From: surangasa at gmail.com (surangasa@gmail.com) Date: Fri, 5 Aug 2005 11:48:48 +0300 Subject: [Tutor] The new iMesh Message-ID: <200508050848.j758mmm27465@www.imesh.com> tutor at python.org, I'd like to invite you to try the new iMesh! iMesh 5 lets you search and download music, videos, images and more. The Professional version is now FREE. It's also 100% clean. NO POPUPS, NO SPYWARE and NO ADWARE. iMesh 5 lets you connect to multiple file sharing networks - iMesh, Kazaa, Limewire and more so you get the most results and super charged download speeds. Get it now, for free, at Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050805/4ad7b020/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 1762 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050805/4ad7b020/attachment.gif -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 3427 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050805/4ad7b020/attachment-0001.gif -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 1396 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050805/4ad7b020/attachment-0002.gif From cpu.crazy at gmail.com Fri Aug 5 17:55:09 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Fri, 05 Aug 2005 09:55:09 -0600 Subject: [Tutor] IP Address from Python module? Message-ID: <42F38BDD.2030505@gmail.com> Is it possible to get my internet and/or network IP address from Python? Is there any other way to get it? Oh. If you're wondering what I mean by Internet and/or network IP I'm talking about the 4 sequence IP (IPv4) (used primarily in small networks) and the 6 sequence IP (IPv6) found on the internet. Thanks, Joe From falcon3166 at hotmail.com Fri Aug 5 21:43:25 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 5 Aug 2005 13:43:25 -0600 Subject: [Tutor] Is there a qucker method than the following? Message-ID: Hi all, Is there a quicker method than the following? import random numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12] cards = ["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"] hand = {numbers:cards} def menu(): print "1. Deal a hand" print "2. Exit" def option(): return int(raw_input("Option: ")) def deal(): a,b,c,d,e = random.choice(13) print "The Five Card Dealer" print "By Nathan Pinno" while 1: menu() opt = option() while opt == 1: if a == 1: a = hand[0] if a == 2: a = hand[1] etc.. while opt == 2: break print "Goodbye." Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050805/650b3cc7/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050805/650b3cc7/PinnoNathanPaul.vcf From tegmine at gmail.com Fri Aug 5 21:54:37 2005 From: tegmine at gmail.com (Luis N) Date: Fri, 5 Aug 2005 12:54:37 -0700 Subject: [Tutor] Is there a qucker method than the following? In-Reply-To: References: Message-ID: <77bfa81a05080512549d763b5@mail.gmail.com> On 8/5/05, Nathan Pinno wrote: > > Hi all, > > Is there a quicker method than the following? > > import random > numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12] > cards = > ["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"] > hand = {numbers:cards} > hand is invalid syntax, list objects are unhashable. deal() is also invalid syntax, and will throw a type error. Fixing these might show you a way to do things quicker. List comprehensions might be useful to you in this context. Luis. From 3dbernard at gmail.com Fri Aug 5 22:14:44 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 5 Aug 2005 16:14:44 -0400 Subject: [Tutor] Functional question Message-ID: <61d0e2b405080513146fdf85ce@mail.gmail.com> Hello, This question is not strictly bound to Python, but rather some functional programming problem, I hope someone can help me or suggest ressources. 1 -- I have a list of lists. Each of these lists has 3 elements: a string, and two integers. Thoughout the lists, there are only two different integers for the first one, and two different for the second one. aLists = [ [ 'Pass1', 10, 200 ], [ 'Pass2', 10, 200 ], [ 'Pass3', 25, 100 ], [ 'Pass4', 10, 100 ], [ 'Pass5', 25, 200 ] ] 2 -- Then I want to regroup the strings into two dictionaries. The first dictionaries is for the strings that have the same first integer, and the second dictionay is for the strings that have the same second integer. dMap1 = {} dMap2 = {} # Iterate lists for aList in aLists: sPass = aList[0] iValue1 = aList[1] iValue2 = aPList[2] # Map pass name to integers dMap1.setdefault( iValue1, [] ).append( sPass ) dMap2.setdefault( iValue2, [] ).append( sPass ) So far so good, it's working, I end up with this structure: dMap1 = { 10 : [ 'Pass1', 'Pass2', 'Pass4' ], 25 : [ 'Pass3', 'Pass5' ] } dMap2 = { 100 : [ 'Pass3', 'Pass4' ], 200 : [ 'Pass1', 'Pass2', 'Pass5' ] } 3 -- This is where I'm completely stump. I want to consolidate the strings into another dictionary the strings that share the same integers, resulting in such a structure: dGroups = { 'group0' : [ 'Pass1', 'Pass2' ], # 10, 200 'group1' : [ 'Pass4' ], # 10, 100 'group2' : [ 'Pass3' ], # 25, 100 'group3' : [ 'Pass5' ], # 25, 200 } However, I have absolutely no idea how to achieve that third dictionary! Thanks Bernard From kent37 at tds.net Fri Aug 5 22:32:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 05 Aug 2005 16:32:08 -0400 Subject: [Tutor] Functional question In-Reply-To: <61d0e2b405080513146fdf85ce@mail.gmail.com> References: <61d0e2b405080513146fdf85ce@mail.gmail.com> Message-ID: <42F3CCC8.6000507@tds.net> Bernard Lebel wrote: > Hello, > > This question is not strictly bound to Python, but rather some > functional programming problem, I hope someone can help me or suggest > ressources. > > 1 -- > I have a list of lists. Each of these lists has 3 elements: a string, > and two integers. Thoughout the lists, there are only two different > integers for the first one, and two different for the second one. > > aLists = [ > [ 'Pass1', 10, 200 ], > [ 'Pass2', 10, 200 ], > [ 'Pass3', 25, 100 ], > [ 'Pass4', 10, 100 ], > [ 'Pass5', 25, 200 ] ] > > > > 2 -- > Then I want to regroup the strings into two dictionaries. The first > dictionaries is for the strings that have the same first integer, and > the second dictionay is for the strings that have the same second > integer. > > dMap1 = {} > dMap2 = {} > > # Iterate lists > for aList in aLists: > > sPass = aList[0] > iValue1 = aList[1] > iValue2 = aPList[2] > > # Map pass name to integers > dMap1.setdefault( iValue1, [] ).append( sPass ) > dMap2.setdefault( iValue2, [] ).append( sPass ) If I understand you correctly, you want to group the strings that have both integers the same. Just use the tuple (iValue1, iValue2) as the key in a third dictionary: dmap3.setdefault( (iValue1, iValue2), [] ).append( sPass ) Kent > So far so good, it's working, I end up with this structure: > > dMap1 = { > 10 : [ 'Pass1', 'Pass2', 'Pass4' ], > 25 : [ 'Pass3', 'Pass5' ] } > > dMap2 = { > 100 : [ 'Pass3', 'Pass4' ], > 200 : [ 'Pass1', 'Pass2', 'Pass5' ] } > > > 3 -- > This is where I'm completely stump. > I want to consolidate the strings into another dictionary the strings > that share the same integers, resulting in such a structure: > > dGroups = { > 'group0' : [ 'Pass1', 'Pass2' ], # 10, 200 > 'group1' : [ 'Pass4' ], # 10, 100 > 'group2' : [ 'Pass3' ], # 25, 100 > 'group3' : [ 'Pass5' ], # 25, 200 } > > However, I have absolutely no idea how to achieve that third dictionary! > > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Fri Aug 5 22:56:44 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 5 Aug 2005 14:56:44 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied Message-ID: Hi all, What's the invalid syntax? Here is the code: import random hand = { '0' : ["Ace"] '1' : ["Two"] '2' : ["Three"] '3' : ["Four"] '4' : ["Five"] '5' : ["Six"] '6' : ["Seven"] '7' : ["Eight"] '8' : ["Nine"] '9' : ["Ten"] '10' : ["Jack"] '11' : ["Queen"] '12' : ["King"] } types = { '0' : ["Diamonds"] '1' : ["Hearts"] '2' : ["Spades"] '3' : ["Clubs"] } playercards = [a,b,c,d,e] t = [t1,t2,t3,t4,t5] def menu(): print "1. Deal a hand" print "2. Exit" def option(): return int(raw_input("Option: ")) def deal(): playercards = random.choice(13) t = random.choice(4) print "The Five Card Dealer" print "By Nathan Pinno" while 1: menu() opt = option() while opt == 1: deal() for index in range(len(playercards)): if index == 0: index = hand['0'] if index == 1: index = hand['1'] if index == 2: index = hand['2'] if index == 3: index = hand['3'] if index == 4: index = hand['4'] if index == 5: index = hand['5'] if index == 6: index = hand['6'] if index == 7: index = hand['7'] if index == 8: index = hand['8'] if index == 9: index = hand['9'] if index == 10: index = hand['10'] if index == 11: index = hand['11'] if index == 12: index = hand['12'] for indice in range(len(t)): if indice == 0: indice = types['0'] if indice == 1: indice = types['1'] if indice == 2: indice = types['2'] if indice == 3: indice = types['3'] print a," of ",t1, b," of ",t2, c," of ",t3, d," of ",t4, e," of ",t5 while opt == 2: break print "Goodbye." If it helps it highlighted the ' after 1 in the hand dictionary. Thanks, Nathan Pinno, Crew, Camrose McDonalds and owner/operator of Zoffee -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050805/e288897b/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050805/e288897b/PinnoNathanPaul.vcf From dyoo at hkn.eecs.berkeley.edu Fri Aug 5 23:09:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 5 Aug 2005 14:09:45 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: > What's the invalid syntax? Here is the code: Hi Nathan, You need to have a comma between the items of a dictionary. For example: ###### >>> numerals = { ... 0 : 'zero', ... 1 : 'one', ... } >>> >>> numerals[0] 'zero' >>> numerals[1] 'one' ###### Some comments on your code. I notice that you're using strings as the keys of your dictionaries, as in: ###### types = { '0' : ["Diamonds"], '1' : ["Hearts"], '2' : ["Spades"], '3' : ["Clubs"], } ###### (with the comma bug corrected). However, you can use numbers as your keys, too, and this will greatly simpify some of the dictionary-selection code. For example: ###### if index == 0: index = hand['0'] if index == 1: index = hand['1'] if index == 2: index = hand['2'] if index == 3: index = hand['3'] if index == 4: index = hand['4'] ... ####### can be reduced from many statements to a single dictionary lookup statement. From dyoo at hkn.eecs.berkeley.edu Fri Aug 5 23:15:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 5 Aug 2005 14:15:02 -0700 (PDT) Subject: [Tutor] IP Address from Python module? In-Reply-To: <42F38BDD.2030505@gmail.com> Message-ID: On Fri, 5 Aug 2005, Joseph Quigley wrote: > Is it possible to get my internet and/or network IP address from Python? > Is there any other way to get it? Hi Joe, I think you're looking for socket.gethostbyname(). http://www.python.org/doc/lib/module-socket.html#l2h-2594 Here's an example using the socket.gethostbyname() function: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 From 3dbernard at gmail.com Fri Aug 5 23:29:50 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 5 Aug 2005 17:29:50 -0400 Subject: [Tutor] Functional question In-Reply-To: <42F3CCC8.6000507@tds.net> References: <61d0e2b405080513146fdf85ce@mail.gmail.com> <42F3CCC8.6000507@tds.net> Message-ID: <61d0e2b40508051429261822d6@mail.gmail.com> Thanks Kent. I had tried the very same thing, but with a list instead of a tuple, and got an got this: >>> dMap[ ['allo','bonjour'] ] = 'salut' Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable It never crossed my mind that a tuple would do it. Thanks again. Bernard On 8/5/05, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > This question is not strictly bound to Python, but rather some > > functional programming problem, I hope someone can help me or suggest > > ressources. > > > > 1 -- > > I have a list of lists. Each of these lists has 3 elements: a string, > > and two integers. Thoughout the lists, there are only two different > > integers for the first one, and two different for the second one. > > > > aLists = [ > > [ 'Pass1', 10, 200 ], > > [ 'Pass2', 10, 200 ], > > [ 'Pass3', 25, 100 ], > > [ 'Pass4', 10, 100 ], > > [ 'Pass5', 25, 200 ] ] > > > > > > > > 2 -- > > Then I want to regroup the strings into two dictionaries. The first > > dictionaries is for the strings that have the same first integer, and > > the second dictionay is for the strings that have the same second > > integer. > > > > dMap1 = {} > > dMap2 = {} > > > > # Iterate lists > > for aList in aLists: > > > > sPass = aList[0] > > iValue1 = aList[1] > > iValue2 = aPList[2] > > > > # Map pass name to integers > > dMap1.setdefault( iValue1, [] ).append( sPass ) > > dMap2.setdefault( iValue2, [] ).append( sPass ) > > If I understand you correctly, you want to group the strings that have both integers the same. Just use the tuple (iValue1, iValue2) as the key in a third dictionary: > dmap3.setdefault( (iValue1, iValue2), [] ).append( sPass ) > > Kent > > > So far so good, it's working, I end up with this structure: > > > > dMap1 = { > > 10 : [ 'Pass1', 'Pass2', 'Pass4' ], > > 25 : [ 'Pass3', 'Pass5' ] } > > > > dMap2 = { > > 100 : [ 'Pass3', 'Pass4' ], > > 200 : [ 'Pass1', 'Pass2', 'Pass5' ] } > > > > > > 3 -- > > This is where I'm completely stump. > > I want to consolidate the strings into another dictionary the strings > > that share the same integers, resulting in such a structure: > > > > dGroups = { > > 'group0' : [ 'Pass1', 'Pass2' ], # 10, 200 > > 'group1' : [ 'Pass4' ], # 10, 100 > > 'group2' : [ 'Pass3' ], # 25, 100 > > 'group3' : [ 'Pass5' ], # 25, 200 } > > > > However, I have absolutely no idea how to achieve that third dictionary! > > > > > > > > Thanks > > Bernard > > _______________________________________________ > > 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 carroll at tjc.com Sat Aug 6 01:40:08 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Aug 2005 16:40:08 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: Message-ID: On Fri, 5 Aug 2005, Nathan Pinno wrote: > What's the invalid syntax? Here is the code: Nathan, My method when encountering a syntax error like this is to look at the part of my code that's generating the syntax error, and see what structure or function it's using. Then find a program segment that does the same thing in a working program or tutorial. Now that I've written a good number of working programs, I can usually find working examples in my own programs, but if not, I hit a python book. I think you'll find this more efficient than simply posting the error message and code to the Tutor list and asking for help; save the Tutor list for the really challenging problems. You'll find you learn a lot more by taking a good whack at it yourself, first. In your case you've already indicated the error is in this code: > hand = { > '0' : ["Ace"] > '1' : ["Two"] > '2' : ["Three"] > '3' : ["Four"] > '4' : ["Five"] > '5' : ["Six"] > '6' : ["Seven"] > '7' : ["Eight"] > '8' : ["Nine"] > '9' : ["Ten"] > '10' : ["Jack"] > '11' : ["Queen"] > '12' : ["King"] > } You're trying to initialize a dictionary. So go find some examples of initializing a dictionary that work, compare them to your code, and see if you can see what's different about your code. Good luck! From carroll at tjc.com Sat Aug 6 01:51:14 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Aug 2005 16:51:14 -0700 (PDT) Subject: [Tutor] IP Address from Python module? In-Reply-To: <42F38BDD.2030505@gmail.com> Message-ID: On Fri, 5 Aug 2005, Joseph Quigley wrote: > Is it possible to get my internet and/or network IP address from Python? import socket ipaddr = socket.gethostbyname(socket.gethostname()) Some users report this gives a meaningless '127.0.0.1' (i.e., localhost), though. But try it and see. It works for me. From danf_1979 at yahoo.es Sat Aug 6 10:40:21 2005 From: danf_1979 at yahoo.es (_ Dan _) Date: Sat, 6 Aug 2005 10:40:21 +0200 (CEST) Subject: [Tutor] Get user input in wxpython In-Reply-To: Message-ID: <20050806084022.38284.qmail@web25202.mail.ukl.yahoo.com> Hi: I'm new to python and wxpython, and I'm trying to make a program to send mail. I'm using what follows: class MyFrame1(wx.Frame): def __init__(self, *args, **kwds): ... self.message = wx.TextCtrl(self.panel_1, -1, "") self.button_1 = wx.Button(self.panel_1, -1, "SEND Mail") ... # And then: wx.EVT_BUTTON(self,self.button_1.GetId(), self.Mail) # The Mail method is: def Mail(self,event): self.from = "dquepal at hotmail.com" self.host = "localhost" self.to = "danf_1979 at yahoo.es" self.body = self.message server = smtplib.SMTP(self.host) server.sendmail(self.from, [self.to], self.body) server.quit() But when pressing the Send Mail button I only get: TypeError: len() of unsized object Anybody knows what I'm doing wrong? Maybe I'm not getting the user input, or just dont know how to use that input in the Mail method... Because if I use: def Mail(self,event): self.from = "dquepal at hotmail.com" self.host = "localhost" self.to = "danf_1979 at yahoo.es" self.body = "any message" #as string everything works fine. server = smtplib.SMTP(self.host) server.sendmail(self.from, [self.to], self.body) server.quit() Thanks in advanced. Daniel Queirolo. ______________________________________________ Renovamos el Correo Yahoo! Nuevos servicios, m?s seguridad http://correo.yahoo.es From greg.kellogg at gmail.com Sat Aug 6 15:18:57 2005 From: greg.kellogg at gmail.com (Greg Kellogg) Date: Sat, 6 Aug 2005 08:18:57 -0500 Subject: [Tutor] Instances Message-ID: <3cbb1dc505080606183b30a54f@mail.gmail.com> Lets say i do: >>> i = f.get_movie('0092411') No I know the i holds an instance: >>> i How can I find out the value of all the data this instance has? I can do a dir(i) ['_Movie__modFunct', '_Movie__movie_data', '_Movie__namesRefs', '_Movie__titlesRefs', '__cmp__', '__contains__', '__deepcopy__', '__delitem__', '__doc__', '__getitem__', '__init__', '__module__', '__nonzero__', '__setitem__', '__str__', 'accessSystem', 'add_to_current_info', 'append_item', 'clear', 'copy', 'currentRole', 'current_info', 'default_info', 'get', 'get_current_info', 'get_namesRefs', 'get_titlesRefs', 'has_current_info', 'has_key', 'isSameTitle', 'items', 'keys', 'keys_alias', 'movieID', 'myID', 'myTitle', 'notes', 'reset', 'set_current_info', 'set_data', 'set_item', 'set_mod_funct', 'set_title', 'summary', 'update_namesRefs', 'update_titlesRefs', 'values'] I know there is more info in there than this, is there a way to see everything that 'i" without hunting and pecking? From kent37 at tds.net Sat Aug 6 16:15:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Aug 2005 10:15:27 -0400 Subject: [Tutor] Functional question In-Reply-To: <61d0e2b40508051429261822d6@mail.gmail.com> References: <61d0e2b405080513146fdf85ce@mail.gmail.com> <42F3CCC8.6000507@tds.net> <61d0e2b40508051429261822d6@mail.gmail.com> Message-ID: <42F4C5FF.2000608@tds.net> Bernard Lebel wrote: > Thanks Kent. > > I had tried the very same thing, but with a list instead of a tuple, > and got an got this: > > >>>>dMap[ ['allo','bonjour'] ] = 'salut' > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: list objects are unhashable > > It never crossed my mind that a tuple would do it. That is one of the key differences between a list and a tuple - a tuple can be used as a dictionary key. Dictionary keys must be hashable, which in practice means they must be immutable. A tuple whose members are also immutable works fine as a key. Kent From kent37 at tds.net Sat Aug 6 16:20:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Aug 2005 10:20:54 -0400 Subject: [Tutor] Get user input in wxpython In-Reply-To: <20050806084022.38284.qmail@web25202.mail.ukl.yahoo.com> References: <20050806084022.38284.qmail@web25202.mail.ukl.yahoo.com> Message-ID: <42F4C746.5060502@tds.net> _ Dan _ wrote: > Hi: > I'm new to python and wxpython, and I'm trying to make > a program to send mail. I'm using what follows: > class MyFrame1(wx.Frame): > def __init__(self, *args, **kwds): > ... > self.message = wx.TextCtrl(self.panel_1, -1, "") > self.button_1 = wx.Button(self.panel_1, -1, "SEND > Mail") > ... > # And then: > wx.EVT_BUTTON(self,self.button_1.GetId(), > self.Mail) > > # The Mail method is: > def Mail(self,event): > self.from = "dquepal at hotmail.com" > self.host = "localhost" > self.to = "danf_1979 at yahoo.es" > > self.body = self.message This line is the problem as you might have guessed :-) self.message is an instance of wx.TextCtrl, not a text string. Try self.body = self.message.GetValue() Kent PS There doesn't seem to be any need to make from, host, to and body be attributes of self; you could use plain local variables here. > > server = smtplib.SMTP(self.host) > server.sendmail(self.from, [self.to], > self.body) > server.quit() > > But when pressing the Send Mail button I only get: > TypeError: len() of unsized object > > Anybody knows what I'm doing wrong? Maybe I'm not > getting the user input, or just dont know how to use > that input in the Mail method... > > Because if I use: > def Mail(self,event): > self.from = "dquepal at hotmail.com" > self.host = "localhost" > self.to = "danf_1979 at yahoo.es" > > self.body = "any message" #as string everything > works fine. > > server = smtplib.SMTP(self.host) > server.sendmail(self.from, [self.to], self.body) > server.quit() > > Thanks in advanced. > Daniel Queirolo. > > > > > > ______________________________________________ > Renovamos el Correo Yahoo! > Nuevos servicios, m?s seguridad > http://correo.yahoo.es > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Aug 6 16:46:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Aug 2005 10:46:18 -0400 Subject: [Tutor] Instances In-Reply-To: <3cbb1dc505080606183b30a54f@mail.gmail.com> References: <3cbb1dc505080606183b30a54f@mail.gmail.com> Message-ID: <42F4CD3A.4000401@tds.net> Greg Kellogg wrote: > Lets say i do: > > >>>>i = f.get_movie('0092411') > > > No I know the i holds an instance: > > >>>>i > > > > How can I find out the value of all the data this instance has? I can > do a dir(i) ... > I know there is more info in there than this, is there a way to see > everything that 'i" without hunting and pecking? You appear to be using imdbpy. The file docs/README.package gives some tips on how to use Movie objects. A Movie behaves like a dictionary; the data is stored as key/value pairs. To see all the data in a movie you could use for key in movie.keys(): print key, '=', movie[key] (Normally I would use for key, value in movie.items(): but there is a bug in movie.items() and this doesn't work. Also Movie has a summary() method that returns a string describing the movie, so you could use print movie.summary() Here is an example based on info from README.packages: >>> from imdb import IMDb >>> i = IMDb() >>> movie_list = i.search_movie('beautiful girls') >>> first_match = movie_list[0] >>> print first_match.summary() Movie ===== Title: Beautiful Girls (1996) >>> i.update(first_match) >>> print first_match.summary() Movie ===== Title: Beautiful Girls (1996) Genres: Drama, Comedy, Romance. Director: Ted Demme. Writer: Scott Rosenberg. Cast: Matt Dillon (Tommy 'Birdman' Rowland), Noah Emmerich (Michael 'Mo' Morris), Annabeth Gish (Tracy Stover), Lauren Holly (Darian Smalls), Timothy Hutton (Willie Conway). Runtime: 112. Country: USA. Language: English. Rating: 7.2 Votes: 7754 Plot: Beautiful Girls is about a group of small-town friends joining up for their first high school reunion. They find themselves evaluating their liv es and their relationships. It's about growing up and facing reality. >>> i.update(first_match, 'all') >>> print first_match.summary() >>> for key, value in first_match.items(): ... print key, '=', value ... Traceback (most recent call last): File "", line 1, in ? File "imdb\Movie.py", line 226, in items return [(k, self.__movie_data[k]) for k in self.keys()] KeyError: 'canonical title' >>> for k in first_match.keys(): ... print k, '=', first_match[k] ... rating = 7.2 composer = [, , , , , ] producer = [, , , , , , ] film length (metres) = ['3145 m'] locations = ['Hopkins, Minnesota, USA (Reunion Location)'] runtimes = ['112'] ... LOTS more info about the movie! Kent From danf_1979 at yahoo.es Sat Aug 6 18:12:23 2005 From: danf_1979 at yahoo.es (danf_1979@yahoo.es) Date: Sat, 6 Aug 2005 12:12:23 -0400 (CLT) Subject: [Tutor] Get user input in wxpython Message-ID: <20050806161223.4F7C8560@localhost.localdomain> Just if someone is trying something similar... I did it! Thanks Ismael for your info! ... self.label_1 = wx.StaticText(self.panel_1, -1, "TO:") self.label_2 = wx.StaticText(self.panel_1, -1, "FROM:") self.label_3 = wx.StaticText(self.panel_1, -1, "SUBJECT") self.label_4 = wx.StaticText(self.panel_1, -1, "MESSAGE:") self.text_ctrl_hacia = wx.TextCtrl(self.panel_1, -1, "") self.text_ctrl_tumail = wx.TextCtrl(self.panel_1, -1, "") self.text_ctrl_asunto = wx.TextCtrl(self.panel_1, -1, "") self.text_ctrl_mensaje = wx.TextCtrl(self.panel_1, -1, "", style=wx.TE_MULTILINE) self.button_sendmail = wx.Button(self.panel_1, -1, "SEND MAIL") ... wx.EVT_BUTTON(self,self.button_sendmail.GetId(), self.Mail) ... def Mail(self,event): print self.text_ctrl_hacia.GetValue() self.hacia = self.text_ctrl_hacia.GetValue() self.desde = self.text_ctrl_tumail.GetValue() self.asunto = self.text_ctrl_asunto.GetValue() self.mensaje = self.text_ctrl_mensaje.GetValue() self.body = string.join(("From: %s" % self.desde,"To: %s" % self.hacia,"Subject: %s" % self.asunto,"",self.mensaje), "\r\n") self.host = "localhost" server = smtplib.SMTP(self.host) server.sendmail(self.desde, [self.hacia], self.body) server.quit() So I'm sending this mail from my program :) From python at kapitalisten.no Sat Aug 6 19:19:19 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Sat, 6 Aug 2005 19:19:19 +0200 (CEST) Subject: [Tutor] Lots of variables Message-ID: <4130.193.217.43.173.1123348759.squirrel@mail.sporck.net> Hello. I am trying to write a gui that has a lot of checkboxes. It is over 200 different ones. I use a for statement to generate: ver = 200 for i in ['Car','House','Boat','Plane']: self.fra26_che01p = Checkbutton (self.fra26) self.fra26_che01p.place(in_=self.fra26,x=5,y=ver) self.fra26_che01p.configure(text=i) self.getattr(self,i)1 = IntVar() self.fra26_che01p.configure(variable=getattr(self,i)) self.fra26_che01v = Checkbutton (self.fra26) self.fra26_che01v.place(in_=self.fra26,x=70,y=ver) #self.fra26_che01v.configure(text="1p") self.getattr(self,i)2 = IntVar() self.fra26_che01v.configure(variable=getattr(self,i)) ver = ver + 17 The variable does not work for obvious reasons. I need to change variable for each new creation. If I had made the variables manually, I would have written (variable=self.car1)/(variable=self.car2) and so forth. Is there some way I can make lots of variables without declaring them up front? Thanks in advance.... -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Sat Aug 6 19:47:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Aug 2005 13:47:57 -0400 Subject: [Tutor] Lots of variables In-Reply-To: <4130.193.217.43.173.1123348759.squirrel@mail.sporck.net> References: <4130.193.217.43.173.1123348759.squirrel@mail.sporck.net> Message-ID: <42F4F7CD.1010200@tds.net> ?yvind wrote: > Hello. > > I am trying to write a gui that has a lot of checkboxes. It is over 200 > different ones. I use a for statement to generate: > > ver = 200 > for i in ['Car','House','Boat','Plane']: > self.fra26_che01p = Checkbutton (self.fra26) > self.fra26_che01p.place(in_=self.fra26,x=5,y=ver) > self.fra26_che01p.configure(text=i) > self.getattr(self,i)1 = IntVar() > self.fra26_che01p.configure(variable=getattr(self,i)) > self.fra26_che01v = Checkbutton (self.fra26) > self.fra26_che01v.place(in_=self.fra26,x=70,y=ver) > #self.fra26_che01v.configure(text="1p") > self.getattr(self,i)2 = IntVar() > self.fra26_che01v.configure(variable=getattr(self,i)) > ver = ver + 17 > > The variable does not work for obvious reasons. I need to change variable > for each new creation. If I had made the variables manually, I would have > written (variable=self.car1)/(variable=self.car2) and so forth. Is there > some way I can make lots of variables without declaring them up front? The usual way to do this is to keep a dictionary mapping the 'variable' names to the values, or maybe just a list of the values. Since you access the checkbuttons through IntVars you may not need to keep a reference to the button itself. So maybe something like this: self.vars = {} ver = 200 for i in ['Car','House','Boat','Plane']: check1 = Checkbutton (self.fra26) check1.place(in_=self.fra26,x=5,y=ver) check1.configure(text=i) var1 = self.vars[i+'1'] = IntVar() check1 .configure(variable=var1) check2 = Checkbutton (self.fra26) check2.place(in_=self.fra26,x=70,y=ver) var2 = self.vars[i+'2'] = IntVar() check2.configure(variable=var2) ver = ver + 17 Now self.vars will have entries for 'Car1', 'Car2', etc. whose values will be the corresponding IntVars. Kent From cpu.crazy at gmail.com Sat Aug 6 21:54:01 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sat, 06 Aug 2005 13:54:01 -0600 Subject: [Tutor] IP Address from Python module? In-Reply-To: References: Message-ID: <42F51559.9060809@gmail.com> Thanks.. I hoped python had something like that!!! From lists at janeden.org Sun Aug 7 10:14:36 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 7 Aug 2005 10:14:36 +0200 Subject: [Tutor] Class instantiation parameters Message-ID: Hi, after using Perl for some years for simple scripting tasks, one of my programs reached a size where an OO design is appropriate. So I rewrote the program using OO techniques in Perl. Because I am not entirely satisfied with the implementation, I decided port the program to Python. The first thing I'd like to sort out are the parameters on class invocation. In Perl, I did (... for lines left out): my $page = Show->new(type => $type, id => $id); package Show; ... sub new { my $class = shift; my $self = { @_ }; ... bless $self, $class; return $self; } making use of the relatively liquid border between hashes (dictionaries) and arrays (lists). In Python, I would do: page = Show(type=type, id=id) class Show: def __init__(self, type, id): self.id = id self.type = type ... return self For two parameters, this is relatively simple. But if I have for example 10 parameters on instantiation, assigning each value the the class object manually will be really clumsy. So how can I add the values of all the paramaters to my class instance in one step? Thanks in advance, Jan -- Imagine if every Thursday your shoes exploded if you tied them the usual way. This happens to us all the time with computers, and nobody thinks of complaining. - Jeff Raskin From lists at janeden.org Sun Aug 7 11:59:32 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 7 Aug 2005 11:59:32 +0200 Subject: [Tutor] Class instantiation parameters In-Reply-To: Message-ID: Hi, Jan Eden wrote on 07.08.2005: >So how can I add the values of all the paramaters to my class >instance in one step? > apologies for replying to my own post: I just discovered the **args formal parameter. Thanks, Jan -- I was gratified to be able to answer promptly, and I did. I said I didn't know. - Mark Twain From ml.cyresse at gmail.com Sun Aug 7 13:24:57 2005 From: ml.cyresse at gmail.com (mailing list) Date: Sun, 7 Aug 2005 23:24:57 +1200 Subject: [Tutor] references and popping, caveats? Message-ID: Hi all, I have the following code - >>> j = """a = { b = { c = { d = 5 e = 10 } } }""" >>> ref = [] >>> data = {} >>> ref.append(data) >>> for line in j.split('\n'): ... if "=" in line: ... (LHS, RHS) = line.split(" = ") ... if RHS == "{": ... #open group ... ref[-1][LHS] = {} ... ref.append(ref[-1][LHS]) ... else: ... ref[-1][LHS] = RHS ... else: ... #Only other value in test data is "}", so close group ... ref.pop(-1) Fairly unreadable huh. Basically, I'm using the list to store dictionary references, so as to create a bunch of nested dictionaries, working on the principle of last in, first off. I guess it's a rudimentary stack or thereabouts. Basically, if there's any caveats with popping and/or lists of references, I'm dead keen to find out before I take my prototype any further. Alternatively, if there's a far more simpler way to do this, also keen to hear it. :) (My first version had a list of keys ["a", "b", "c", "d"] and would use that to track depth. I then had a function which looked like this - if len(keyList) - 1 == -1: return elif len(keyList) - 1 == 0: return fooDict[keyList[0]] elif len(keyList) - 1 == 1: return fooDict[keyList[0]][keyList[1]] ... ... elif len(keyList) -1 == 5: return fooDict[keyList[0]][keyList[1]][keyList[2]][keyList[3]][keyList[4]][keyList[5]] And so forth.... Yuck. My very own coding WTF. ) Any help appreciated, Liam Clarke From kent37 at tds.net Sun Aug 7 14:40:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Aug 2005 08:40:40 -0400 Subject: [Tutor] Class instantiation parameters In-Reply-To: References: Message-ID: <42F60148.9030005@tds.net> Jan Eden wrote: > In Python, I would do: > > page = Show(type=type, id=id) > > class Show: def __init__(self, type, id): self.id = id self.type = > type ... return self > > For two parameters, this is relatively simple. But if I have for > example 10 parameters on instantiation, assigning each value the the > class object manually will be really clumsy. > > So how can I add the values of all the paramaters to my class > instance in one step? There was recently a long discussion of this on comp.lang.python. http://groups.google.com/group/comp.lang.python/browse_frm/thread/7346ad00a14e821a/9dc993d295475cac?q=locals()&rnum=15&hl=en#9dc993d295475cac A simple solution is def __init__ (self, x, y, z): self.__dict__.update(locals()) del self.self Kent From lists at janeden.org Sun Aug 7 16:23:46 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 7 Aug 2005 16:23:46 +0200 Subject: [Tutor] Class instantiation parameters In-Reply-To: <42F60148.9030005@tds.net> Message-ID: Hi Kent, Kent Johnson wrote on 07.08.2005: >>So how can I add the values of all the paramaters to my class >>instance in one step? > >There was recently a long discussion of this on comp.lang.python. >http://groups.google.com/group/comp.lang.python/browse_frm/thread/ >7346ad00a14e821a/9dc993d295475cac?q=locals()&rnum=15&hl=en# >9dc993d295475cac Thanks for this. I thought I could do it with the help of **args, but maybe I still think too much in Perl terms. It's a bit unexpected that this task asks for such an indirect approach. In Perl, where my class instances are usually nothing but (blessed) hash references, a more verbose version of my actual method would read: package NewClass; ... sub new { my $self = shift; my $parameters = { @_ }; for (keys %$parameters) { $self->{$_} = $parameters->{$_}; } My idea was to transfer the same technique to Python like this: class NewClass: def __init__(self, **parameters): for i in parameters.keys(): self.i = parameters[i] But the assignment in the for loop obviously does not work with instance attributes. I will have to read up some more about instance attributes. Thanks again, Jan -- Bad spellers of the world Untie! From lists at janeden.org Sun Aug 7 16:33:42 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 7 Aug 2005 16:33:42 +0200 Subject: [Tutor] Class instantiation parameters In-Reply-To: Message-ID: Jan Eden wrote on 07.08.2005: >But the assignment in the for loop obviously does not work with >instance attributes. I will have to read up some more about instance >attributes. Ok... so this works: class NewClass: def __init__(self, **parameters): self.data = {} for i in parameters.keys(): self.data[i] = parameters[i] self = NewClass(arg1='Value', arg2='Another value', arg3='Yet another value') print self.data It seems that I need to add a dictionary as a data attribute to my instance object to do what I wanted to. This is unfortunate, because it complicates my syntax: Instead of self.type, I need to use self.data['type']. - Jan -- I'd never join any club that would have the likes of me as a member. - Groucho Marx From kent37 at tds.net Sun Aug 7 16:45:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Aug 2005 10:45:21 -0400 Subject: [Tutor] Class instantiation parameters In-Reply-To: References: Message-ID: <42F61E81.4080604@tds.net> Jan Eden wrote: > My idea was to transfer the same technique to Python like this: > > class NewClass: > def __init__(self, **parameters): > for i in parameters.keys(): self.i = parameters[i] > > But the assignment in the for loop obviously does not work with > instance attributes. I will have to read up some more about instance > attributes. for i in parameters.keys(): setattr(self, i, parameters[i]) or for k, v in parameters.items(): setattr(self, k, v) The problem with this approach is that the function can be called with any number of arguments - you lose the limited type safety you get from declaring the arguments in the def - and it only works with keyword arguments, not positional arguments. If you really just want a dictionary, maybe you should just use one? If you want the syntactic sugar of attribute access instead of dictionary lookup you could make a dict subclass that supports that. The comments to this recipe show one way to do it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 This recipe is more complete but has different initialization semantics that what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389916 You might also be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218485 Kent From administrata at hotmail.com Sun Aug 7 16:49:11 2005 From: administrata at hotmail.com (. ,) Date: Sun, 07 Aug 2005 14:49:11 +0000 Subject: [Tutor] Guess my number? Message-ID: I want the program to say "You're stupid!" When a player fails to guess in 10 tries. But, it's not working.. import random number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != number): if (guess > number): print "Lower...\n" elif (guess < number): print "Higher...\n" elif (tires > 10): print "You're stupid!" else: print "Error!" guess = int(raw_input("Take a guess: ")) tries += 1 print "\nYou guess it! The number was", number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From cpu.crazy at gmail.com Sun Aug 7 06:17:46 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sat, 06 Aug 2005 22:17:46 -0600 Subject: [Tutor] XMMS song search Message-ID: <42F58B6A.600@gmail.com> Hi. I have 7.8 GB of music (1808 songs) and I use XMMS to play them. However I can't find some songs. Apparently there is no song search feature in XMMS (something I plan to add whenever I learn C or can incorporate Python into C.. unless someone else has already done this) so I have a hard time finding a song (I have to open kwrite open the playlist and search for a song number or name). I thought I'd write a python program to scan the playlist file for a keyword. I tried: songsearch = raw_input(Enter song name: ") f = file(/home/joe/.xmms/xmms.pls) f.find(songsearch) but got an error: AttributeError: 'file' object has no attribute 'find' what can I do to display several songs that have 'a' in the name? What can I do to search the playlist in the first place? I wouldn't mind some links to tutorials that can show me how to do this. Thanks, Joe From rob.andrews at gmail.com Sun Aug 7 17:19:41 2005 From: rob.andrews at gmail.com (Rob Andrews) Date: Sun, 7 Aug 2005 10:19:41 -0500 Subject: [Tutor] Guess my number? In-Reply-To: References: Message-ID: <8d757d2e05080708198ee6ff7@mail.gmail.com> Let's take a look.... I pasted your code into a new window and gave it a go. You used tabs for indentation (or they got in there somewhere in the email/copy/paste process), which confused my tiny mind, so I replaced 'em with spaces. I noticed a few things. Here's my code: ##################################### import random import sys number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 while (guess != number): if (tries > 10): print "too many guesses" sys.exit() if (guess > number): print "Lower...\n" elif (guess < number): print "Higher...\n" # elif (tries > 10): # print "You're stupid!" else: print "Error!" guess = int(raw_input("Take a guess: ")) tries += 1 ##################################### I noticed you mis-spelled "tries" in one place, so I changed the spelling. I also moved the test for the number of tries to a separate "if" statement running before the "if" you had already included, so if the user guesses too many times, it won't continue to run through the guess-checking routine. And I used sys.exit() to get out cleanly when the user exceeds the guess limit. -Rob On 8/7/05, . , wrote: > I want the program to say "You're stupid!" When a player fails to guess in > 10 tries. > But, it's not working.. > > > import random > > number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess: ")) > tries = 1 > > while (guess != number): > if (guess > number): > print "Lower...\n" > elif (guess < number): > print "Higher...\n" > elif (tires > 10): > print "You're stupid!" > else: > print "Error!" > > guess = int(raw_input("Take a guess: ")) > tries += 1 > > print "\nYou guess it! The number was", number > print "And it only took you", tries, "tries!\n" > raw_input("\n\nPress the enter key to exit.") From amonroe at columbus.rr.com Sun Aug 7 17:46:04 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 7 Aug 2005 11:46:04 -0400 Subject: [Tutor] XMMS song search In-Reply-To: <42F58B6A.600@gmail.com> References: <42F58B6A.600@gmail.com> Message-ID: <150492854276.20050807114604@columbus.rr.com> > songsearch = raw_input(Enter song name: ") > f = file(/home/joe/.xmms/xmms.pls) Don't forget your quotation marks around the filename. > f.find(songsearch) You _find_ stuff in strings, not in the file itself. Read each line of the file one at a time, because each line will be a string. for thisline in f: if thisline.find(songsearch) > 0: print thisline #Also at the end of the program don't forget to close what you opened f.close() Alan From srini_iyyer_bio at yahoo.com Sun Aug 7 19:01:29 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sun, 7 Aug 2005 10:01:29 -0700 (PDT) Subject: [Tutor] a dictionary method good for this process In-Reply-To: <42F25805.5020904@tds.net> Message-ID: <20050807170129.54132.qmail@web53506.mail.yahoo.com> Hi Kent: Thank you for your tip on making a sub-dictionary. However, I see some new prbs. that I am unable to solve are persisting. could you enlighten me, please. > d={} > for m in listB: > cols = m.split('\t') > term = cols[1] > d.setdefault(term, []).append(m) > > for i in listA: > items = d.get(i) > for item in items: > print item >>> for i in imagecls: items= d.get(i) for i in items: print i Traceback (most recent call last): File "", line 3, in -toplevel- for i in items: TypeError: iteration over non-sequence >>> for i in imagecls: items = d.get(i) print items None ['NM_001903\t21652\tT65187\n', 'NM_001903\t21652\tT65118\n'] ['NM_001659\t22012\tT66053\n'] None First when I loop over items, I get iterative over non-sequence (I assume this is None type object). But when I print then I see the results as a list and None. What is this None. And why is it not allowing me to iteratve over the list? Please throw some light. Also, .setdefault() is still some what murky. May be I need to work more on that. Thanks Srini --- Kent Johnson wrote: > Srinivas Iyyer wrote: > > Dear group: > > > > I have two lists and I have to match the element > in > > the first list to element in second list and print > the > > line from second list: > > > > Example: > > listA =['apple','baby','cat'] > > listB > =['fruit\tapple','tree\tapple','fruit\tmango', > > 'human\tbaby' > > 'infant\tbaby' > > 'human\tAlbert' > > 'animal\tcat' > > 'tiger\tcat' > > 'animan\tdog'] > > > > > > I have to take apple, search in listB and print > > > > fruit apple > > tree apple > > infant baby > > human baby > > animal cat > > tiger cat > > Presumably that is the results from searching for > 'apple', 'baby' and 'cat'... > > I would make a helper dictionary that maps from the > second element in listB to a list of listB entries > containing that element. This way you make just one > pass over listB: > > listA =['apple','baby','cat'] > listB =['fruit\tapple','tree\tapple','fruit\tmango', > 'human\tbaby', > 'infant\tbaby', > 'human\tAlbert', > 'animal\tcat', > 'tiger\tcat', > 'animan\tdog'] > > # Make a helper dict that maps the second element of > listB to a list of elements > d={} > for m in listB: > cols = m.split('\t') > term = cols[1] > d.setdefault(term, []).append(m) > > for i in listA: > items = d.get(i) > for item in items: > print item > > > The only tricky part is the line > d.setdefault(term, []).append(m) > > This is just a shortcut for something like > try: > data = d[term] > except KeyError: > d[term] = data = [] > data.append(m) > > Kent > > > > > > > I am doing it this way: > > > > for i in listA: > > for m in listB: > > cols = m.split('\t') > > term = cols[2] > > if i == term: > > print m > > > > this is very time consuming. > > > > Because the two columns in listB are redundant I > am > > unable to do a dict method. > > > > The other way could be using a reg.ex method > (which I > > did not try yet because the script written based > on > > equality is still running. > > > > for i in listA: > > pat = re.compile(i) > > for m in listB: > > cols = m.split('\t') > > terms = cols[1] > > if pat.match(terms): > > print m > > > > Experts, could you please suggest any other method > > which is fast and does the job correctly. > > > > Thank you. > > > > Srini > > > > > > > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From alan.gauld at freenet.co.uk Sun Aug 7 19:04:13 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 7 Aug 2005 18:04:13 +0100 Subject: [Tutor] Lots of variables References: <4130.193.217.43.173.1123348759.squirrel@mail.sporck.net> Message-ID: <008301c59b72$09c26900$bea68651@xp> > I am trying to write a gui that has a lot of checkboxes. It is over > 200 > different ones. I use a for statement to generate: > > ver = 200 > for i in ['Car','House','Boat','Plane']: > self.fra26_che01p = Checkbutton (self.fra26) > self.fra26_che01p.place(in_=self.fra26,x=5,y=ver) > self.fra26_che01p.configure(text=i) > The variable does not work for obvious reasons. I need to change > variable > for each new creation. If I had made the variables manually, I would > have Try a dictionary using the strings in your list as the keys and the controls as the values. See the bank account example in my OOP topic for an example. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Aug 7 19:15:07 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 7 Aug 2005 18:15:07 +0100 Subject: [Tutor] Class instantiation parameters References: Message-ID: <008f01c59b73$92c78220$bea68651@xp> > page = Show(type=type, id=id) > > class Show: > def __init__(self, type, id): > self.id = id > ... > return self First a couple of comments. You don't need to return self from __init__. You can only instantiate Show *after* you've defined it. > For two parameters, this is relatively simple. > But if I have for example 10 parameters on instantiation, 10 *parameters* in the constructor is not that unusual. But at instantiation you would not normally expect to pass more than 4-6 *arguments*. The others would normally use default values. **args is indeed the solution to this so you may have figured it all out already, but your terminology is slightly confusing (because while it is strictly valid in what it says, but so unlikely in its meaning, that I suspect you are getting some of your terms mixed up?) > assigning each value the the class object manually > will be really clumsy. It's actually how most OOP languages do it! Perl is unusual baecause of its shortcuts and Python provides a half-way house solution. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From gordnjen at rogers.com Sun Aug 7 19:20:20 2005 From: gordnjen at rogers.com (gordnjen) Date: Sun, 7 Aug 2005 13:20:20 -0400 Subject: [Tutor] Assistance! Message-ID: <002d01c59b74$4a3954b0$a471c545@JennineGord> I am now stuck again. I am at my wit's end. The course I am taking is a supposed "beginners" course. It is a distance education class, and our textbook does NOT contain the information required to do all of the assignments (perhaps it was designed for people with more experience and/or knowledge?). Anyways, our latest assignment is that we have to create a working chequebook (view here: http://cmpt165.cs.sfu.ca/~ggbaker/examples/chequebook.html) This is what I have so far (see attached). I am so completely lost. Our textbook does not tell us how to implement a password security system on a website, or how to store data. The project is already over a week late, and I feel absolutely hopeless about it. Could you possibly give me some pointers on this? Please, please please? Thank you in advance, Jennine Gates -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.338 / Virus Database: 267.10.1/64 - Release Date: 04/08/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.338 / Virus Database: 267.10.1/64 - Release Date: 04/08/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050807/82acf60b/chequebook.html -------------- next part -------------- A non-text attachment was scrubbed... Name: chequelib.pyc Type: application/octet-stream Size: 2197 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050807/82acf60b/chequelib.obj -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: allcheques1130pm.py Url: http://mail.python.org/pipermail/tutor/attachments/20050807/82acf60b/allcheques1130pm.diff From alan.gauld at freenet.co.uk Sun Aug 7 19:23:45 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 7 Aug 2005 18:23:45 +0100 Subject: [Tutor] What's the invalid syntax? Code supplied References: Message-ID: <00aa01c59b74$c3f879c0$bea68651@xp> > What's the invalid syntax? Here is the code: > import random > hand = { > '0' : ["Ace"] > '1' : ["Two"] Nathan, You really need to take some time out to read about data structures in Python. You are trying to use a dictionary, with a string as a key and a list as a value. The list has a single string as its content. As Kent has pointed out you almost certainly can use a number as the key and I'm pretty sure you can get away with the string as the value. Why do you think you need a list as the value? Have you read any tutorial pages on dictionaries? Do you understand the concept of key/value pairs? You are making life difficult for yourself by picking inappropriate data structures. You are then posting broken code to the tutor list with no description of the error, or the error message text, which makes everyone on the list work much harder to figuure out what might be wrong! Ultimately it all slows down your work and everyone else who is contributing to the mailing list. Sorry if this sounds harsh but I've just come off 3 days of 14 hour shifts and am probably a bit less patient than normal. But this approach is slowing you down too. You will progress much faster if you take the time to *understand* what you are doing before doing it! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cpu.crazy at gmail.com Sun Aug 7 20:16:34 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 07 Aug 2005 12:16:34 -0600 Subject: [Tutor] Tutor Digest, Vol 18, Issue 37 In-Reply-To: References: Message-ID: <42F65002.1010509@gmail.com> Hi. > I want the program to say "You're stupid!" When a player fails to guess in > 10 tries. > But, it's not working.. Very simple fix for bug: > elif (guess < number): > print "Higher...\n" > elif (tires > 10): > print "You're stupid!" > else: > print "Error!" > > guess = int(raw_input("Take a guess: ")) > tries += 1 first off you tries is misspelled (someone probably already caught that). Second you have elif guess > ... and then elif tries > .... That's your problem. You need: if tries > 10: print "You're stupid." instead of elif tries > 10.... elif is used only when refering to the original if (in this case guess). So you need a new if statement. Hope this helps. Joe From cpu.crazy at gmail.com Sun Aug 7 20:17:14 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 07 Aug 2005 12:17:14 -0600 Subject: [Tutor] Guess my number? In-Reply-To: References: Message-ID: <42F6502A.8010401@gmail.com> Hi. > I want the program to say "You're stupid!" When a player fails to guess in > 10 tries. > But, it's not working.. Very simple fix for bug: > elif (guess < number): > print "Higher...\n" > elif (tires > 10): > print "You're stupid!" > else: > print "Error!" > > guess = int(raw_input("Take a guess: ")) > tries += 1 first off you tries is misspelled (someone probably already caught that). Second you have elif guess > ... and then elif tries > .... That's your problem. You need: if tries > 10: print "You're stupid." instead of elif tries > 10.... elif is used only when refering to the original if (in this case guess). So you need a new if statement. Hope this helps. Joe From tegmine at gmail.com Sun Aug 7 22:00:57 2005 From: tegmine at gmail.com (Luis N) Date: Sun, 7 Aug 2005 13:00:57 -0700 Subject: [Tutor] Assistance! In-Reply-To: <002d01c59b74$4a3954b0$a471c545@JennineGord> References: <002d01c59b74$4a3954b0$a471c545@JennineGord> Message-ID: <77bfa81a05080713001f4b069c@mail.gmail.com> On 8/7/05, gordnjen wrote: > > I am now stuck again. I am at my wit's end. The course I am taking is a > supposed "beginners" course. It is a distance education class, and our > textbook does NOT contain the information required to do all of the > assignments (perhaps it was designed for people with more experience and/or > knowledge?). Anyways, our latest assignment is that we have to create a > working chequebook (view here: > http://cmpt165.cs.sfu.ca/~ggbaker/examples/chequebook.html) > > This is what I have so far (see attached). > > I am so completely lost. > > Our textbook does not tell us how to implement a password security system on > a website, or how to store data. > > The project is already over a week late, and I feel absolutely hopeless > about it. > > Could you possibly give me some pointers on this? Please, please please? > > Thank you in advance, > > Jennine Gates > Hi Jennine, To complete this assignment you will be writing a CGI. From the website it appears that you have not had to write one before that used form data. To use form data with python, you should use the cgi module. You can examine the documentation for this module by pressing F1 while within IDLE, and entering the module list. Here's a simple example: #!/usr/LOCAL/bin/python print "Content-type: text/html\n\n" import cgi def main(form): if form.has_key("Name"): print "

Name: %s

" % form["Name"].value else: print """
""" if __name__ == "__main__": main(cgi.FieldStorage()) A working example is viewable at: http://cgi.sfu.ca/~rbnewby/cgi-bin/example.cgi Depending upon the requirements of the assignment you may be able to password protect the script with htauth, details here: http://www.sfu.ca/acs/sfuwebhelp/htaccess.htm Cheers, Luis From lists at janeden.org Sun Aug 7 22:08:25 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 7 Aug 2005 22:08:25 +0200 Subject: [Tutor] Class instantiation parameters In-Reply-To: <42F61E81.4080604@tds.net> Message-ID: Hi Kent, hi Alan, Alan G wrote on 07.08.2005: >> page = Show(type=type, id=id) >> >> class Show: >> def __init__(self, type, id): >> self.id = id >> ... >> return self > >First a couple of comments. >You don't need to return self from __init__. >You can only instantiate Show *after* you've defined it. > Right - I still think along the lines of Perl subroutines used as methods. >**args is indeed the solution to this so you may have >figured it all out already, but your terminology is >slightly confusing (because while it is strictly valid >in what it says, but so unlikely in its meaning, that >I suspect you are getting some of your terms mixed up?) The idea is to pass keyword arguments to an instantiation function and automatically create instance attributes for each keyword argument. My apologies if I still mix up some well-defined terms in Python. Kent Johnson wrote on 07.08.2005: >for i in parameters.keys(): setattr(self, i, parameters[i]) > >or for k, v in parameters.items(): setattr(self, k, v) > >The problem with this approach is that the function can be called >with any number of arguments - you lose the limited type safety you >get from declaring the arguments in the def - and it only works with >keyword arguments, not positional arguments. > Thanks! The setattr function is exactly what I was looking for. I should not need to worry about type safety, because the instance is instantiated from within a script after making sure that id is an integer and type is a string from a predefined set of strings. Now I'll see if I understand the practical difference between items() and iteritems() - the Python tutorial uses iteritems() in such a context. >If you really just want a dictionary, maybe you should just use one? >If you want the syntactic sugar of attribute access instead of >dictionary lookup you could make a dict subclass that supports that. I do not really want a dictionary - I just want to pass some named parameters and turn them into attributes. But I will check out the recipes anyway. This is a really friendly and helpful list. Thanks again for all your help. - Jan -- Mac OS X. Because making Unix user-friendly is easier than debugging Windows. From falcon3166 at hotmail.com Sun Aug 7 22:47:31 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 7 Aug 2005 14:47:31 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: <00aa01c59b74$c3f879c0$bea68651@xp> Message-ID: Alan and all, I'm no longer going to use this method. I thought up a more easier idea for dealing cards. I was going to share it, but with all this time and effort pointing out things that I should know, instead of helping me, I don't think I will, because it will probably be ripped to shreds by you, and dash my idea before it even takes off. I will keep my ideas to myself, Nathan Pinno --------------------------------------------------------------- I wanted help, and you critised me, I wanted aid, and you refused, So I will do it myself! --Author unknown --------------------------------------------------------------- ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Tutor mailing list" Sent: Sunday, August 07, 2005 11:23 AM Subject: Re: [Tutor] What's the invalid syntax? Code supplied >> What's the invalid syntax? Here is the code: >> import random >> hand = { >> '0' : ["Ace"] >> '1' : ["Two"] > > Nathan, > > You really need to take some time out to read about data structures in > Python. > You are trying to use a dictionary, with a string as a key and a list as a > value. > The list has a single string as its content. > > As Kent has pointed out you almost certainly can use a number as the key > and > I'm pretty sure you can get away with the string as the value. Why do you > think you need a list as the value? Have you read any tutorial pages on > dictionaries? Do you understand the concept of key/value pairs? > > You are making life difficult for yourself by picking inappropriate > data structures. You are then posting broken code to the tutor list > with no description of the error, or the error message text, which > makes everyone on the list work much harder to figuure out what might > be wrong! Ultimately it all slows down your work and everyone else > who is contributing to the mailing list. > > Sorry if this sounds harsh but I've just come off 3 days of 14 hour > shifts and am probably a bit less patient than normal. But this approach > is slowing you down too. You will progress much faster if you take the > time to *understand* what you are doing before doing it! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From falcon3166 at hotmail.com Sun Aug 7 23:11:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 7 Aug 2005 15:11:28 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: <00aa01c59b74$c3f879c0$bea68651@xp> <102511949604.20050807170420@columbus.rr.com> Message-ID: All, I do understand that concept. I was trying to implement it, and got stuck, so I asked for help. Nathan --------------------------------------------------------------- I wanted help, and you criticized me, I wanted aid, and you refused, So I will do it myself! --Author unknown ------------------------------------------------------------------- ----- Original Message ----- From: "R. Alan Monroe" To: "Nathan Pinno" Sent: Sunday, August 07, 2005 3:04 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied > >> because it will probably be ripped to shreds by you, > > Overreacting a bit? I think "Do you understand the concept of > key/value pairs?" was an honest question to figure out what you do and > don't know, and not a criticism. > > (a different) Alan > > From steve.reighard at gmail.com Mon Aug 8 01:31:07 2005 From: steve.reighard at gmail.com (steve reighard) Date: Sun, 7 Aug 2005 19:31:07 -0400 Subject: [Tutor] What's the invalid syntax? Code supplied In-Reply-To: References: <00aa01c59b74$c3f879c0$bea68651@xp> <102511949604.20050807170420@columbus.rr.com> Message-ID: <85661be805080716316c3c5196@mail.gmail.com> I've been on this mailing list for some time, I even remember Tim Peters, and have been very impressed with the patience and expertise of the "tutors" who answer questions, e.g. Allen, Danny, Bob, etc. I want to urge those tutors to continue to help us neophytes and to thank them for the help they give so frequently, good-naturedly, and freely. I will not mourn the fact that Nathan refuses to share his card dealing algorithm with the rest of us; but I would greatly miss the instruction of the people who try to help him understand the concepts and techniques of Python. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050807/1f88afff/attachment.htm From falcon3166 at hotmail.com Mon Aug 8 01:47:03 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 7 Aug 2005 17:47:03 -0600 Subject: [Tutor] What's the invalid syntax? Code supplied References: <00aa01c59b74$c3f879c0$bea68651@xp><102511949604.20050807170420@columbus.rr.com> <85661be805080716316c3c5196@mail.gmail.com> Message-ID: After reading what Steve Reighard and Danny wrote, I've decided that I was wrong. I'm sorry. I'm almost done my new algorithm, and will share it with the group. Nathan --------------------------------------------------------------- I wanted help, and you criticized me, I wanted aid, and you refused, So I will do it myself! --Author unknown ------------------------------------------------------------------- ----- Original Message ----- From: steve reighard To: tutor at python.org Sent: Sunday, August 07, 2005 5:31 PM Subject: Re: [Tutor] What's the invalid syntax? Code supplied I've been on this mailing list for some time, I even remember Tim Peters, and have been very impressed with the patience and expertise of the "tutors" who answer questions, e.g. Allen, Danny, Bob, etc. I want to urge those tutors to continue to help us neophytes and to thank them for the help they give so frequently, good-naturedly, and freely. I will not mourn the fact that Nathan refuses to share his card dealing algorithm with the rest of us; but I would greatly miss the instruction of the people who try to help him understand the concepts and techniques of Python. Steve ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050807/166d5add/attachment.htm From cpu.crazy at gmail.com Mon Aug 8 01:05:16 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 07 Aug 2005 17:05:16 -0600 Subject: [Tutor] IP Address from Python module? In-Reply-To: References: Message-ID: <42F693AC.70202@gmail.com> Danny Yoo wrote: >On Fri, 5 Aug 2005, Joseph Quigley wrote: > > > >>Is it possible to get my internet and/or network IP address from Python? >>Is there any other way to get it? >> >> > >Hi Joe, > >I think you're looking for socket.gethostbyname(). > > http://www.python.org/doc/lib/module-socket.html#l2h-2594 > >Here's an example using the socket.gethostbyname() function: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 > > > > Oh.. btw I don't think that will work on the internet. Cause a friend of mine has the 192.168.0.2 IP. My internet IP should be IPv6 and I don't think it changes... I'm also looking for my IP address that websites can block. But still I've found a use for the current tutorials, Thanks, JQ From kent37 at tds.net Mon Aug 8 02:42:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Aug 2005 20:42:01 -0400 Subject: [Tutor] Class instantiation parameters In-Reply-To: References: Message-ID: <42F6AA59.4000201@tds.net> Jan Eden wrote: > Now I'll see if I understand the practical difference between items() > and iteritems() - the Python tutorial uses iteritems() in such a > context. iteritems() is actually better usage but a little harder to explain. dict.items() creates a new list with the (key, value) pairs: >>> d=dict(a=1, b=2, c=3) >>> d {'a': 1, 'c': 3, 'b': 2} >>> d.items() [('a', 1), ('c', 3), ('b', 2)] dict.iteritems() returns an iterator which will yield the (key, value) pairs when its next method is called: >>> i = d.iteritems() >>> i >>> i.next() ('a', 1) >>> i.next() ('c', 3) >>> i.next() ('b', 2) In the context of a for loop, either one will work - the result is the same - but iteritems() is more efficient because it doesn't create an intermediate list which is then thrown away. Of course for small dicts the difference is negligible. > This is a really friendly and helpful list. Thanks again for all your help. You're welcome. The Python community is known for friendly hospitality, you'll like it here :-) Kent From falcon3166 at hotmail.com Mon Aug 8 03:04:21 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 7 Aug 2005 19:04:21 -0600 Subject: [Tutor] Can the following algorithm be improved? Message-ID: My message is in the zip file. It's too big otherwise. Nathan --------------------------------------------------------------- I wanted help, and you criticized me, I wanted aid, and you refused, So I will do it myself! --Author unknown ------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050807/1db69e70/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050807/1db69e70/PinnoNathanPaul-0001.vcf -------------- next part -------------- A non-text attachment was scrubbed... Name: message.zip Type: application/x-zip-compressed Size: 1623 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050807/1db69e70/message-0001.bin From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 03:05:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 7 Aug 2005 18:05:23 -0700 (PDT) Subject: [Tutor] IP Address from Python module? In-Reply-To: <42F693AC.70202@gmail.com> Message-ID: > >I think you're looking for socket.gethostbyname(). > > > > http://www.python.org/doc/lib/module-socket.html#l2h-2594 > > > >Here's an example using the socket.gethostbyname() function: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 > > > > > Oh.. btw I don't think that will work on the internet. Cause a friend of > mine has the 192.168.0.2 IP. Hi Joe, That actually sounds right in a sense. Any internet address with '192.168.x.x' is a "local" IP address, and is commonly allocated to folks on an internal network. For the really dull details about this, see RFC 1918 on "Private Address Space": http://www.faqs.org/rfcs/rfc1918.html So anything with 192.168.x.x is a private, internal address. In the context of the Internet, it's sorta useless, since it's not an address that one can use to connect to an external machine outside of the local area network. In fact, Brian Hammon's comment in: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 does mention that if you're behind a router, then the router itself sets up a small private network, which may explain why you may be seeing '192.168.x.x' as an address. The second comment on the cookbook page shows an alternative technique that should be more robust: use http://checkip.dyndns.org. > My internet IP should be IPv6 and I don't think it changes... Are you sure about that? IPv6 has not been widely deployed yet; most folks still connect to the internet through the IPv4 protocol. On the off-chance that you ARE on IPv6, see the getaddrinfo() function, which should accomodate: http://www.python.org/doc/lib/module-socket.html#l2h-2592 For example: ###### >>> import socket >>> socket.getaddrinfo('hkn.eecs.berkeley.edu', 80) [(2, 1, 6, '', ('128.32.47.228', 80)), (2, 2, 17, '', ('128.32.47.228', 80))] ###### Good luck to you! From kent37 at tds.net Mon Aug 8 03:08:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Aug 2005 21:08:57 -0400 Subject: [Tutor] a dictionary method good for this process In-Reply-To: <20050807170129.54132.qmail@web53506.mail.yahoo.com> References: <20050807170129.54132.qmail@web53506.mail.yahoo.com> Message-ID: <42F6B0A9.5080705@tds.net> Srinivas Iyyer wrote: > Hi Kent: > Thank you for your tip on making a sub-dictionary. > However, I see some new prbs. that I am unable to > solve are persisting. could you enlighten me, please. > > >>d={} >>for m in listB: >> cols = m.split('\t') >> term = cols[1] >> d.setdefault(term, []).append(m) >> >>for i in listA: >> items = d.get(i) >> for item in items: >> print item > > >>>>for i in imagecls: > > items= d.get(i) > for i in items: > print i > > > > Traceback (most recent call last): > File "", line 3, in -toplevel- > for i in items: > TypeError: iteration over non-sequence > > > > >>>>for i in imagecls: > > items = d.get(i) > print items > > > None > ['NM_001903\t21652\tT65187\n', > 'NM_001903\t21652\tT65118\n'] > ['NM_001659\t22012\tT66053\n'] > None > > > > > > First when I loop over items, I get iterative over > non-sequence (I assume this is None type object). > > But when I print then I see the results as a list and > None. > > What is this None. And why is it not allowing me to > iteratve over the list? None is the result of looking up one of the items in imagecls in d. This means that item has no entry in d, so d.get() returns None. Then you try to iterate over None (in the nested loop) and you can't do that. I would fix it by using d[i] to do the dictionary lookup and catching KeyError: for i in imagecls: try: items= d[i] for i in items: print i except KeyError: print 'No entry for', i, 'in d' > Please throw some light. Also, .setdefault() is still > some what murky. May be I need to work more on that. Some docs here: http://docs.python.org/lib/typesmapping.html Kent From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 03:30:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 7 Aug 2005 18:30:24 -0700 (PDT) Subject: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? In-Reply-To: Message-ID: Answer: yes, very much so. *grin* Ok, let's take a look at some snippets. ###### cd = int(raw_input("How many cards to deal (1-6) or 9 to exit:")) if cd == 1: a = random.choice(range(52)) if a == 0: a = "Ace of Hearts" elif a == 1: a = "Two of Hearts" [... code cut] elif cd == 2: b = random.choice(range(52)) c = random.choice(range(52)) for item in [b,c]: if item == 0: item = "Ace of Hearts" elif item == 1: item = "Two of Hearts" [... code cut] elif cd == 3: d = random.choice(range(52)) e = random.choice(range(52)) f = random.choice(range(52)) for item in (d,e,f): if item == 0: item = "Ace of Hearts" elif item == 1: item = "Two of Hearts" ###### Ok, let's stop there. The block of code above is taking a number (0-52) and trying to transform it into a readable definition. But there is repetition here that can be improved if you take advantage of the problem's structure. If you can write a function that takes a number from 0 to 52, and turns it into a card name, then instead of having to repeat the same if/elif code the number of times that you're dealing a card, you can save a lot of typing. You'll only need maybe eighty lines of code, instead of six hundred. (Actually, if you take advantage of the essence of the program, the program can be reduced to about ten lines total. That's the general direction that we'll try to lead you towards. Short programs are much nicer than long ones.) To make it clear what we mean, here's a similar situation: let's say that we wanted to flip two coins and get back a nice description of what we got. We could write code like this: ###### first_flip = random.choice(range(2)) second_flip = random.choice(range(2)) if first_flip == 0 and second_flip == 0: print "heads", "heads" elif first_flip == 0 and second_flip == 1: print "heads", "tails" elif first_flip == 1 and second_flip == 0: print "tails", "heads" elif first_flip == 1 and second_flip == 1: print "tails", "tails" ####### But there is a much nicer way of writing this: ###### def number_to_coin(n): if n == 0: return "heads" else: return "tails" first_flip = random.choice(range(2)) second_flip = random.choice(range(2)) print number_to_coin(first_flip), number_to_coin(second_flip) ###### There is a concrete reason why the second version is better: it scales if we want to use more coins. Once we have number_to_coin(), we can easily handle three coins: ###### first_flip = random.choice(range(2)) second_flip = random.choice(range(2)) third_flip = random.choice(range(2)) print number_to_coin(first_flip), number_to_coin(second_flip), print number_to_coin(third_flip) ###### The original approach, on the other hand, simply won't scale at all, and we'll end up with huge source code for very little gain. Avoiding code duplication is one major reason that we use functions. As soon as you start cutting and pasting code, that's a honking red warning light that you should be writing functions. But it takes practice, which is what we're pointing out to you now. *grin* Try rewriting your program so you don't copy-and-paste those huge if/elif blocks on each card flip. That is, write a function number_to_card() that takes a number from 0 to 52 and returns the string description of that card. Your program will be much more managable, and will probably fit on a single screen. From falcon3166 at hotmail.com Mon Aug 8 04:10:19 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 7 Aug 2005 20:10:19 -0600 Subject: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? References: Message-ID: My message is in the attachment. --------------------------------------------------------------- I wanted help, and you criticized me, I wanted aid, and you refused, So I will do it myself! --Author unknown ------------------------------------------------------------------- ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Sunday, August 07, 2005 7:30 PM Subject: Use functions re avoid Re: [Tutor] Can the following algorithm be improved? > > Answer: yes, very much so. *grin* > > > Ok, let's take a look at some snippets. > > ###### > cd = int(raw_input("How many cards to deal (1-6) or 9 to exit:")) > if cd == 1: > a = random.choice(range(52)) > if a == 0: > a = "Ace of Hearts" > elif a == 1: > a = "Two of Hearts" > [... code cut] > elif cd == 2: > b = random.choice(range(52)) > c = random.choice(range(52)) > for item in [b,c]: > if item == 0: > item = "Ace of Hearts" > elif item == 1: > item = "Two of Hearts" > [... code cut] > elif cd == 3: > d = random.choice(range(52)) > e = random.choice(range(52)) > f = random.choice(range(52)) > for item in (d,e,f): > if item == 0: > item = "Ace of Hearts" > elif item == 1: > item = "Two of Hearts" > ###### > > Ok, let's stop there. > > The block of code above is taking a number (0-52) and trying to transform > it into a readable definition. But there is repetition here that can be > improved if you take advantage of the problem's structure. > > > If you can write a function that takes a number from 0 to 52, and turns it > into a card name, then instead of having to repeat the same if/elif code > the number of times that you're dealing a card, you can save a lot of > typing. You'll only need maybe eighty lines of code, instead of six > hundred. > > (Actually, if you take advantage of the essence of the program, the > program can be reduced to about ten lines total. That's the general > direction that we'll try to lead you towards. Short programs are much > nicer than long ones.) > > > > To make it clear what we mean, here's a similar situation: let's say that > we wanted to flip two coins and get back a nice description of what we > got. We could write code like this: > > ###### > first_flip = random.choice(range(2)) > second_flip = random.choice(range(2)) > > if first_flip == 0 and second_flip == 0: > print "heads", "heads" > elif first_flip == 0 and second_flip == 1: > print "heads", "tails" > elif first_flip == 1 and second_flip == 0: > print "tails", "heads" > elif first_flip == 1 and second_flip == 1: > print "tails", "tails" > ####### > > > But there is a much nicer way of writing this: > > ###### > def number_to_coin(n): > if n == 0: > return "heads" > else: > return "tails" > > first_flip = random.choice(range(2)) > second_flip = random.choice(range(2)) > print number_to_coin(first_flip), number_to_coin(second_flip) > ###### > > > There is a concrete reason why the second version is better: it scales if > we want to use more coins. Once we have number_to_coin(), we can easily > handle three coins: > > ###### > first_flip = random.choice(range(2)) > second_flip = random.choice(range(2)) > third_flip = random.choice(range(2)) > print number_to_coin(first_flip), number_to_coin(second_flip), > print number_to_coin(third_flip) > ###### > > The original approach, on the other hand, simply won't scale at all, and > we'll end up with huge source code for very little gain. > > > Avoiding code duplication is one major reason that we use functions. As > soon as you start cutting and pasting code, that's a honking red warning > light that you should be writing functions. But it takes practice, which > is what we're pointing out to you now. *grin* > > > Try rewriting your program so you don't copy-and-paste those huge if/elif > blocks on each card flip. > > That is, write a function number_to_card() that takes a number from 0 to > 52 and returns the string description of that card. Your program will be > much more managable, and will probably fit on a single screen. > > -------------- next part -------------- A non-text attachment was scrubbed... Name: message2.zip Type: application/x-zip-compressed Size: 817 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050807/054f2b05/message2.bin From bvande at po-box.mcgill.ca Mon Aug 8 06:03:46 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 08 Aug 2005 00:03:46 -0400 Subject: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? In-Reply-To: References: Message-ID: <42F6D9A2.4010805@po-box.mcgill.ca> Nathan Pinno said unto the world upon 2005-08-07 22:10: > My message is in the attachment. Nathan, Just one fellow's voice, but I vote for "please don't do that" [the attachment]. It makes it more work to read your message. > Here is the improved algorithm: > import random > a = random.choice(range(52)) > u = random.choice(range(52)) > cards = ['Ace of Hearts','Two of Hearts', > 'Jack of Clubs','Queen of Clubs','King of Clubs'] > print "The Card Dealer" > print "By Nathan Pinno" > while 1: > cd = int(raw_input("How many cards to deal (1-6) or 9 to exit:")) > if cd == 1: > print cards[a] > elif cd == 2: > print cards[b] > print cards[c] > elif cd == 3: > print cards[d] > print cards[e] > print cards[f] > elif cd == 4: > print cards[g] > print cards[j] > elif cd == 5: > print cards[k] > print cards[o] > elif cd == 6: > print cards[p] > print cards[u] > elif cd == 9: > break > print "Goodbye." > > Can it be improved on anympre? Yep. You should follow Danny's suggestion and make a function which deals a single card. Then, your can call that function the requisite number of times. I'm not sure in the code here why you define a-u. Is there some reason you cannot have the two card case use a and b, the 3 case a, b, and c, etc.? > R. Alan Monroe suggested a different way. Instead of cards, you would would > have cardrank and type. To get the cardrank and type you would do a % 4, > and for the type a % 13. It would work, only how would you keep two > identical cards from showing up? Good question. But notice that your code has the same problem. Nothing stops the (dramatically unlikely) even that a-u all get assigned the same card. Over 6 cards, it will certainly turn up that you have given the same card twice with this code, too. (The way I figure it: >>> ( (52**6) - (52*51*50*49*48*47.0) ) / (52**6) 0.25858966166881681 25% of the time.) Say you go with your method of defining a deck (cards above) and then making random choices from it. Try something like this (untested code): cards = ["Ace of ...",] # As above cards_dealt = [] def get_card(): while True: new_card = random.choice(cards)] if new_card not in cards_dealt: cards_dealt.append(new_card) break return new_card while True: cd = #as before if cd == 9: break elif cd in range(1, 7): the_deal = [] for i in range(cd): the_deal.append(get_card()) else: print "Read the instructions, please." This could still be improved a lot (it was off the cuff). For instance, get_card might in theory take 1000's of attempts to get a 'fresh' card. There are much more efficient ways. But it might be a shorter step from the code you have. Small improvements are small, but they are also improvements. I really suggest you take make a closer examination of Danny's coin example. Best, Brian vdB From tomcloyd at bestmindhealth.com Mon Aug 8 07:01:04 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Sun, 07 Aug 2005 22:01:04 -0700 Subject: [Tutor] use of webbrowser.open_new() Message-ID: Having just discovered the webbrowser module, I've confirmed that I can indeed open a URL in my default browser using something like webbrowser.get_new("{URL}") What I want to do is open a web page stored on my local machine. I'm not getting it to work - webbrowser.open_new("C:\__Library\folders\05238 Design for Confusion\05238 Design for Confusion -05krugman.html") Traceback (most recent call last): File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 3149, in runcode locals = self.frame.f_locals) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 1569, in runcode h_exec(code, globals=globals, locals=locals, module=module) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 516, in __init__ exec code in globals, locals File "", line 0, in __main__ File "C:\Python24\Lib\webbrowser.py", line 46, in open_new get().open(url, 1) File "C:\Python24\Lib\webbrowser.py", line 250, in open os.startfile(url) WindowsError: [Errno 2] The system cannot find the file specified: 'C:\\__Library\x0colders*38 Design for Confusion*38 Design for Confusion -05krugman.html' Can you suggest what I might be doing wrong here? -- t. ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com / tc at bestmindhealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From jfouhy at paradise.net.nz Mon Aug 8 07:15:20 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 08 Aug 2005 17:15:20 +1200 (NZST) Subject: [Tutor] use of webbrowser.open_new() In-Reply-To: References: Message-ID: <1123478120.42f6ea68c2574@www.paradise.net.nz> Quoting Tom Cloyd : Compare the filename here: > webbrowser.open_new("C:\__Library\folders\05238 Design for Confusion\05238 > Design for Confusion -05krugman.html") With here: > WindowsError: [Errno 2] The system cannot find the file specified: > 'C:\\__Library\x0colders*38 Design for Confusion*38 Design for Confusion > -05krugman.html' Do you notice any differences? -- John. From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 07:26:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 7 Aug 2005 22:26:33 -0700 (PDT) Subject: [Tutor] use of webbrowser.open_new() In-Reply-To: Message-ID: On Sun, 7 Aug 2005, Tom Cloyd wrote: > Having just discovered the webbrowser module, I've confirmed that I can > indeed open a URL in my default browser using something like > > webbrowser.get_new("{URL}") > > What I want to do is open a web page stored on my local machine. I'm not > getting it to work - > > webbrowser.open_new("C:\__Library\folders\05238 Design for Confusion\05238 > Design for Confusion -05krugman.html") Hi Tom, Not sure if this is relevant, but Local file urls should have a "file:///" prefix. For the specific details Section 3.10 of: http://www.faqs.org/rfcs/rfc1738.html shows the syntax of file URLs. You may want to double check that the file that you're trying to open does exist: it has an unusual file name, and even small typos will cause issues. Try using webrowser.open_new on simpler file names first, to see if those work out for you. Good luck! From rabidpoobear at gmail.com Mon Aug 8 08:38:13 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 8 Aug 2005 01:38:13 -0500 Subject: [Tutor] deck dealing program Message-ID: <004201c59be3$c15805e0$aa0ca8c0@luke> from random import randint def identify_card(n): cardname = "" royals = ["Jack","Queen","King","Ace"] temp = n % 13 if temp > 8: cardname += royals[temp-9] else: cardname += str(temp+2) cardname += " of " suits = ["Spades","Hearts","Diamonds","Clubs"] cardname += suits[n/13] return cardname def main(): deck = range(52) cards = [] while 1: x = raw_input("how many cards do you want? ") try: x = int(x) except ValueError: print "Invalid value exiting for I have no error code. Please use an int next time." raise SystemExit if x <= 52 and x >= 0: y = 0 while y < x: cards.append(identify_card(deck.pop(randint(0,len(deck)-1)))) y += 1 break print cards if __name__ == "__main__": main() #Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/184c1fac/attachment.htm From python-tutor at toddmaynard.com Mon Aug 8 09:02:09 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Mon, 8 Aug 2005 03:02:09 -0400 Subject: [Tutor] deck dealing program In-Reply-To: <004201c59be3$c15805e0$aa0ca8c0@luke> References: <004201c59be3$c15805e0$aa0ca8c0@luke> Message-ID: <200508080302.10003.python-tutor@toddmaynard.com> Are you: a.) Having trouble with the code and looking for help? b.) Looking for suggestions on how to improve the code? c.) Offering the code as a demo for Nathan et al.? I was just doing stuff along the same lines and was having fun seeing the different approaches to the same problem. --Todd On Monday 08 August 2005 02:38 am, luke wrote: > from random import randint > > def identify_card(n): > cardname = "" > royals = ["Jack","Queen","King","Ace"] > temp = n % 13 > if temp > 8: > cardname += royals[temp-9] > else: > cardname += str(temp+2) > cardname += " of " > > suits = ["Spades","Hearts","Diamonds","Clubs"] > cardname += suits[n/13] > return cardname > > def main(): > deck = range(52) > cards = [] > while 1: > x = raw_input("how many cards do you want? ") > try: > x = int(x) > except ValueError: > print "Invalid value exiting for I have no error code. Please > use an int next time." raise SystemExit > if x <= 52 and x >= 0: > y = 0 > while y < x: > > cards.append(identify_card(deck.pop(randint(0,len(deck)-1)))) y += 1 > break > print cards > if __name__ == "__main__": > main() > > #Luke From gnumathetes at gmail.com Mon Aug 8 09:07:40 2005 From: gnumathetes at gmail.com (Don Parris) Date: Mon, 8 Aug 2005 03:07:40 -0400 Subject: [Tutor] Question About chdir() Message-ID: <669261440508080007ac65623@mail.gmail.com> The book, "Programming Python", shows an example of os.chdir() on the Windows platform, as follows: os.chdir(r'c:\temp') What's the 'r' for? It didn't seem to make any difference in how Python works - at least not on the surface. Thanks, Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com "Hey man, whatever pickles your list!" From ewald.ertl at hartter.com Mon Aug 8 09:16:24 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 08 Aug 2005 09:16:24 +0200 Subject: [Tutor] Question About chdir() In-Reply-To: <669261440508080007ac65623@mail.gmail.com> References: <669261440508080007ac65623@mail.gmail.com> Message-ID: <42F706C8.5000609@hartter.com> Hi Don! Don Parris wrote: > The book, "Programming Python", shows an example of os.chdir() on the > Windows platform, as follows: > > os.chdir(r'c:\temp') r ... raw Strings. There will no substitution be processed. Otherwise the "\t" ( Tab ) will be inserted in the string: >>> print "a\tb" a b >>> print r"a\tb" a\tb >>> HTH Ewald From python-tutor at toddmaynard.com Mon Aug 8 09:18:34 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Mon, 8 Aug 2005 03:18:34 -0400 Subject: [Tutor] Question About chdir() In-Reply-To: <669261440508080007ac65623@mail.gmail.com> References: <669261440508080007ac65623@mail.gmail.com> Message-ID: <200508080318.34076.python-tutor@toddmaynard.com> Let's see if I can get this right.....as I am working on memory and not enough sleep. The 'r' means that using a raw string so the backslashes aren't escaped out.... The equivalent without using the 'r' would be: os.chdir('c:\\temp') --Todd On Monday 08 August 2005 03:07 am, Don Parris wrote: > The book, "Programming Python", shows an example of os.chdir() on the > Windows platform, as follows: > > os.chdir(r'c:\temp') > > What's the 'r' for? It didn't seem to make any difference in how > Python works - at least not on the surface. > > Thanks, > Don From davholla2002 at yahoo.co.uk Mon Aug 8 10:46:05 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 8 Aug 2005 09:46:05 +0100 (BST) Subject: [Tutor] Get information from a web page Message-ID: <20050808084605.17770.qmail@web25406.mail.ukl.yahoo.com> Hi All, I am trying to save to disk a webpage (so I can extract useful info) with a url of type "http://xxx.co.uk/index.php?node=2371&pagetree=&fromid=20397". However the following :- urllib.urlopen, urllib._urlopener, urllib2.Request, urllib2.urlopen,urllib2.urlretrieve just retrieve this webpage :- http://xxx.co.uk (the root page) not the page I wanted to retrieve, any ideas about to get the right page ? Thanks inadvance David --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/d55ebbde/attachment.htm From python-tutor at toddmaynard.com Mon Aug 8 11:11:57 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Mon, 8 Aug 2005 05:11:57 -0400 Subject: [Tutor] Get information from a web page In-Reply-To: <20050808084605.17770.qmail@web25406.mail.ukl.yahoo.com> References: <20050808084605.17770.qmail@web25406.mail.ukl.yahoo.com> Message-ID: <200508080511.57809.python-tutor@toddmaynard.com> Not sure exactly what you have going wrong without the code or the exact url you are using. Does something like: import urllib page = urllib.urlopen("http://slashdot.org/article.pl?sid=05/08/08/043236&tid=126").read() print page give you the correct results? Is the problem specific to only to that url? --Todd On Monday 08 August 2005 04:46 am, David Holland wrote: > Hi All, > I am trying to save to disk a webpage (so I can extract useful info) with a > url of type "http://xxx.co.uk/index.php?node=2371&pagetree=&fromid=20397". > However the following :- > urllib.urlopen, urllib._urlopener, urllib2.Request, > urllib2.urlopen,urllib2.urlretrieve just retrieve this webpage :- > http://xxx.co.uk (the root page) not the page I wanted to retrieve, any > ideas about to get the right page ? Thanks inadvance > > David > > > --------------------------------- > Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with > voicemail From davholla2002 at yahoo.co.uk Mon Aug 8 12:21:59 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 8 Aug 2005 11:21:59 +0100 (BST) Subject: [Tutor] Tutor Digest, Vol 18, Issue 41 In-Reply-To: Message-ID: <20050808102159.20196.qmail@web25407.mail.ukl.yahoo.com> Looking at the slashdot url works fine, I think the problem is because I am trying to download a page with an address of the form url.php?node=5924&pagetree=&fromid=&objectid=25586 And I only download url not url.phpetc. Is there anyway that that can be done ? David Message: 8 Date: Mon, 8 Aug 2005 05:11:57 -0400 From: python-tutor at toddmaynard.com Subject: Re: [Tutor] Get information from a web page To: tutor at python.org Message-ID: <200508080511.57809.python-tutor at toddmaynard.com> Content-Type: text/plain; charset="iso-8859-6" Not sure exactly what you have going wrong without the code or the exact url you are using. Does something like: import urllib page = urllib.urlopen("http://slashdot.org/article.pl?sid=05/08/08/043236&tid=126").read() print page give you the correct results? Is the problem specific to only to that url?************************************* --------------------------------- To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/c82e6b2b/attachment.htm From tomcloyd at bestmindhealth.com Mon Aug 8 12:12:38 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Mon, 08 Aug 2005 03:12:38 -0700 Subject: [Tutor] raw string - solution to open_new() problem Message-ID: Ewald Ertl's reply to Don Parris's question about "r" operator gave me the idea of trying that out to solve my problem with file name scrambling when trying to use webbrowser.open_new() to open a file on my computer in a browser. It worked! So, thie webbrowser.open_new("file://C:\__Library\folders\02394 Yale Style Manual\02394 Yale_Style_Manual.htm") does not work, but this webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style Manual\02394 Yale_Style_Manual.htm") does. Thank you Ewald, for triggering the solution in my mind! Now, if anyone can explain why webbrowser.open_new() does the character substitution thing it was doing (and thus becoming unable to locate the file in question), I'm eager to hear it. Meanwhile, I can go ahead with my program. -- t. ====================================================== Tom Cloyd, MS MA, LMHC Private practice Psychotherapist Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com / tc at bestmindhealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From kent37 at tds.net Mon Aug 8 13:08:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 07:08:32 -0400 Subject: [Tutor] use of webbrowser.open_new() In-Reply-To: References: Message-ID: <42F73D30.70706@tds.net> Tom Cloyd wrote: > Having just discovered the webbrowser module, I've confirmed that I can > indeed open a URL in my default browser using something like > > webbrowser.get_new("{URL}") > > What I want to do is open a web page stored on my local machine. I'm not > getting it to work - > > webbrowser.open_new("C:\__Library\folders\05238 Design for Confusion\05238 > Design for Confusion -05krugman.html") The backslash (\) has a special meaning in strings; it means, "interpret the next character as a special code". A complete list of the codes is here: http://docs.python.org/ref/strings.html So \f means FORM FEED and \052 means the character with octal value 052 which happens to be an asterisk. That is why the file name in the error message looks different from the one you wrote. There are two ways to fix this. First, you can prefix the string with an 'r' (for 'raw') which disables most of the \ escapes. This is handy when you are copying the file name from Windows Explorer: webbrowser.open_new(r"C:\__Library\folders\05238 Design for Confusion\05238 Design for Confusion -05krugman.html") Alternately you can use / instead of \; this will work fine: webbrowser.open_new("C:/__Library/folders/05238 Design for Confusion/05238 Design for Confusion -05krugman.html") Kent > Traceback (most recent call last): > File "C:\Program Files\ActiveState Komodo > 3.1\dbgp\pythonlib\dbgp\client.py", line 3149, in runcode > locals = self.frame.f_locals) > File "C:\Program Files\ActiveState Komodo > 3.1\dbgp\pythonlib\dbgp\client.py", line 1569, in runcode > h_exec(code, globals=globals, locals=locals, module=module) > File "C:\Program Files\ActiveState Komodo > 3.1\dbgp\pythonlib\dbgp\client.py", line 516, in __init__ > exec code in globals, locals > File "", line 0, in __main__ > File "C:\Python24\Lib\webbrowser.py", line 46, in open_new > get().open(url, 1) > File "C:\Python24\Lib\webbrowser.py", line 250, in open > os.startfile(url) > WindowsError: [Errno 2] The system cannot find the file specified: > 'C:\\__Library\x0colders*38 Design for Confusion*38 Design for Confusion > -05krugman.html' > > Can you suggest what I might be doing wrong here? > > -- t. > > ====================================================== > Tom Cloyd > Bellingham, Washington, U.S.A: (360) 920-1226 > << BestMindHealth.com / tc at bestmindhealth.com >> > ====================================================== > > Using Opera's revolutionary e-mail client (program): > http://www.opera.com/mail/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Aug 8 13:15:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 07:15:12 -0400 Subject: [Tutor] Tutor Digest, Vol 18, Issue 41 In-Reply-To: <20050808102159.20196.qmail@web25407.mail.ukl.yahoo.com> References: <20050808102159.20196.qmail@web25407.mail.ukl.yahoo.com> Message-ID: <42F73EC0.2040609@tds.net> David Holland wrote: > Looking at the slashdot url works fine, I think the problem is because I > am trying to download a page with an address of the form > url.php?node=5924&pagetree=&fromid=&objectid=25586 > And I only download url not url.phpetc. > Is there anyway that that can be done ? Please show us some code. Kent From lists at janeden.org Mon Aug 8 13:16:18 2005 From: lists at janeden.org (Jan Eden) Date: Mon, 8 Aug 2005 13:16:18 +0200 Subject: [Tutor] Fetching dictionaries using MySQLdb Message-ID: Hi, in Perl's DBI, I used fetchrow_hashref() to receive a database row as a dictionary, with the field names being the dictionary keys. MySQLdb's fetchone() returns a tuple Unfortunately, I have a dictionary of SQL queries which return rows of different lengths (read: with a varying number of fields). The documentation for MySQLdb says that fetchoneDict() is deprecated and the usage of fetchone() is suggested. Is there a recommended way to receive the results of an SQL query in the form I need? Or do I have to create a dictionary of fieldname tuples which can be zipped with the query result tuple? Thanks, Jan -- Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl From kent37 at tds.net Mon Aug 8 13:32:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 07:32:54 -0400 Subject: [Tutor] Fetching dictionaries using MySQLdb In-Reply-To: References: Message-ID: <42F742E6.7020900@tds.net> Jan Eden wrote: > Hi, > > in Perl's DBI, I used fetchrow_hashref() to receive a database row as > a dictionary, with the field names being the dictionary keys. > > MySQLdb's fetchone() returns a tuple Unfortunately, I have a > dictionary of SQL queries which return rows of different lengths > (read: with a varying number of fields). > > The documentation for MySQLdb says that fetchoneDict() is deprecated > and the usage of fetchone() is suggested. You could just use fetchoneDict(); deprecated isn't the same as gone... > > Is there a recommended way to receive the results of an SQL query in > the form I need? Or do I have to create a dictionary of fieldname > tuples which can be zipped with the query result tuple? You can create a list of field names from the cursor.description attribute. But if the number of fields in the result varies how do you know which field goes with which description? Kent From lists at janeden.org Mon Aug 8 15:08:06 2005 From: lists at janeden.org (Jan Eden) Date: Mon, 8 Aug 2005 15:08:06 +0200 Subject: [Tutor] Fetching dictionaries using MySQLdb In-Reply-To: <42F742E6.7020900@tds.net> Message-ID: Kent Johnson wrote on 08.08.2005: >Jan Eden wrote: >>The documentation for MySQLdb says that fetchoneDict() is >>deprecated and the usage of fetchone() is suggested. > >You could just use fetchoneDict(); deprecated isn't the same as >gone... I tend to avoid deprecated functions/methods - I would need another method sooner or later anyway. >> >>Is there a recommended way to receive the results of an SQL query >>in the form I need? Or do I have to create a dictionary of >>fieldname tuples which can be zipped with the query result tuple? > >You can create a list of field names from the cursor.description >attribute. But if the number of fields in the result varies how do >you know which field goes with which description? > That works, thank you. I will use the cursor.description attribute immediately after executing a query, so it will contain the correct field descriptions whenever I need them. The rest of my program uses the type attribute to decide which fields are present and which are not. All this is part of a port from Perl to Python - I will publish a log of everything I encountered in a couple of weeks. Cheers, Jan -- There's no place like ~/ From dma8hm1956 at gmail.com Mon Aug 8 16:54:50 2005 From: dma8hm1956 at gmail.com (Hossein Movahhedian) Date: Mon, 8 Aug 2005 19:24:50 +0430 (IRST) Subject: [Tutor] Curses example on Linux? Message-ID: Hi All, I have copied the following example from "Learning to Program by Alan Gauld (section: Event Driven Programming)". To run it on Linux (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt' with 'curses.stdscr'. But there is no stdscr method in curses. In fact with 'import curses.stdscr' I get the following error message:: Traceback (most recent call last): File "", line 1, in ? ImportError: No module named stdscr How should I modify it for Linux? Thanks in advance, Hossein The example:{{{ import msvcrt def doKeyEvent(key): if key == '\x00' or key == '\xe0': # non ASCII key = msvcrt.getch() # fetch second character print ord(key) def doQuitEvent(key): raise SystemExit # First, clear the screen of clutter then warn the user # of what to do to quit lines = 25 # set to number of lines in console for line in range(lines): print print "Hit space to end..." print # Now mainloop runs "forever" while True: ky = msvcrt.getch() length = len(ky) if length != 0: # send events to event handling functions if ky == " ": # check for quit event doQuitEvent(ky) else: doKeyEvent(ky) }}} From carroll at tjc.com Mon Aug 8 18:00:34 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 8 Aug 2005 09:00:34 -0700 (PDT) Subject: [Tutor] raw string - solution to open_new() problem In-Reply-To: Message-ID: On Mon, 8 Aug 2005, Tom Cloyd wrote: > So, thie > > webbrowser.open_new("file://C:\__Library\folders\02394 Yale Style > Manual\02394 Yale_Style_Manual.htm") > > does not work, but this > > webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style > Manual\02394 Yale_Style_Manual.htm") I use forward slashes, it's simpler: webbrowser.open_new("file://C:/__Library/folders/02394 Yale Style Manual/02394 Yale_Style_Manual.htm") > Now, if anyone can explain why webbrowser.open_new() does the character > substitution thing it was doing (and thus becoming unable to locate the > file in question), I'm eager to hear it. Your original contains "\02394 Yale Style". "\023" equates to an octal 23 (hex 13, decimal 19), rather than looking for a directory named: 02394 Yale Style Manual It's looking for X94 Yale Style Manual Where "X" is actually a character with hex code 0x19. From tubaranger at gmail.com Mon Aug 8 18:04:19 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Mon, 8 Aug 2005 11:04:19 -0500 Subject: [Tutor] Shut up and deal! Message-ID: <57aa5506050808090450832d13@mail.gmail.com> I found the conversation of dealing cards interesting, so I took a few minutes (about 20 while I waited for a production run to finish) and came up with the following Dealer class. I come with a long history of coding in C/C++ and have been told my code looks like it (notice, in particular the nested "for" loops in the Shuffle method). What type of Pythonic changes would make this? What features would be nice? This was just for fun, so let's not take it too seriously! --greg - - - - Start Snippet - - - - - - - - - - #!/usr/bin/python from random import shuffle class Dealer(object): # define your deck here SUITS = ('Spades', 'Hearts', 'Clubs', 'Diamonds') RANKS = ('2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace') def __init__(self, decks=1, suits=SUITS, ranks=RANKS): self.number_of_decks = decks self.suits = suits self.ranks = ranks self.Shuffle() def Shuffle(self): self.deck = [] for deck in range(self.number_of_decks): for suit in self.suits: for rank in self.ranks: self.deck.append('%s of %s'%(rank,suit)) shuffle(self.deck) def Deal(self): '''Return the top card from the deck, or None if the deck is depleated''' if len(self.deck) > 0: card = self.deck[0] del self.deck[0] return card else: return None ############################################################################### ### Unit Test ################################################################# ############################################################################### if __name__ == '__main__': dealer = Dealer() for n in range(10): print dealer.Deal() - - - - End Snippet - - - - - Which yields: 2 of Clubs 7 of Diamonds 9 of Diamonds Ace of Diamonds Jack of Hearts King of Hearts 8 of Clubs King of Clubs 5 of Spades 3 of Hearts -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/348e960a/attachment-0001.htm From davholla2002 at yahoo.co.uk Mon Aug 8 18:53:16 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 8 Aug 2005 17:53:16 +0100 (BST) Subject: [Tutor] Using urllib to retrieve info Message-ID: <20050808165317.42896.qmail@web25402.mail.ukl.yahoo.com> Kent, Sorry I should have put my code. This is what I wrote import urllib import urllib2 f = urllib.urlopen("http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897").read() newfile = open("newfile.html",'w') newfile.write(f) newfile.close() print 'finished' It runs fine but the file saved to disk is the information at : 'http://support.mywork.co.uk' not 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897"' (By the way the real url is http://support.mywork.co.uk as I don't what my boss to know I am doing this, in case I can't not get it to work, in which case he will say a waste of time. Of course if I do get it to work it will not be a waste of time). The bizarre thing is that for an address like :- 'http://www.linuxquestions.org/questions/showthread.php?s=&threadid=316298'. It works okay. Does that make sense. Thanks everyone for the help so far. ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From kent37 at tds.net Mon Aug 8 19:37:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 13:37:18 -0400 Subject: [Tutor] Shut up and deal! In-Reply-To: <57aa5506050808090450832d13@mail.gmail.com> References: <57aa5506050808090450832d13@mail.gmail.com> Message-ID: <42F7984E.1030006@tds.net> Greg Lindstrom wrote: > I found the conversation of dealing cards interesting, so I took a few > minutes (about 20 while I waited for a production run to finish) and > came up with the following Dealer class. I come with a long history of > coding in C/C++ and have been told my code looks like it (notice, in > particular the nested "for" loops in the Shuffle method). What type of > Pythonic changes would make this? What features would be nice? This > was just for fun, so let's not take it too seriously! It looks pretty good to me; a couple of alternatives suggested below. Oh, and typical Python usage is to start method names with lower case letters, e.g. shuffle(), deal(). Kent > > --greg > > - - - - Start Snippet - - - - - - - - - - > #!/usr/bin/python > from random import shuffle > > class Dealer(object): > # define your deck here > SUITS = ('Spades', 'Hearts', 'Clubs', 'Diamonds') > RANKS = > ('2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace') > > def __init__(self, decks=1, suits=SUITS, ranks=RANKS): > self.number_of_decks = decks > self.suits = suits > self.ranks = ranks > self.Shuffle() > > def Shuffle(self): > self.deck = [] > for deck in range(self.number_of_decks): > for suit in self.suits: > for rank in self.ranks: > self.deck.append('%s of %s'%(rank,suit)) If you don't like the nested for you can use a generator expression with two 'for' clauses: deck.extend('%s of %s'%(rank,suit) for suit in self.suits for rank in self.ranks) though I think your version is clearer. > shuffle(self.deck) > > def Deal(self): > '''Return the top card from the deck, or None if the deck is > depleated''' > if len(self.deck) > 0: > card = self.deck[0] > del self.deck[0] > return card > else: > return None could be try: return self.deck.pop(0) except IndexError: return None Since you don't really care which end of the deck is dealt you could pop the end of the deck (use self.deck.pop()), that avoids having to move all the other cards down. From mosinu at earthlink.net Mon Aug 8 19:41:34 2005 From: mosinu at earthlink.net (Will Harris) Date: Mon, 8 Aug 2005 13:41:34 -0400 (GMT-04:00) Subject: [Tutor] while loops Message-ID: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> I am working my way through "python programming for the absolute beginner" and one of the challenges is to create a program that will flip a coin 100 times and tell you how many of each it did. Now I have it flipping the coin, but when I try to do this 100 times I end up with it running through 100 times, but always the same result comes back. It will either be 100 heads, or 100 tails. I have tried if statements and while loops and both seem to give me all or nothing. I am just looking for a hint at the direction to look of adjust to get the code below working not really the solution. Thanks in advanced for any tips. #!/usr/bin/python import random coin = random.randrange(2) count = 0 head_count = 0 tail_count = 0 while (count != 100): if coin == 0: print "You got Heads!" head_count = head_count + 1 count = count + 1 else: print "You got Tails!" tail_count = tail_count + 1 count = count + 1 print "Out of", count, "you flipped", head_count, "heads and ", tail_count, "tails" From kent37 at tds.net Mon Aug 8 19:48:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 13:48:42 -0400 Subject: [Tutor] Using urllib to retrieve info In-Reply-To: <20050808165317.42896.qmail@web25402.mail.ukl.yahoo.com> References: <20050808165317.42896.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <42F79AFA.7090904@tds.net> David Holland wrote: > Kent, > > Sorry I should have put my code. > This is what I wrote > import urllib > import urllib2 > f = > urllib.urlopen("http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897").read() > newfile = open("newfile.html",'w') > newfile.write(f) > newfile.close() > print 'finished' > > It runs fine but the file saved to disk is the > information at : 'http://support.mywork.co.uk' > not > 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897"' There is something strange with this site that has nothing to do with Python. Just playing around with the two URLs in Firefox I get different results by reloading the page. If I try loading the two URLs with curl, I get the same thing for both. Possibly there is something going on with cookies; you might take a look at urllib2 and its support for cookies to see if you can get it working the way you want. Kent From kent37 at tds.net Mon Aug 8 19:56:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Aug 2005 13:56:13 -0400 Subject: [Tutor] while loops In-Reply-To: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> References: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> Message-ID: <42F79CBD.2020900@tds.net> Will Harris wrote: > I am working my way through "python programming for the absolute > beginner" and one of the challenges is to create a program that will > flip a coin 100 times and tell you how many of each it did. Now I > have it flipping the coin, but when I try to do this 100 times I end > up with it running through 100 times, but always the same result > comes back. It will either be 100 heads, or 100 tails. I have tried > if statements and while loops and both seem to give me all or > nothing. I am just looking for a hint at the direction to look of > adjust to get the code below working not really the solution. Thanks > in advanced for any tips. You need to change the value of coin inside the loop. The code you have flips the coin once and reports the result 100 times. Kent > > #!/usr/bin/python > import random > > coin = random.randrange(2) > > count = 0 > head_count = 0 > tail_count = 0 > > while (count != 100): > if coin == 0: > print "You got Heads!" > head_count = head_count + 1 > count = count + 1 > else: > print "You got Tails!" > tail_count = tail_count + 1 > count = count + 1 > > print "Out of", count, "you flipped", head_count, "heads and ", tail_count, "tails" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From python at jayloden.com Mon Aug 8 15:58:38 2005 From: python at jayloden.com (Jay Loden) Date: Mon, 8 Aug 2005 13:58:38 +0000 Subject: [Tutor] while loops In-Reply-To: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> References: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> Message-ID: <200508081358.38863.python@jayloden.com> > coin = random.randrange(2) That's the problem there...you've got coin assigned outside the while loop, so it is assigned 0 or 1 once, before the loop, and then you're running 100 checks on the same value. If you move > coin = random.randrange(2) to inside the while loop before the if statement, you'll get the result you want. -Jay On Monday 08 August 2005 5:41 pm, Will Harris wrote: > I am working my way through "python programming for the absolute beginner" > and one of the challenges is to create a program that will flip a coin 100 > times and tell you how many of each it did. Now I have it flipping the > coin, but when I try to do this 100 times I end up with it running through > 100 times, but always the same result comes back. It will either be 100 > heads, or 100 tails. I have tried if statements and while loops and both > seem to give me all or nothing. I am just looking for a hint at the > direction to look of adjust to get the code below working not really the > solution. Thanks in advanced for any tips. > > #!/usr/bin/python > import random > > coin = random.randrange(2) > > count = 0 > head_count = 0 > tail_count = 0 > > while (count != 100): > if coin == 0: > print "You got Heads!" > head_count = head_count + 1 > count = count + 1 > else: > print "You got Tails!" > tail_count = tail_count + 1 > count = count + 1 > > print "Out of", count, "you flipped", head_count, "heads and ", tail_count, > "tails" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Aug 8 20:08:57 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 8 Aug 2005 19:08:57 +0100 Subject: [Tutor] raw string - solution to open_new() problem References: Message-ID: <016601c59c44$3f3da180$bea68651@xp> > webbrowser.open_new(r"file://C:\__Library\folders\02394 Yale Style > Manual\02394 Yale_Style_Manual.htm") > > does. > > Thank you Ewald, for triggering the solution in my mind! > > Now, if anyone can explain why webbrowser.open_new() does the > character substitution thing it was doing (and thus becoming unable > to locate the file in question), I'm eager to hear it. It's not the function that does it, it's Python itself. If you just try using print for the two values(with and without 'r') you will see the same effect. It's standard Python string handling. Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 20:11:43 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 11:11:43 -0700 (PDT) Subject: [Tutor] use of webbrowser.open_new() In-Reply-To: Message-ID: > > http://www.faqs.org/rfcs/rfc1738.html > > > > shows the syntax of file URLs. > > Man, that Berners-Lee can sure write plain English, can he not? I didn't > find that reference much use at all, in truth. Hi Tom, [Note: when you're responding to a message on Python-tutor, please make sure to CC to the mailing list too.] It's meant to be a bit terse. The second on file urls isn't too bad though. Here, let's take a closer look at it: """ The file URL scheme is used to designate files accessible on a particular host computer. This scheme, unlike most other URL schemes, does not designate a resource that is universally accessible over the Internet. A file URL takes the form: file:/// where is the fully qualified domain name of the system on which the is accessible, and is a hierarchical directory path of the form //.../. As a special case, can be the string "localhost" or the empty string; this is interpreted as `the machine from which the URL is being interpreted'. """ According to the file URL spec, you need to use forward slashes, not back slashes, when defining the subdirectory path. Your web browser might be nice enough to try to account for backslashes, but it's not standard. That's why the reference is relevant: it tells how to write out file urls so that any web browser that follows the standard will do the right thing. > webbrowser.open_new("file://C:\www\02394-Yale_Style_Manual.htm") Here's a possible correction: webbrowser.open_new("file:///C:/www/02394-Yale_Style_Manual.htm") We need three forward slashes in front of 'file:' because, in the file URL: file:/// we're leaving the host part empty to say that we're looking at a local file (last paragraph of the quoted section above), and forward slashes instead of backslashes, since that's what the spec says. *grin* But even more importantly: backslashes in string literals are special. You may have seen something like this before: ###### >>> print "hello\tworld\nthis is a\ntest" hello world this is a test ###### That the backslash starts an "escape character". "\t" stands for the tab character, and "\n" stands for the newline character. This is relevant to your problem because "\0239" stands for another escaped character. For more details on these escape sequences, see: http://www.python.org/doc/ref/strings.html Quickest way to fix this: don't use backslashes! *grin* Use forward slashes instead. Backslashes in string literals are special, and we have to take special care for them. If we do want to put a literal backslash in our string, we have to double the backslashes up: ###### >>> s = "hello\\world" >>> print s hello\world ###### but it's often just simpler just to use forward slashes for paths instead. Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 20:19:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 11:19:02 -0700 (PDT) Subject: [Tutor] Fetching dictionaries using MySQLdb In-Reply-To: Message-ID: On Mon, 8 Aug 2005, Jan Eden wrote: > Is there a recommended way to receive the results of an SQL query in the > form I need? Or do I have to create a dictionary of fieldname tuples > which can be zipped with the query result tuple? Hi Jan, MySQLdb supports the concept of customized cursor types. They have a particular cursor class that returns dictionary objects: ###### >>> import MySQLdb >>> import MySQLdb.cursors >>> MySQLdb.cursors.DictCursor ###### When we construct a connection object, we can tell MySQL to construct those kind of custom cursors by default: ###### >>> conn = MySQLdb.connect(db='test_adb', ... cursorclass=MySQLdb.cursors.DictCursor) >>> cursor = conn.cursor() >>> cursor.execute("""select name, start_coordinate, ... end_coordinate ... from BAC""") 1624L >>> >>> cursor.fetchone() {'name': 'F10A5', 'end_coordinate': 28462975L, 'start_coordinate': 28333429L} >>> cursor.fetchone() {'name': 'T12M4', 'end_coordinate': 3002250L, 'start_coordinate': 2942990L} >>> cursor.fetchone() {'name': 'T12I7', 'end_coordinate': 24869607L, 'start_coordinate': 24834300L} ###### Good luck! From rabidpoobear at gmail.com Mon Aug 8 20:20:29 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 8 Aug 2005 13:20:29 -0500 Subject: [Tutor] deck dealing program References: <004201c59be3$c15805e0$aa0ca8c0@luke> <200508080302.10003.python-tutor@toddmaynard.com> Message-ID: <000701c59c45$dc45de10$aa0ca8c0@luke> Just offering my take on the problem. hope it helps someone. ----- Original Message ----- From: To: Sent: Monday, August 08, 2005 2:02 AM Subject: Re: [Tutor] deck dealing program > Are you: > a.) Having trouble with the code and looking for help? > b.) Looking for suggestions on how to improve the code? > c.) Offering the code as a demo for Nathan et al.? > > I was just doing stuff along the same lines and was having fun seeing the > different approaches to the same problem. > > --Todd > > On Monday 08 August 2005 02:38 am, luke wrote: > > from random import randint > > > > def identify_card(n): > > cardname = "" > > royals = ["Jack","Queen","King","Ace"] > > temp = n % 13 > > if temp > 8: > > cardname += royals[temp-9] > > else: > > cardname += str(temp+2) > > cardname += " of " > > > > suits = ["Spades","Hearts","Diamonds","Clubs"] > > cardname += suits[n/13] > > return cardname > > > > def main(): > > deck = range(52) > > cards = [] > > while 1: > > x = raw_input("how many cards do you want? ") > > try: > > x = int(x) > > except ValueError: > > print "Invalid value exiting for I have no error code. Please > > use an int next time." raise SystemExit > > if x <= 52 and x >= 0: > > y = 0 > > while y < x: > > > > cards.append(identify_card(deck.pop(randint(0,len(deck)-1)))) y += 1 > > break > > print cards > > if __name__ == "__main__": > > main() > > > > #Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 20:27:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 11:27:02 -0700 (PDT) Subject: [Tutor] Curses example on Linux? In-Reply-To: Message-ID: On Mon, 8 Aug 2005, Hossein Movahhedian wrote: > I have copied the following example from "Learning to Program by Alan > Gauld (section: Event Driven Programming)". To run it on Linux > (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt' > with 'curses.stdscr'. Hi Hossein, According to: http://www.amk.ca/python/howto/curses/ Alan probably meant to say to replace: ###### import msvcrt ###### with: ###### import curses msvcrt = curses.initscr() ###### as a quick hack to replace 'msvcrt' with something that works on Linux. It sounded that you wanted to look at other examples of curses programming? A long time ago, I wrote a quick-and-dirty demo program that uses curses here: http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py Good luck to you! From alan.gauld at freenet.co.uk Mon Aug 8 20:33:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 8 Aug 2005 19:33:21 +0100 Subject: [Tutor] Using urllib to retrieve info References: <20050808165317.42896.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <019101c59c47$a8757c10$bea68651@xp> > It runs fine but the file saved to disk is the > information at : 'http://support.mywork.co.uk' > not > 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897"' Could there be cookies involved? Just a thought, Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Aug 8 20:45:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 11:45:51 -0700 (PDT) Subject: [Tutor] Shut up and deal! In-Reply-To: <57aa5506050808090450832d13@mail.gmail.com> Message-ID: On Mon, 8 Aug 2005, Greg Lindstrom wrote: > I found the conversation of dealing cards interesting, so I took a few > minutes (about 20 while I waited for a production run to finish) and > came up with the following Dealer class. [text cut] > What type of Pythonic changes would make this? What features would be > nice? Hi Greg, For your program, it can make sense to treat the Cards themselves as a class, rather than have them be just a string representation of a card. Something like this: ###### class Card: def __init__(self, suit, rank): self.suit, self.rank = suit, rank ###### might work because then we can treat Cards as a separate data type. One advantage is that we can then later extract the rank or suit out of the card without having to do any string manipulation. If we still want to make it easy to get a string representation of these cards, we can add an __str__() method to the Card class definition. There's often a temptation to make everything a string because we're comfortable with them, but sometimes that representation choice makes things hard on ourselves when we're doing more than pure string manipulation. Hope this helps! From alan.gauld at freenet.co.uk Mon Aug 8 21:07:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 8 Aug 2005 20:07:37 +0100 Subject: [Tutor] What's the invalid syntax? Code supplied References: <00aa01c59b74$c3f879c0$bea68651@xp> Message-ID: <019d01c59c4c$716291e0$bea68651@xp> Nathan, > I'm no longer going to use this method. I thought up a more easier > idea for dealing cards. I was going to share it, but with all this > time and effort pointing out things that I should know, instead of > helping me, I don't think I will, because it will probably be ripped > to shreds by you, and dash my idea before it even takes off. Now I've had some sleep I'll try to be a little kinder. I was not trying to 'rip you to shreds' but to help you. But you are not helping us to help you by posting code that is full of basic syntax errors. Try to fix those yourself and if you get stuck tell us what the problem is and include the error text. Python does very well at printing useful error messages, without which we are left having to read your code line by line. This means we don't know whether you are looking for a new approach, help with the syntax, or just general comments. Many of the mistakes you are making are covered in the various tutorials that are on the web, some time spent reading those will avoid many of the problems you are encountering. And reading documentation is an essential skill for any programmer to learn. While the mailing list is here to help newbies to Python and programming we are all volunteers doing this in our own time. We are happy to help folks who are stuck, we just ask for some help in that you give us as much specific information about the help you need as possible. A subject line saying 'it doesn't work' and a screen full of code is not enough. > I wanted help, and you critised me, > I wanted aid, and you refused, > So I will do it myself! No-one has refused you, but doing it by yourself is a big part of learning and no bad thing. You have made some progress since you started posting to the list, but you could progress faster by paying more attention to the basics. The list is best used for the times when you are unable to make any further progress by yourself. As I said in my post yesterday we are trying to help you to help yourself. I'm sorry if my words sounded harsh but they were borne out of seeing a posting with no clue as to the problem but full of basic syntax errors. And maybe it could have been expressed more subtly but having returned from 3 long days I was not in the mood for sweet talking! :-( Sorry if it offended, it was not meant so to do. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lists at janeden.org Mon Aug 8 21:26:36 2005 From: lists at janeden.org (Jan Eden) Date: Mon, 8 Aug 2005 21:26:36 +0200 Subject: [Tutor] Fetching dictionaries using MySQLdb In-Reply-To: Message-ID: Hi Danny, Danny Yoo wrote on 08.08.2005: >On Mon, 8 Aug 2005, Jan Eden wrote: > >>Is there a recommended way to receive the results of an SQL query >>in the form I need? Or do I have to create a dictionary of >>fieldname tuples which can be zipped with the query result tuple? > > >Hi Jan, > >MySQLdb supports the concept of customized cursor types. They have >a particular cursor class that returns dictionary objects: Great! I found the pydoc for MySQLdb a bit confusing and would probably have taken quite a while to figure that out - thanks a lot. - Jan -- Any technology which is distinguishable from magic is insufficiently advanced. From cpu.crazy at gmail.com Mon Aug 8 16:22:42 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 08 Aug 2005 08:22:42 -0600 Subject: [Tutor] IP Address from Python module? In-Reply-To: References: Message-ID: <42F76AB2.80406@gmail.com> Danny Yoo wrote: >Hi Joe, > >That actually sounds right in a sense. Any internet address with >'192.168.x.x' is a "local" IP address, and is commonly allocated to folks >on an internal network. For the really dull details about this, see RFC >1918 on "Private Address Space": > > http://www.faqs.org/rfcs/rfc1918.html > >So anything with 192.168.x.x is a private, internal address. In the >context of the Internet, it's sorta useless, since it's not an address >that one can use to connect to an external machine outside of the local >area network. > >In fact, Brian Hammon's comment in: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 > >does mention that if you're behind a router, then the router itself sets >up a small private network, which may explain why you may be seeing >'192.168.x.x' as an address. > >The second comment on the cookbook page shows an alternative technique >that should be more robust: use http://checkip.dyndns.org. > > > > > >>My internet IP should be IPv6 and I don't think it changes... >> >> > >Are you sure about that? IPv6 has not been widely deployed yet; most >folks still connect to the internet through the IPv4 protocol. > >On the off-chance that you ARE on IPv6, see the getaddrinfo() function, >which should accomodate: > > http://www.python.org/doc/lib/module-socket.html#l2h-2592 > >For example: > >###### > > >>>>import socket >>>>socket.getaddrinfo('hkn.eecs.berkeley.edu', 80) >>>> >>>> >[(2, 1, 6, '', ('128.32.47.228', 80)), > (2, 2, 17, '', ('128.32.47.228', 80))] >###### > > >Good luck to you! > > > > Thank you. And thank you for the links. Well I remember something on a game I played and it had a IPv6 address (refering to my computer while o nthe internet).. of course I bought my computer parts in October 2004 so there could be a good chance that I do not have IPv6... either way, thanks. :-) Oh and I don't have a router... just a good old-fashioned CAT5 hub. Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/4a3f325f/attachment.htm From mosinu at earthlink.net Mon Aug 8 23:49:52 2005 From: mosinu at earthlink.net (Will Harris) Date: Mon, 08 Aug 2005 17:49:52 -0400 Subject: [Tutor] while loops In-Reply-To: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> References: <8025945.1123522895062.JavaMail.root@elwamui-little.atl.sa.earthlink.net> Message-ID: <42F7D380.9050205@earthlink.net> Thanks for the help guys. From Liam.Clarke-Hutchinson at business.govt.nz Mon Aug 8 23:40:56 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 9 Aug 2005 09:40:56 +1200 Subject: [Tutor] Using urllib to retrieve info Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A5ED@chbnt01.alpha.wd.govt.nz> Hi all, David, are you able to send us a screen shot of what you're trying to get? >From your desired link I just get a bunch of ads with another ad telling me it's for sale. When I open http://support.mywork.co.uk it looks exactly the same as http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objec tid=21897 So yah, are there cookies, it looks like the site lost it's domain to me. You may also find that urllib's User Agent setting causes some sites to flat out spit the dummy. Try google.com with urllib without changing the user agent, google gets all huffy when rival bots attempt to spider it. I believe you can change the User-Agent using urllib, so you can easily masquerade as Internet Explorer or a Mozilla browser. >From http://docs.python.org/lib/module-urllib.html """ By default, the URLopener class sends a User-Agent: header of "urllib/VVV", where VVV is the urllib version number. Applications can define their own User-Agent: header by subclassing URLopener or FancyURLopener and setting the class attribute version to an appropriate string value in the subclass definition. """ That's another caveat when using urllib. But yeah, digression aside, short answer is, I think your specified resource is dead, and a url-camper has taken all urls for that site and redirected them to a pop-up fest. Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Alan G Sent: Tuesday, 9 August 2005 6:33 a.m. To: David Holland; tutor python Subject: Re: [Tutor] Using urllib to retrieve info > It runs fine but the file saved to disk is the > information at : 'http://support.mywork.co.uk' > not > 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=2039 > 7&objectid=21897"' Could there be cookies involved? Just a thought, Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From danf_1979 at yahoo.es Tue Aug 9 01:28:42 2005 From: danf_1979 at yahoo.es (_ Dan _) Date: Tue, 9 Aug 2005 01:28:42 +0200 (CEST) Subject: [Tutor] NotebookSizer is no longer needed In-Reply-To: Message-ID: <20050808232843.16263.qmail@web25201.mail.ukl.yahoo.com> Hi... Well, I'm working on Gui programs with wxglade. On MS Windows I'm getting the following message: "DeprecationWarning: NotebookSizer is no longer needed" No message on Linux... and, if I remove the notebook sizer, then I cannot put any notebook at all, so I'm kind of lost in here... Anybody knows about this? :( My tree is like: Frame_1 Sizer_1 Notebook_1 Note_book_pane_1 Note_book_pane_2 So the Sizer_1 would be the "NotebookSizer". If I remove it, then I can't place a notebook, at least in wxglade. Anyhow, I know very little about wxpython... >From Chile, Daniel. ______________________________________________ Renovamos el Correo Yahoo! Nuevos servicios, m?s seguridad http://correo.yahoo.es From rdm at rcblue.com Tue Aug 9 01:33:05 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Aug 2005 16:33:05 -0700 Subject: [Tutor] problem with Python Tutorial Message-ID: <6.2.1.2.2.20050808162427.09660d00@rcblue.com> Quoting from "6.2 Standard Modules", of the Python Tutorial (): ================================== One particular module deserves some attention: sys, which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts: >>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = 'C> ' C> print 'Yuck!' Yuck! C> These two variables are only defined if the interpreter is in interactive mode. ========end of quote=================== I tried this with IDLE: >>> import sys >>> sys.ps1 Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps1 AttributeError: 'module' object has no attribute 'ps1' >>> sys.ps2 Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' What's wrong? Thanks, Dick Moores From moparfan90 at gmail.com Tue Aug 9 01:48:12 2005 From: moparfan90 at gmail.com (Dan Deternova) Date: Mon, 8 Aug 2005 19:48:12 -0400 Subject: [Tutor] help Message-ID: <9560d3c05080816487b0b46c2@mail.gmail.com> i am making a simple script to get the hang of Tkinter. i want to use the input of the user from a Entry and calcuate the area. i have tryied many way... as you can see in my script. the Entry is under def area(): and the output i want is under def cal(): ... please help me fix my code and explain to me what you did.. thanks in advance. ~moparfan90 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050808/0508be4c/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Tkinter program 1.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20050808/0508be4c/Tkinterprogram1.diff From dyoo at hkn.eecs.berkeley.edu Tue Aug 9 01:57:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 16:57:32 -0700 (PDT) Subject: [Tutor] problem with Python Tutorial In-Reply-To: <6.2.1.2.2.20050808162427.09660d00@rcblue.com> Message-ID: > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > > What's wrong? IDLE doesn't use sys.ps2. See the thread starting at: http://mail.python.org/pipermail/idle-dev/2002-February/000862.html From danf_1979 at yahoo.es Tue Aug 9 02:02:06 2005 From: danf_1979 at yahoo.es (_ Dan _) Date: Tue, 9 Aug 2005 02:02:06 +0200 (CEST) Subject: [Tutor] NotebookSizer is no longer needed Message-ID: <20050809000215.91360.qmail@web25205.mail.ukl.yahoo.com> There is a good chance I got it all wrong... ______________________________________________ Renovamos el Correo Yahoo! Nuevos servicios, m?s seguridad http://correo.yahoo.es -------------- next part -------------- An embedded message was scrubbed... From: _ Dan _ Subject: NotebookSizer is no longer needed Date: Tue, 9 Aug 2005 01:28:42 +0200 (CEST) Size: 1206 Url: http://mail.python.org/pipermail/tutor/attachments/20050809/47464c50/attachment.eml From rdm at rcblue.com Tue Aug 9 02:36:26 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Aug 2005 17:36:26 -0700 Subject: [Tutor] problem with Python Tutorial In-Reply-To: References: <6.2.1.2.2.20050808162427.09660d00@rcblue.com> Message-ID: <6.2.1.2.2.20050808173514.042c3e20@rcblue.com> Danny Yoo wrote at 16:57 8/8/2005: > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > sys.ps2 > > AttributeError: 'module' object has no attribute 'ps2' > > > > What's wrong? > > >IDLE doesn't use sys.ps2. See the thread starting at: > > http://mail.python.org/pipermail/idle-dev/2002-February/000862.html Thanks, Danny. Should that info be added to the tutorial? Dick From rdm at rcblue.com Tue Aug 9 06:41:37 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Aug 2005 21:41:37 -0700 Subject: [Tutor] function won't import from module Message-ID: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> I have a bunch of functions I've collected in one script, "mycalc.py", which I use as a module, "mycalc". The last one I wrote, cmpSeq() is as follows: ===========begin code============== def cmpSeq(seq1, seq2): """ find first index at which two sequences differ """ if seq1 == seq2: print "Sequences are identical, and of length %d" % len(seq1) return None if len(seq1) >= len(seq2): shorterOrEqualSequence = seq2 else: shorterOrEqualSequence = seq1 for index in range(len(shorterOrEqualSequence)): if seq1[index] != seq2[index]: print "sequences first differ at index", index print "seq1[%d] = %s" % (index, seq1[index]) print "seq2[%d] = %s" % (index, seq2[index]) break if index == len(shorterOrEqualSequence)-1: print "sequences are identical thru end of shorter sequence at index", index print "len(seq1) =", len(seq1) print "len(seq2) =", len(seq2) ========end code for cmpSeq()========= In a script, cmpSeq() works fine. For example followed by a = "qwertys" b = "qxerty" cmpSeq(a,b) The output is: sequences first differ at index 1 seq1[1] = w seq2[1] = x len(seq1) = 7 len(seq2) = 6 cmpSeq() is now copy-pasted into mycalc.py, but is not useable there: #testof_cmpSeq.py import mycalc a = "qwerty" b = "qxerty" mycalc.cmpSeq(a,b) which produces: Traceback (most recent call last): File "C:\Python24\MyScripts\testof_cmpSeq.py", line 1, in -toplevel- from mycalc import cmpSeq ImportError: cannot import name cmpSeq However, other functions in mycalc work fine. For example: #testof_print_hms import mycalc seconds = 87658 mycalc.print_hms(seconds) This outputs 24 hours, 20 minutes, 58 seconds That may have been a bit long-winded; if so, I apologize. But would someone please point out why cmpSeq() can't be imported from mycalc? Thanks, Dick Moores From dyoo at hkn.eecs.berkeley.edu Tue Aug 9 06:42:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Aug 2005 21:42:17 -0700 (PDT) Subject: [Tutor] problem with Python Tutorial In-Reply-To: <6.2.1.2.2.20050808173514.042c3e20@rcblue.com> Message-ID: On Mon, 8 Aug 2005, Dick Moores wrote: > Danny Yoo wrote at 16:57 8/8/2005: > > > Traceback (most recent call last): > > > File "", line 1, in -toplevel- > > > sys.ps2 > > > AttributeError: 'module' object has no attribute 'ps2' > > > > > > What's wrong? > > > > > >IDLE doesn't use sys.ps2. See the thread starting at: > > > > http://mail.python.org/pipermail/idle-dev/2002-February/000862.html > > Thanks, Danny. Should that info be added to the tutorial? It can't hurt (much) to send a ping off to the documentation folks and see if they can add a note about it in the tutorial. Send a message off to the docs at python.org folks about it. From javier at ruere.com.ar Tue Aug 9 08:22:32 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue, 09 Aug 2005 03:22:32 -0300 Subject: [Tutor] function won't import from module In-Reply-To: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> References: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> Message-ID: Dick Moores wrote: > I have a bunch of functions I've collected in one script, "mycalc.py", > which I use as a module, "mycalc". The last one I wrote, cmpSeq() is as > follows: > [code] > > In a script, cmpSeq() works fine. For example followed by > [example] > > The output is: > [output] > > cmpSeq() is now copy-pasted into mycalc.py, but is not useable there: > [example] > > which produces: > [Traceback] > > However, other functions in mycalc work fine. For example: > [example] > > That may have been a bit long-winded; if so, I apologize. Not at all! :) I couldn't reproduce the error. The problem is not in the given code then. Use PyChecker or PyLint to aid you find the problem. Other comments: Instead of: for index in range(len(shorterOrEqualSequence)): if seq1[index] != seq2[index]: prints... break if index == len(shorterOrEqualSequence)-1: print "sequences are identical thru end of shorter sequence at index", index this could be used: for index in range(len(shorterOrEqualSequence)): if seq1[index] != seq2[index]: prints... break else: print "sequences are identical thru end of shorter sequence at index", index And instead of: if len(seq1) >= len(seq2): shorterOrEqualSequence = seq2 else: shorterOrEqualSequence = seq1 for index in range(len(shorterOrEqualSequence)): etc. this could be used: for index in xrange(min(len(seq1), len(seq2))): etc. The main loop, I would write it like this: from itertools import izip, count def cmpSeq(seq1, seq2): """ find first index at which two sequences differ """ if seq1 == seq2: print "Sequences are identical, and of length %d" % len(seq1) return None for i, ca, cb in izip(count(), seq1, seq2): if ca != cb: print "sequences first differ at index", index print "seq1[%d] = %s" % (index, seq1[index]) print "seq2[%d] = %s" % (index, seq2[index]) break else: print "sequences are identical thru end of shorter sequence at index", i Javier From alan.gauld at freenet.co.uk Tue Aug 9 09:29:26 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 08:29:26 +0100 Subject: [Tutor] Curses example on Linux? References: Message-ID: <01d801c59cb4$132538e0$bea68651@xp> >> I have copied the following example from "Learning to Program by >> Alan >> Gauld (section: Event Driven Programming)". To run it on Linux >> (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt' >> with 'curses.stdscr'. I thought I'd fixed that fault. The sequence should be: import curses mscvrt = curses.initscr() mscvcrt.getch() I will make the changes and upload the fixed file as soon as possible. Thanks for bringing it up. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > > > Hi Hossein, > > > According to: > > http://www.amk.ca/python/howto/curses/ > > > Alan probably meant to say to replace: > > ###### > import msvcrt > ###### > > with: > > ###### > import curses > msvcrt = curses.initscr() > ###### > > as a quick hack to replace 'msvcrt' with something that works on > Linux. > > > It sounded that you wanted to look at other examples of curses > programming? A long time ago, I wrote a quick-and-dirty demo > program that > uses curses here: > > http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py > > > Good luck to you! > > > From alan.gauld at freenet.co.uk Tue Aug 9 09:42:51 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 08:42:51 +0100 Subject: [Tutor] function won't import from module References: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> Message-ID: <020b01c59cb5$f2eb55d0$bea68651@xp> Dick, I can't see a problem but I notice an inconsistency below: > #testof_cmpSeq.py > import mycalc > which produces: > > Traceback (most recent call last): > File "C:\Python24\MyScripts\testof_cmpSeq.py", line 1, > in -toplevel- > from mycalc import cmpSeq > ImportError: cannot import name cmpSeq In the code snippet you claim to use import mycalc but the error suggests you used 'from mycalc import cmpSeq'. I don't know which is correct and they should both work, but it might be worth checking if it makes a difference. Also was it a freshj interpreter session or was your interactive version of cmpSeq sttill around? Again it shouldn't have been a problem but... > #testof_print_hms > import mycalc > > seconds = 87658 > mycalc.print_hms(seconds) Whereas here you are definitely using import mycalc. Did you do this after adding cmpSeq? If so it would appear that Python is happy with the function definition. Did you try calling mycalc.cmpSeq in this same session? Clutching at straws... Alan G. From alan.gauld at freenet.co.uk Tue Aug 9 10:02:03 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 09:02:03 +0100 Subject: [Tutor] help References: <9560d3c05080816487b0b46c2@mail.gmail.com> Message-ID: <021701c59cb8$a13ef360$bea68651@xp> Hi Dan, I think you need to back up a little and build the program piece by piece. > i am making a simple script to get the hang of Tkinter. The script is quite complex for a starter. You could focus down on just a single control initially, the area button. Get that to pop up the dialog and read the numbers. Have a button on that to do the calculation and display the result. Only once you get that working expand the UI to have the other operations. That way you can focus on one problem at a time. Now in your code: First you have some very long lines, they wouldn't even fit on my screen at 1200x1000 resolution! Either move the comments before the lines they describe or 'fold' the function parameters foo(param1, param2, param3): code here It might seem cosmetic but in a language like Python where indentation is critical it can make a big difference in spotting simple mistakes. Second you use pack() in your widget creation code: w = foo(....).pack() w will always hold NOne because pack returns None. You need top do it in two steps: w = foo(....) w.pack() An annoying foible of Tkinter which catches most folks at some point. Thirdly you need to pass parameters in and return values out of your functions to ebnable communication between you different windows. Either that or use global variables but that gets messy very quickly. You probably need to use some globals because you are not using OOP yet but the way the code is just now the dialog functions cannot see the toplevel window controls and vice versa. Finally I'm not sure what cal() is doing: def cal(): win4 = Toplevel <------ Huh??? print 'area = ', 'w'*'h' The win4 line assigns a local(to cal() ) variable to the 'TopLevel' Tkinter function but then does nothing with it. WE then try to print the result of multiplying two strings together, which is an invalid operation. I assume you wanted w*h where w and h are the valuesset in area() but those are hidden inside area(). You need to either pass them to cal() as parameters or make them global. Also printing will try to display the result on a console window, but by naming the script .pyw there will be no console so you won't see the output! Again you probably need to use a global Label control and set the text proprty to the result. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From davholla2002 at yahoo.co.uk Tue Aug 9 09:57:15 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue, 9 Aug 2005 08:57:15 +0100 (BST) Subject: [Tutor] Using urllib to retrieve info In-Reply-To: <019101c59c47$a8757c10$bea68651@xp> Message-ID: <20050809075715.28612.qmail@web25407.mail.ukl.yahoo.com> Alan, Sorry of course that is the problem. These pages are password protected !!!! Is it possible to download password protected pages (I know the password but I don't how to get the program to use it). David --- Alan G wrote: > > It runs fine but the file saved to disk is the > > information at : 'http://support.mywork.co.uk' > > not > > > 'http://support.mywork.co.uk/index.php?node=2371&pagetree=&fromid=20397&objectid=21897"' > > Could there be cookies involved? > > Just a thought, > > Alan G. > > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From alan.gauld at freenet.co.uk Tue Aug 9 10:06:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 09:06:37 +0100 Subject: [Tutor] Using urllib to retrieve info References: <20050809075715.28612.qmail@web25407.mail.ukl.yahoo.com> Message-ID: <021d01c59cb9$44890380$bea68651@xp> > Sorry of course that is the problem. These pages are > password protected !!!! > Is it possible to download password protected pages (I > know the password but I don't how to get the program > to use it). That will depend on how the protection is implemented. If your server is a J2EE box with full blown Kerberos security it may be almost impossible. If it's a more conventional server like apache which is protecting a file or folder then you may only have to submit the username and password - ie login! - or build that into a cookie. If the protection is done by the application itself then it could be anywhere in between those two extremes. HTH, Alan G. From dma8hm1956 at gmail.com Tue Aug 9 11:01:42 2005 From: dma8hm1956 at gmail.com (Hossein Movahhedian) Date: Tue, 9 Aug 2005 13:31:42 +0430 (IRST) Subject: [Tutor] Curses example on Linux? In-Reply-To: References: Message-ID: Dear Danny Hi, Many thanks for your help and especially the references in your reply. Now the code works fine. BTW, I had to replace "ky = msvcrt.getch()" with "ky = chr(msvcrt.getch())". Regards, Hossein On Mon, 8 Aug 2005, Danny Yoo wrote: > > > On Mon, 8 Aug 2005, Hossein Movahhedian wrote: > > > I have copied the following example from "Learning to Program by Alan > > Gauld (section: Event Driven Programming)". To run it on Linux > > (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt' > > with 'curses.stdscr'. > > > Hi Hossein, > > > According to: > > http://www.amk.ca/python/howto/curses/ > > > Alan probably meant to say to replace: > > ###### > import msvcrt > ###### > > with: > > ###### > import curses > msvcrt = curses.initscr() > ###### > > as a quick hack to replace 'msvcrt' with something that works on Linux. > > > It sounded that you wanted to look at other examples of curses > programming? A long time ago, I wrote a quick-and-dirty demo program that > uses curses here: > > http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py > > > Good luck to you! > From tomcloyd at bestmindhealth.com Tue Aug 9 11:10:37 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Tue, 09 Aug 2005 02:10:37 -0700 Subject: [Tutor] surprising len() results ??? Message-ID: List, I'm running a program I wrote which I've run a number of times before, successfully. I use the following statement to fix the problem of utf-8 codes which blow up a later part of my production process that I cannot fix: trans_table = maketrans('()??????????????????????????','--AaAAaaCcEEeeIIiiNnOOooUUuu') As I said, this has been working fine. But no longer. I previously have been running the ActivePython-2.4.1-247-win32 Python from ActiveState, and executing my program in ActiveState's Komodo IDE. Due to some problems with the Boa Constructor IDE, I removed ActivePython and ran the Python 2.4.1 Windows installer from python.org. I mention this because I'm wondering if this might be behind my problem. I'm still running from within Komodo. Today, when running my program, when execution gets to the maketrans() function above, I get: Traceback (most recent call last): File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 1799, in runMain self.dbg.runfile(debug_args[0], debug_args) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 1524, in runfile h_execfile(file, args, module=main, tracer=self) File "C:\Program Files\ActiveState Komodo 3.1\dbgp\pythonlib\dbgp\client.py", line 590, in __init__ execfile(file, globals, locals) File "C:\Documents and Settings\Tom C\My Documents\Python projects - Toms\li-database\LI-db-use--dict_db.py", line 49, in __main__ trans_table = maketrans('()??????????????????????????','--AaAAaaCcEEeeIIiiNnOOooUUuu') ValueError: maketrans arguments must have same length This makes no sense to me. So, I then broke up the maketrans() function statement's two parameters, and ran these two statements from within the program: print len('()??????????????????????????') print len('--AaAAaaCcEEeeIIiiNnOOooUUuu') the result: 54 28 I'm completely mystified by this. All of it. None of it makes sense. This program was working fine. Now it doesn't. And those two parameter string are plainly the same length, but Python doesn't think so. All help will be gratefully accepted! -- t. ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com / tc at bestmindhealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From rdm at rcblue.com Tue Aug 9 11:35:04 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Aug 2005 02:35:04 -0700 Subject: [Tutor] function won't import from module In-Reply-To: <020b01c59cb5$f2eb55d0$bea68651@xp> References: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> <020b01c59cb5$f2eb55d0$bea68651@xp> Message-ID: <6.2.1.2.2.20050809020317.06820d50@rcblue.com> Alan G wrote at 00:42 8/9/2005: >Dick, > >I can't see a problem but I notice an inconsistency below: > >>#testof_cmpSeq.py >>import mycalc > >>which produces: >> >>Traceback (most recent call last): >> File "C:\Python24\MyScripts\testof_cmpSeq.py", line 1, in -toplevel- >> from mycalc import cmpSeq >>ImportError: cannot import name cmpSeq > >In the code snippet you claim to use import mycalc but the error >suggests you used 'from mycalc import cmpSeq'. > >I don't know which is correct and they should both work, but it might >be worth checking if it makes a difference. > >Also was it a freshj interpreter session or was your interactive >version of cmpSeq sttill around? Again it shouldn't have been a >problem but... > >>#testof_print_hms >>import mycalc >> >>seconds = 87658 >>mycalc.print_hms(seconds) > >Whereas here you are definitely using import mycalc. > >Did you do this after adding cmpSeq? If so it would appear that >Python is happy with the function definition. Did you try calling >mycalc.cmpSeq in this same session? > >Clutching at straws... > >Alan G. Yes, I now see the inconsistencies in my post. But they don't accurately reflect what I actually did. Sorry. I went back and checked and still got errors. I tried deleting a mycalc.pyc that had been created and the problem cleared up! If I remember correctly, for a while I had moved mycalc.py to another folder in PYTHONPATH (I had recently learned how to modify PYTHONPATH in Win XP), and the .pyc was in this folder. Sorry I don't remember clearly. But what is clear is the problem cleared up immediately after deleting the .pyc. Does this make sense? Showing mycalc is OK now: IDLE 1.1 >>> from mycalc import cmpSeq >>> a = range(1,1000) >>> b = range(1,1000) >>> cmpSeq(a,b) Sequences are identical, and of length 999 >>> b[500] = 13 >>> cmpSeq(a,b) sequences first differ at index 500 seq1[500] = 501 seq2[500] = 13 len(seq1) = 999 len(seq2) = 999 Now I'll begin to ponder the suggestions made by Javier Ruere. Dick From jorge at bcs.org.uk Tue Aug 9 12:18:54 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Tue, 9 Aug 2005 11:18:54 +0100 Subject: [Tutor] Tkinter Menus Message-ID: Hello, I'm having this issue with Tkinter. I have a frame with all my buttons, checkboxes et al, and all is working fine. I want to add menus and added the following to my frame (fCanvas) code: # create a toplevel menu menu = Menu(fCanvas) fCanvas.config(menu=menu) # create a pulldown menu, and add it to the menu bar filemenu = Menu(menu, tearoff=0) filemenu.add_command(label="Open", command=self.doBrowse) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.doQuit) menu.add_cascade(label="File", menu=filemenu) # create analyze pulldown menu analyzemenu = Menu(menu, tearoff=0) analyzemenu.add_command(label="Start", command=self.doStart) analyzemenu.add_command(label="Reset", command=self.doReset) menu.add_cascade(label="Analyze", menu=analyzemenu) # create about pulldown menu aboutmenu = Menu(menu, tearoff=0) menu.add_cascade(label="About", menu=aboutmenu) Gives me the error: Traceback (most recent call last): File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 203, in ? myApp = LogAnalyzerGUI() File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 11, in __init__ self.buildUI() File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 35, in buildUI fCanvas.config(menu=menu) File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1139, in configure return self._configure('configure', cnf, kw) File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1130, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TclError: unknown option "-menu" Unless I replace the menu creation from using my frame to using the root: root = Tk() menu = Menu(root) root.config(menu=menu) But this obviously creates another window which is not what I want at all. Any thoughts? Chrs j. From alan.gauld at freenet.co.uk Tue Aug 9 12:22:29 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 11:22:29 +0100 Subject: [Tutor] function won't import from module References: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com><020b01c59cb5$f2eb55d0$bea68651@xp> <6.2.1.2.2.20050809020317.06820d50@rcblue.com> Message-ID: <023701c59ccc$3f1ffe90$bea68651@xp> > I tried deleting a mycalc.pyc that had been created and the problem > cleared up! If I remember correctly, for a while I had moved > mycalc.py to another folder in PYTHONPATH (I had recently learned > how to modify PYTHONPATH in Win XP), and the .pyc was in this > folder. Sorry I don't remember clearly. But what is clear is the > problem cleared up immediately after deleting the .pyc. Does this > make sense? Definitely. If the old pyc file was found first in the search path then it would have been imported. If the py and pyc are inthe same folder that won't be a problem because Python will see both and check the modification date but if it finds an isolated pyc first it will just use that. Alan G. From mi.janssen at gmail.com Tue Aug 9 12:33:11 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue, 9 Aug 2005 12:33:11 +0200 Subject: [Tutor] surprising len() results ??? In-Reply-To: References: Message-ID: <1ff2dfbf050809033345e53aaa@mail.gmail.com> On 8/9/05, Tom Cloyd wrote: > print len('()??????????????????????????') > print len('--AaAAaaCcEEeeIIiiNnOOooUUuu') > > the result: > > 54 > 28 > > I'm completely mystified by this. All of it. None of it makes sense. This > program was working fine. Now it doesn't. And those two parameter string > are plainly the same length, but Python doesn't think so. on my computer (python 2.3): >>> s = '?' # a-umlaut >>> len(s) 1 >>> len(s.decode('latin-1')) # prepare for utf-8 encoding 1 >>> len(s.decode('latin-1').encode('utf-8')) 2 >>> len('a'.decode('latin-1').encode('utf-8')) 1 seems like len returns the number of bytes and some encodings uses more than one byte for certain chars. You can proberbly decode your strings from utf-8 (or whatever encoding you use (and perhaps encode it back into a one-char-one-byte encoding [on my system the decoded (unicode) string is just fine]). regards Michael From rdm at rcblue.com Tue Aug 9 12:35:07 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Aug 2005 03:35:07 -0700 Subject: [Tutor] function won't import from module In-Reply-To: <023701c59ccc$3f1ffe90$bea68651@xp> References: <6.2.1.2.2.20050808204832.06d49eb0@rcblue.com> <020b01c59cb5$f2eb55d0$bea68651@xp> <6.2.1.2.2.20050809020317.06820d50@rcblue.com> <023701c59ccc$3f1ffe90$bea68651@xp> Message-ID: <6.2.1.2.2.20050809032812.0c8bae40@rcblue.com> Alan G wrote at 03:22 8/9/2005: >>I tried deleting a mycalc.pyc that had been created and the problem >>cleared up! If I remember correctly, for a while I had moved mycalc.py >>to another folder in PYTHONPATH (I had recently learned how to modify >>PYTHONPATH in Win XP), and the .pyc was in this folder. Sorry I don't >>remember clearly. But what is clear is the problem cleared up >>immediately after deleting the .pyc. Does this make sense? > >Definitely. If the old pyc file was found first in the search path >then it would have been imported. If the py and pyc are inthe same folder >that won't be a problem because Python will see both and check the >modification date but if it finds an isolated pyc first it will >just use that. > >Alan G. >>> import sys >>> sys.path ['C:\\Python24\\Lib\\idlelib', 'C:\\Python24', 'C:\\Python24\\MyScripts', 'C:\\Python24\\MyBestScripts', 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\Documents and Settings\\Dick', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', 'C:\\Python24\\lib\\site-packages', 'C:\\Python24\\lib\\site-packages\\Numeric', 'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24\\lib\\site-packages\\win32\\lib', 'C:\\Python24\\lib\\site-packages\\Pythonwin'] the pyc was in C:\\Python24, and mycalc.py had been moved back to C:\\Python24\\MyScripts. Does the order of folders in the output of sys.path determine the order of looking for a mycalc.* to execute? Thanks, Dick From kent37 at tds.net Tue Aug 9 13:27:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 07:27:55 -0400 Subject: [Tutor] Using urllib to retrieve info In-Reply-To: <20050809075715.28612.qmail@web25407.mail.ukl.yahoo.com> References: <20050809075715.28612.qmail@web25407.mail.ukl.yahoo.com> Message-ID: <42F8933B.5040204@tds.net> David Holland wrote: > Alan, > > Sorry of course that is the problem. These pages are > password protected !!!! > Is it possible to download password protected pages (I > know the password but I don't how to get the program > to use it). urllib2 supports basic and digest authentication. There ale examples using basic auth here: http://docs.python.org/lib/urllib2-examples.html http://www.voidspace.org.uk/python/recipebook.shtml#auth If the server uses form-based auth I think you will have to post to the form yourself and maybe set up urllib2 to handle cookies as well. Look at the login form and you may be able to figure out how to post the results directly. The second link above also has a cookie example. Kent From kent37 at tds.net Tue Aug 9 13:39:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 07:39:35 -0400 Subject: [Tutor] Tkinter Menus In-Reply-To: References: Message-ID: <42F895F7.2020205@tds.net> Jorge Louis De Castro wrote: > Hello, > > I'm having this issue with Tkinter. I have a frame with all my buttons, > checkboxes et al, and all is working fine. I want to add menus and added the > following to my frame (fCanvas) code: > > # create a toplevel menu > menu = Menu(fCanvas) > fCanvas.config(menu=menu) > # create a pulldown menu, and add it to the menu bar > filemenu = Menu(menu, tearoff=0) > filemenu.add_command(label="Open", command=self.doBrowse) > filemenu.add_separator() > filemenu.add_command(label="Exit", command=self.doQuit) > menu.add_cascade(label="File", menu=filemenu) > # create analyze pulldown menu > analyzemenu = Menu(menu, tearoff=0) > analyzemenu.add_command(label="Start", command=self.doStart) > analyzemenu.add_command(label="Reset", command=self.doReset) > menu.add_cascade(label="Analyze", menu=analyzemenu) > # create about pulldown menu > aboutmenu = Menu(menu, tearoff=0) > menu.add_cascade(label="About", menu=aboutmenu) > > Gives me the error: > Traceback (most recent call last): > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 203, in ? > myApp = LogAnalyzerGUI() > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 11, in > __init__ > self.buildUI() > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 35, in > buildUI > fCanvas.config(menu=menu) > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1139, in configure > return self._configure('configure', cnf, kw) > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1130, in _configure > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > TclError: unknown option "-menu" > > > Unless I replace the menu creation from using my frame to using the root: > > root = Tk() > menu = Menu(root) > root.config(menu=menu) > > But this obviously creates another window which is not what I want at all. > Any thoughts? You don't show what fCanvas is...are you creating a Toplevel window? If you just want one window with a menubar you can add your widgets directly to root. Here is a simple example: from Tkinter import * def callback(code): print "called the callback with code", code root = Tk() w=Label(root,text="Hello!!") w.pack() b=Button(root,text="Bye",command='exit') b.pack() # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=lambda: callback('New')) filemenu.add_command(label="Open...", command=lambda: callback('Open')) filemenu.add_separator() filemenu.add_command(label="Exit", command='exit') mainloop() Kent From python at kapitalisten.no Tue Aug 9 14:00:05 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 9 Aug 2005 14:00:05 +0200 (CEST) Subject: [Tutor] Run a cmd program Message-ID: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> Hello. I need to run a program (http://www.microsoft.com/ntserver/nts/downloads/management/uptime/default.asp) thru Python. It is normally run such as "uptime AUTO-SRV-001 /s /d:04/01/2005" in the command prompt. Is it possible to run a already compiled exe file in Python and thereafter get the result out? What module/command should I look for to run another program? Googling have only given me results about how to run Python.. Thanks in advance. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From rdm at rcblue.com Tue Aug 9 14:07:09 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Aug 2005 05:07:09 -0700 Subject: [Tutor] PyChecker: Installing and or Using Message-ID: <6.2.1.2.2.20050809043619.084baa20@rcblue.com> Win XP. Python2.4. Javier Ruere suggested getting PyChecker or PyLint. I found PyChecker and put the pychecker-0.8.14 folder in C:\Python24\Lib\site-packages\PyChecker. I don't really know what I'm doing (obviously?), but I added C:\Python24\Lib\site-packages\PyChecker\pychecker-0.8.14\pychecker to PYTHONPATH. So now: >>> import sys >>> sys.path ['C:\\Python24\\Lib\\idlelib', 'C:\\Python24', 'C:\\Python24\\MyScripts', 'C:\\Python24\\MyBestScripts', 'C:\\Python24\\Lib\\site-packages\\PyChecker\\pychecker-0.8.14\\pychecker', 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\Documents and Settings\\Dick', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', 'C:\\Python24\\lib\\site-packages', 'C:\\Python24\\lib\\site-packages\\Numeric', 'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24\\lib\\site-packages\\win32\\lib', 'C:\\Python24\\lib\\site-packages\\Pythonwin'] There's this section in : Note: On Windows, use pychecker.bat. You may also need to add python/scripts to your PATH. pychecker and pychecker.bat will only exist if pychecker has been installed. To install, do: python setup.py install Note: If you haven't installed pychecker, it can be run by doing: python pychecker/checker.py My probably dumb question is, how do I "do" those things? I've tried "python setup.py install" at the command line (at Run, I entered cmd and then at the prompt in the window I entered python setup.py install. No good. Then I tried python pychecker/checker.py . I got: C:\Documents and Settings\Dick>python pychecker/checker.py 'python' is not recognized as an internal or external command, operable program or batch file. and also C:\>python pychecker/checker.py 'python' is not recognized as an internal or external command, operable program or batch file. Can someone help me (he said plaintively)? Dick From dma8hm1956 at gmail.com Tue Aug 9 14:23:46 2005 From: dma8hm1956 at gmail.com (Hossein Movahhedian) Date: Tue, 9 Aug 2005 16:53:46 +0430 (IRST) Subject: [Tutor] Curses example on Linux? In-Reply-To: <01d801c59cb4$132538e0$bea68651@xp> References: <01d801c59cb4$132538e0$bea68651@xp> Message-ID: Dear Alan Hi, First of all let me thank you very much for that excellent tutorial. As a Python beginner, I learned many things from that. As I have mentioned in my previous message to this list, in that example I had to replace "ky = msvcrt.getch()" with "ky = chr(msvcrt.getch())". The other problem is that when the program is finished the previous terminal state is not restored (I am using xterm on Linux). Finally, I noticed a typo in the example "class Message" in section Object Oriented Programming. __init__ is written __inti__ in "def __inti__(self, aString):". Regards, Hossein On Tue, 9 Aug 2005, Alan G wrote: > >> I have copied the following example from "Learning to Program by > >> Alan > >> Gauld (section: Event Driven Programming)". To run it on Linux > >> (Redhat 8.0; Python 2.4) the tutorial says to replace 'msvcrt' > >> with 'curses.stdscr'. > > I thought I'd fixed that fault. > > The sequence should be: > > import curses > mscvrt = curses.initscr() > mscvcrt.getch() > > > I will make the changes and upload the fixed file as soon as possible. > > > Thanks for bringing it up. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > Hi Hossein, > > > > > > According to: > > > > http://www.amk.ca/python/howto/curses/ > > > > > > Alan probably meant to say to replace: > > > > ###### > > import msvcrt > > ###### > > > > with: > > > > ###### > > import curses > > msvcrt = curses.initscr() > > ###### > > > > as a quick hack to replace 'msvcrt' with something that works on > > Linux. > > > > > > It sounded that you wanted to look at other examples of curses > > programming? A long time ago, I wrote a quick-and-dirty demo > > program that > > uses curses here: > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/circularwriting.py > > > > > > Good luck to you! > > > > > > > From adam.jtm30 at gmail.com Tue Aug 9 14:35:53 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 9 Aug 2005 13:35:53 +0100 Subject: [Tutor] Run a cmd program In-Reply-To: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> References: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> Message-ID: >>> import commands >>> commands.getoutput("uptime AUTO-SRV-001 /s /d:04/01/2005") that should do it On 8/9/05, ?yvind wrote: > > Hello. > > I need to run a program > ( > http://www.microsoft.com/ntserver/nts/downloads/management/uptime/default.asp > ) > thru Python. It is normally run such as "uptime AUTO-SRV-001 /s > /d:04/01/2005" in the command prompt. Is it possible to run a already > compiled exe file in Python and thereafter get the result out? What > module/command should I look for to run another program? Googling have > only given me results about how to run Python.. > > Thanks in advance. > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/23f7e347/attachment.htm From rschroev_nospam_ml at fastmail.fm Tue Aug 9 14:39:55 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 09 Aug 2005 14:39:55 +0200 Subject: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? In-Reply-To: <42F6D9A2.4010805@po-box.mcgill.ca> References: <42F6D9A2.4010805@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > Say you go with your method of defining a deck (cards above) and then > making random choices from it. Try something like this (untested code): > > cards = ["Ace of ...",] # As above > cards_dealt = [] > def get_card(): > while True: > new_card = random.choice(cards)] > if new_card not in cards_dealt: > cards_dealt.append(new_card) > break > return new_card The random module has a nice function for this: sample( population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. New in version 2.3. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample from a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From python at kapitalisten.no Tue Aug 9 14:57:50 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 9 Aug 2005 14:57:50 +0200 (CEST) Subject: [Tutor] Run a cmd program In-Reply-To: References: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> Message-ID: <53184.193.71.38.142.1123592270.squirrel@mail.sporck.net> Thanks a lot. However, it didn't work. I got an error stating something along: "Is not recognized as an internal or external command, executable program or ...... file" (I don't know how to translate the word ..... to english). But, when I looked in the manual about the commands module, I found this: "Availability: Unix." That might explain. However, in the manual I also found two other commands to try. 'Execl' which made PythonWin 2.3.5 crash regardless how I used it, and os.popen. The latter worked perfectly. Have a great day.... >>>> import commands >>>> commands.getoutput("uptime AUTO-SRV-001 /s /d:04/01/2005") > > that should do it > > On 8/9/05, ?yvind wrote: >> >> Hello. >> >> I need to run a program >> ( >> http://www.microsoft.com/ntserver/nts/downloads/management/uptime/default.asp >> ) >> thru Python. It is normally run such as "uptime AUTO-SRV-001 /s >> /d:04/01/2005" in the command prompt. Is it possible to run a already >> compiled exe file in Python and thereafter get the result out? What >> module/command should I look for to run another program? Googling have >> only given me results about how to run Python.. >> >> Thanks in advance. >> >> -- >> This email has been scanned for viruses & spam by Decna as - >> www.decna.no >> Denne e-posten er sjekket for virus & spam av Decna as - >> www.decna.no >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Tue Aug 9 15:07:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 09:07:38 -0400 Subject: [Tutor] Run a cmd program In-Reply-To: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> References: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> Message-ID: <42F8AA9A.5020407@tds.net> ?yvind wrote: > Hello. > > I need to run a program > (http://www.microsoft.com/ntserver/nts/downloads/management/uptime/default.asp) > thru Python. It is normally run such as "uptime AUTO-SRV-001 /s > /d:04/01/2005" in the command prompt. Is it possible to run a already > compiled exe file in Python and thereafter get the result out? What > module/command should I look for to run another program? Googling have > only given me results about how to run Python.. Try the subprocess module, something like results = subprocess.Popen('uptime AUTO-SRV-001 /s /d:04/01/2005', stdout=subprocess.PIPE).communicate()[0] Kent From ohemming at gmail.com Tue Aug 9 15:12:33 2005 From: ohemming at gmail.com (oliver) Date: Tue, 9 Aug 2005 09:12:33 -0400 Subject: [Tutor] Run a cmd program In-Reply-To: <53184.193.71.38.142.1123592270.squirrel@mail.sporck.net> References: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> <53184.193.71.38.142.1123592270.squirrel@mail.sporck.net> Message-ID: <2ff82e87050809061249aba016@mail.gmail.com> On 8/9/05, ?yvind wrote: > Thanks a lot. However, it didn't work. I got an error stating something > along: "Is not recognized as an internal or external command, executable > program or ...... file" (I don't know how to translate the word ..... to > english). That looks like a windows error not a python problem. Python cannot find the path to the uptime executable. You need to either fully qualify the uptime command ( C:\path\to\uptime ) or somehow set the path in the python environment. From kent37 at tds.net Tue Aug 9 15:13:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 09:13:42 -0400 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <6.2.1.2.2.20050809043619.084baa20@rcblue.com> References: <6.2.1.2.2.20050809043619.084baa20@rcblue.com> Message-ID: <42F8AC06.2050303@tds.net> Dick Moores wrote: > Win XP. Python2.4. > > Javier Ruere suggested getting PyChecker or PyLint. I found PyChecker and > put the pychecker-0.8.14 folder in > C:\Python24\Lib\site-packages\PyChecker. I don't really know what I'm > doing (obviously?), but I added > C:\Python24\Lib\site-packages\PyChecker\pychecker-0.8.14\pychecker to > PYTHONPATH. You should only do one of these; packages in site-packages are already in the path, though you have too many levels of directories...the install should do this right. > My probably dumb question is, how do I "do" those things? I've tried > "python setup.py install" at the command line (at Run, I entered cmd and > then at the prompt in the window I entered python setup.py install. No > good. Then I tried python pychecker/checker.py . I got: > > C:\Documents and Settings\Dick>python pychecker/checker.py > 'python' is not recognized as an internal or external command, > operable program or batch file. You have to add 'C:\Python24' to your PATH environment variable, or give the full path in the command line as C:\Python24\python setup.py install Also when you run setup.py you will have to be in the directory containing setup.py. Question to the tutors - should the Python installer on Windows be adding C:\Python24 to the PATH variable? My recollection is that it used to do that but recent versions don't. Kent From kent37 at tds.net Tue Aug 9 15:29:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 09:29:10 -0400 Subject: [Tutor] Run a cmd program In-Reply-To: <2ff82e87050809061249aba016@mail.gmail.com> References: <47718.193.71.38.142.1123588805.squirrel@mail.sporck.net> <53184.193.71.38.142.1123592270.squirrel@mail.sporck.net> <2ff82e87050809061249aba016@mail.gmail.com> Message-ID: <42F8AFA6.7050103@tds.net> oliver wrote: > On 8/9/05, ?yvind wrote: > >>Thanks a lot. However, it didn't work. I got an error stating something >>along: "Is not recognized as an internal or external command, executable >>program or ...... file" (I don't know how to translate the word ..... to >>english). > > > That looks like a windows error not a python problem. Python cannot > find the path to the uptime executable. You need to either fully > qualify the uptime command ( C:\path\to\uptime ) or somehow set the > path in the python environment. The commands module is not supported on Windows. It's kind of strange, because the module is present, but it doesn't work. >>> import commands >>> commands.getoutput('java') "'{' is not recognized as an internal or external command,\noperable program or batch file." Note the '{' - this is the unrecognized command. From the docs for command: cmd is actually run as { cmd ; } 2>&1 which shows where the { comes from... Kent From davholla2002 at yahoo.co.uk Tue Aug 9 15:53:17 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue, 9 Aug 2005 14:53:17 +0100 (BST) Subject: [Tutor] Using urllib to retrieve info In-Reply-To: <021d01c59cb9$44890380$bea68651@xp> Message-ID: <20050809135317.51352.qmail@web25403.mail.ukl.yahoo.com> I had a look at urllib2 and I found this example :- import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) urllib2.urlopen('http://www.example.com/login.html') One question, what does realm refer to and also what does it mean by host ? Thanks in advance. --- Alan G wrote: > > Sorry of course that is the problem. These pages > are > > password protected !!!! > > Is it possible to download password protected > pages (I > > know the password but I don't how to get the > program > > to use it). > > That will depend on how the protection is > implemented. > If your server is a J2EE box with full blown > Kerberos > security it may be almost impossible. If it's a more > > conventional server like apache which is protecting > a file or folder then you may only have to submit > the username and password - ie login! - or build > that into a cookie. > > If the protection is done by the application itself > then > it could be anywhere in between those two extremes. > > HTH, > > Alan G. > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From lists at janeden.org Tue Aug 9 15:55:01 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 9 Aug 2005 15:55:01 +0200 Subject: [Tutor] Default class in module Message-ID: Hi, I'd like to pack some modules in a package. Each module contains a single class, which forces me to from Pythonsite.Show import Page page = Page() ... class Page(Site.DB): #class DB from module Site in package Pythonsite ... Is there a way to define a default class for a module which would me allow to from Pythonsite import Show page = Show() #page as an instance of default class in Show class Page(Site): #Page as a subclass of default class in Site Thanks, Jan -- There's no place like ~/ From rdm at rcblue.com Tue Aug 9 16:22:44 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Aug 2005 07:22:44 -0700 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <42F8AC06.2050303@tds.net> References: <6.2.1.2.2.20050809043619.084baa20@rcblue.com> <42F8AC06.2050303@tds.net> Message-ID: <6.2.1.2.2.20050809065728.02a16820@rcblue.com> Kent Johnson wrote at 06:13 8/9/2005: >Dick Moores wrote: > > Win XP. Python2.4. > > > > Javier Ruere suggested getting PyChecker or PyLint. I found PyChecker > and > > put the pychecker-0.8.14 folder in > > C:\Python24\Lib\site-packages\PyChecker. I don't really know what I'm > > doing (obviously?), but I added > > C:\Python24\Lib\site-packages\PyChecker\pychecker-0.8.14\pychecker to > > PYTHONPATH. > >You should only do one of these; packages in site-packages are already >in the path, though you have too many levels of directories...the >install should do this right. > > > My probably dumb question is, how do I "do" those things? I've tried > > "python setup.py install" at the command line (at Run, I entered cmd and > > then at the prompt in the window I entered python setup.py install. No > > good. Then I tried python pychecker/checker.py . I got: > > > > C:\Documents and Settings\Dick>python pychecker/checker.py > > 'python' is not recognized as an internal or external command, > > operable program or batch file. > >You have to add 'C:\Python24' to your PATH environment variable, or give >the full path in the command line as >C:\Python24\python setup.py install > >Also when you run setup.py you will have to be in the directory >containing setup.py. OK, I got it to install. But now, when I try to use checker.py I get: Warning (from warnings module): File "C:\Python24\lib\site-packages\pychecker\checker.py", line 609 m = imp.init_builtin(moduleName) DeprecationWarning: the regex module is deprecated; please use the re module That line 609 is in this function in checker.py: def fixupBuiltinModules(needs_init=0): for moduleName in sys.builtin_module_names : if needs_init: _ = Module(moduleName, 0) module = _allModules.get(moduleName, None) if module is not None : try : m = imp.init_builtin(moduleName) except ImportError : pass else : extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, []) module.attributes = [ '__dict__' ] + dir(m) + extra_attrs >>> import sys >>> sys.builtin_module_names ('__builtin__', '__main__', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_csv', '_heapq', '_hotshot', '_locale', '_multibytecodec', '_random', '_sre', '_subprocess', '_symtable', '_weakref', '_winreg', 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', 'collections', 'datetime', 'errno', 'exceptions', 'gc', 'imageop', 'imp', 'itertools', 'marshal', 'math', 'md5', 'mmap', 'msvcrt', 'nt', 'operator', 'parser', 'regex', 'rgbimg', 'sha', 'signal', 'strop', 'struct', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport') >>> What now? Dick From jobauk at hotmail.com Tue Aug 9 16:29:00 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Tue, 09 Aug 2005 14:29:00 +0000 Subject: [Tutor] Tkinter Menus In-Reply-To: <42F895F7.2020205@tds.net> Message-ID: Ah, sorry. Here is the definition of fCanvas: class LogAnalyzerGUI(Frame): def __init__(self, parent=0): Frame.__init__(self, parent) self.type = 2 self.terms = 0 self.master.title('XML Analyzer') self.buildUI() def buildUI(self): fCanvas = Frame(self) Label(fCanvas, text="Filename: ").grid(row=0, sticky=E) ... > > Hello, > > > > I'm having this issue with Tkinter. I have a frame with all my buttons, > > checkboxes et al, and all is working fine. I want to add menus and added >the > > following to my frame (fCanvas) code: > > > > # create a toplevel menu > > menu = Menu(fCanvas) > > fCanvas.config(menu=menu) > > # create a pulldown menu, and add it to the menu bar > > filemenu = Menu(menu, tearoff=0) > > filemenu.add_command(label="Open", command=self.doBrowse) > > filemenu.add_separator() > > filemenu.add_command(label="Exit", command=self.doQuit) > > menu.add_cascade(label="File", menu=filemenu) > > # create analyze pulldown menu > > analyzemenu = Menu(menu, tearoff=0) > > analyzemenu.add_command(label="Start", command=self.doStart) > > analyzemenu.add_command(label="Reset", command=self.doReset) > > menu.add_cascade(label="Analyze", menu=analyzemenu) > > # create about pulldown menu > > aboutmenu = Menu(menu, tearoff=0) > > menu.add_cascade(label="About", menu=aboutmenu) > > > > Gives me the error: > > Traceback (most recent call last): > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 203, >in ? > > myApp = LogAnalyzerGUI() > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 11, in > > __init__ > > self.buildUI() > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 35, in > > buildUI > > fCanvas.config(menu=menu) > > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1139, in configure > > return self._configure('configure', cnf, kw) > > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1130, in _configure > > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > > TclError: unknown option "-menu" > > > > > > Unless I replace the menu creation from using my frame to using the >root: > > > > root = Tk() > > menu = Menu(root) > > root.config(menu=menu) > > > > But this obviously creates another window which is not what I want at >all. > > Any thoughts? > >You don't show what fCanvas is...are you creating a Toplevel window? If you >just want one >window with a menubar you can add your widgets directly to >root. Here is a simple example: Yes, I know that. I tried that and saw, as expected, that it popped a window outside my fCanvas frame, whereas I want to add the menu to the fCanvas frame the same way I added the labels ,buttons, etc. The interpreter complains that it doesn't know the 'menu' configuration option from the config method. This works as expected if the root is used like you say >menu = Menu(root) >root.config(menu=menu) But doesnt if I want to add it to fCanvas: menu = Menu(fCanvas) fCanvas.config(menu=menu) Chrs j. From RPhillips at engineer.co.summit.oh.us Tue Aug 9 16:45:31 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Tue, 09 Aug 2005 10:45:31 -0400 Subject: [Tutor] Stuck: unicode in regular expressions Message-ID: I am expecting users to cut-and-paste DMS data into an application * like: +40 30 15 E40 15 34.56, -81 0 0, 81 57 34.27E, W 40? 13' 27.343", 40? 13' 27.343" S, 140? 13' 27.343"S, S40? 13' 27.34454, 81:57:34.27E I've been able to write a regex that seems to work in redemo.py, but it doesn't do at all what I want when I try to code it using the re module. The problem seems to be the way I am using unicode * specifically all those punctuation marks that might get pasted in. I anticipate the program getting its input from a browser; maybe that will narrow down the range somewhat. Anyway, given the string above, what regex will match the " and ' characters, please? I have tried \x02BC and \x92 and \x2019 for the ' , but no result. I am sure it's simple; I am sure some other newbie has asked it, but I have Googled my brains out, and can't find it. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/a7924361/attachment.htm From kent37 at tds.net Tue Aug 9 17:01:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Aug 2005 11:01:04 -0400 Subject: [Tutor] Stuck: unicode in regular expressions In-Reply-To: References: Message-ID: <42F8C530.3020907@tds.net> Ron Phillips wrote: > I am expecting users to cut-and-paste DMS data into an application ? > like: +40 30 15 E40 15 34.56, -81 0 0, 81 57 34.27E, W 40? 13? > 27.343?, 40? 13? 27.343? S, 140? 13? 27.343?S, S40? 13? 27.34454, > 81:57:34.27E > > I've been able to write a regex that seems to work in redemo.py, but it > doesn't do at all what I want when I try to code it using the re module. > The problem seems to be the way I am using unicode ? specifically all > those punctuation marks that might get pasted in. I anticipate the > program getting its input from a browser; maybe that will narrow down > the range somewhat. I'm guessing a bit here, but you have to know what encoding you are getting from the browser. If the input is from a form, I think you will get back results in the same encoding as the page containing the form. Then I think you can either - convert the form data to unicode and use unicode in the regex, or - use the same encoding for the regex as the form data A good way to start would be to print repr(formdata) that will show you exactly what is in the data. Kent > > Anyway, given the string above, what regex will match the ? and ? > characters, please? I have tried \x02BC and \x92 and \x2019 for the ? , > but no result. I am sure it's simple; I am sure some other newbie has > asked it, but I have Googled my brains out, and can't find it. > > Ron > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jobauk at hotmail.com Tue Aug 9 18:06:48 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Tue, 09 Aug 2005 16:06:48 +0000 Subject: [Tutor] Tkinter Menus In-Reply-To: <42F895F7.2020205@tds.net> Message-ID: Got it! Because 'menu' is a config option of the top level window's config but not of 'Frame', It's just a matter of calling self.master.config(menu=menu) Thanks j. >From: Kent Johnson >To: Python Tutor >Subject: Re: [Tutor] Tkinter Menus >Date: Tue, 09 Aug 2005 07:39:35 -0400 > >Jorge Louis De Castro wrote: > > Hello, > > > > I'm having this issue with Tkinter. I have a frame with all my buttons, > > checkboxes et al, and all is working fine. I want to add menus and added >the > > following to my frame (fCanvas) code: > > > > # create a toplevel menu > > menu = Menu(fCanvas) > > fCanvas.config(menu=menu) > > # create a pulldown menu, and add it to the menu bar > > filemenu = Menu(menu, tearoff=0) > > filemenu.add_command(label="Open", command=self.doBrowse) > > filemenu.add_separator() > > filemenu.add_command(label="Exit", command=self.doQuit) > > menu.add_cascade(label="File", menu=filemenu) > > # create analyze pulldown menu > > analyzemenu = Menu(menu, tearoff=0) > > analyzemenu.add_command(label="Start", command=self.doStart) > > analyzemenu.add_command(label="Reset", command=self.doReset) > > menu.add_cascade(label="Analyze", menu=analyzemenu) > > # create about pulldown menu > > aboutmenu = Menu(menu, tearoff=0) > > menu.add_cascade(label="About", menu=aboutmenu) > > > > Gives me the error: > > Traceback (most recent call last): > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 203, >in ? > > myApp = LogAnalyzerGUI() > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 11, in > > __init__ > > self.buildUI() > > File "C:\Workplace\python\im_logparser\msn_parser_gui.py", line 35, in > > buildUI > > fCanvas.config(menu=menu) > > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1139, in configure > > return self._configure('configure', cnf, kw) > > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1130, in _configure > > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > > TclError: unknown option "-menu" > > > > > > Unless I replace the menu creation from using my frame to using the >root: > > > > root = Tk() > > menu = Menu(root) > > root.config(menu=menu) > > > > But this obviously creates another window which is not what I want at >all. > > Any thoughts? > >You don't show what fCanvas is...are you creating a Toplevel window? If you >just want one window with a menubar you can add your widgets directly to >root. Here is a simple example: > >from Tkinter import * > >def callback(code): > print "called the callback with code", code > >root = Tk() > >w=Label(root,text="Hello!!") >w.pack() >b=Button(root,text="Bye",command='exit') >b.pack() > ># create a menu >menu = Menu(root) >root.config(menu=menu) > >filemenu = Menu(menu) >menu.add_cascade(label="File", menu=filemenu) >filemenu.add_command(label="New", command=lambda: callback('New')) >filemenu.add_command(label="Open...", command=lambda: callback('Open')) >filemenu.add_separator() >filemenu.add_command(label="Exit", command='exit') > >mainloop() > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Tue Aug 9 18:36:49 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 17:36:49 +0100 Subject: [Tutor] Curses example on Linux? References: <01d801c59cb4$132538e0$bea68651@xp> Message-ID: <026c01c59d00$8b2648b0$bea68651@xp> > "ky = chr(msvcrt.getch())". The other problem is that when > the program is finished the previous terminal state is not > restored (I am using xterm on Linux). Yep, and that applies to my cygwin terminal too. I think there is a setty command you can issue that fixres this but since I hardly ever use curses I can't recall what it is - anyone??? > Finally, I noticed a typo in the example "class Message" in > section Object Oriented Programming. __init__ is written __inti__ > in "def __inti__(self, aString):". OK, Thanks. If you find any more typos send them to me via the mail me link at the bottom of each page - it saves bandwidth on the tutor list (and my embarrasment :-) BTW Which version of the tutor are you reading? The inti bug seems to have been fixed in the latest English version... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Tue Aug 9 21:32:18 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 13:32:18 -0600 Subject: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? References: <42F6D9A2.4010805@po-box.mcgill.ca> Message-ID: Hey Brian and all, Just coded in and tried your program Brian. Doesn't print a thing. I thought the odds were more like 6/52! or 1/(1.3443029195*10^84). --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: "Brian van den Broek" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Sunday, August 07, 2005 10:03 PM Subject: Re: [Tutor] Use functions re avoid Re: Can the following algorithm be improved? > Nathan Pinno said unto the world upon 2005-08-07 22:10: >> My message is in the attachment. > > Nathan, > > Just one fellow's voice, but I vote for "please don't do that" [the > attachment]. It makes it more work to read your message. > >> Here is the improved algorithm: >> import random a = random.choice(range(52)) > >> u = random.choice(range(52)) >> cards = ['Ace of Hearts','Two of Hearts', > > > >> 'Jack of Clubs','Queen of Clubs','King of Clubs'] >> print "The Card Dealer" >> print "By Nathan Pinno" >> while 1: >> cd = int(raw_input("How many cards to deal (1-6) or 9 to exit:")) >> if cd == 1: >> print cards[a] >> elif cd == 2: >> print cards[b] >> print cards[c] >> elif cd == 3: >> print cards[d] >> print cards[e] >> print cards[f] >> elif cd == 4: >> print cards[g] > >> print cards[j] >> elif cd == 5: >> print cards[k] > >> print cards[o] >> elif cd == 6: >> print cards[p] > >> print cards[u] >> elif cd == 9: >> break >> print "Goodbye." >> >> Can it be improved on anympre? > > > > Yep. You should follow Danny's suggestion and make a function which deals > a single card. Then, your can call that function the requisite number of > times. > > I'm not sure in the code here why you define a-u. Is there some reason you > cannot have the two card case use a and b, the 3 case a, b, and c, etc.? > >> R. Alan Monroe suggested a different way. Instead of cards, you would >> would >> have cardrank and type. To get the cardrank and type you would do a % 4, >> and for the type a % 13. It would work, only how would you keep two > > identical cards from showing up? > > Good question. But notice that your code has the same problem. Nothing > stops the (dramatically unlikely) even that a-u all get assigned the same > card. Over 6 cards, it will certainly turn up that you have given the same > card twice with this code, too. (The way I figure it: > > >>> ( (52**6) - (52*51*50*49*48*47.0) ) / (52**6) > 0.25858966166881681 > > 25% of the time.) > > Say you go with your method of defining a deck (cards above) and then > making random choices from it. Try something like this (untested code): > > cards = ["Ace of ...",] # As above > cards_dealt = [] > def get_card(): > while True: > new_card = random.choice(cards)] > if new_card not in cards_dealt: > cards_dealt.append(new_card) > break > return new_card > > while True: > cd = #as before > if cd == 9: > break > elif cd in range(1, 7): > the_deal = [] > for i in range(cd): > the_deal.append(get_card()) > else: > print "Read the instructions, please." > > > This could still be improved a lot (it was off the cuff). For instance, > get_card might in theory take 1000's of attempts to get a 'fresh' card. > There are much more efficient ways. But it might be a shorter step from > the code you have. Small improvements are small, but they are also > improvements. > > I really suggest you take make a closer examination of Danny's coin > example. > > Best, > > Brian vdB > > From falcon3166 at hotmail.com Tue Aug 9 21:35:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 13:35:33 -0600 Subject: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? References: <42F6D9A2.4010805@po-box.mcgill.ca> Message-ID: Hey all, I just fixed it so that it prints. The problem was that it returned the cards instead of printing them. Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: "Nathan Pinno" To: "Brian van den Broek" Cc: "Tutor mailing list" Sent: Tuesday, August 09, 2005 1:32 PM Subject: Re: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? > Hey Brian and all, > > Just coded in and tried your program Brian. Doesn't print a thing. > > I thought the odds were more like 6/52! or 1/(1.3443029195*10^84). > --------------------------------------------------------------- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. > --Benjamin Franklin > ------------------------------------------------------------------- > ----- Original Message ----- > From: "Brian van den Broek" > To: "Nathan Pinno" > Cc: "Tutor mailing list" > Sent: Sunday, August 07, 2005 10:03 PM > Subject: Re: [Tutor] Use functions re avoid Re: Can the following > algorithm > be improved? > > >> Nathan Pinno said unto the world upon 2005-08-07 22:10: >>> My message is in the attachment. >> >> Nathan, >> >> Just one fellow's voice, but I vote for "please don't do that" [the >> attachment]. It makes it more work to read your message. >> >>> Here is the improved algorithm: >>> import random a = random.choice(range(52)) >> >>> u = random.choice(range(52)) >>> cards = ['Ace of Hearts','Two of Hearts', >> >> >> >>> 'Jack of Clubs','Queen of Clubs','King of Clubs'] >>> print "The Card Dealer" >>> print "By Nathan Pinno" >>> while 1: >>> cd = int(raw_input("How many cards to deal (1-6) or 9 to exit:")) >>> if cd == 1: >>> print cards[a] >>> elif cd == 2: >>> print cards[b] >>> print cards[c] >>> elif cd == 3: >>> print cards[d] >>> print cards[e] >>> print cards[f] >>> elif cd == 4: >>> print cards[g] >> >>> print cards[j] >>> elif cd == 5: >>> print cards[k] >> >>> print cards[o] >>> elif cd == 6: >>> print cards[p] >> >>> print cards[u] >>> elif cd == 9: >>> break >>> print "Goodbye." >>> >>> Can it be improved on anympre? >> >> >> >> Yep. You should follow Danny's suggestion and make a function which deals >> a single card. Then, your can call that function the requisite number of >> times. >> >> I'm not sure in the code here why you define a-u. Is there some reason >> you >> cannot have the two card case use a and b, the 3 case a, b, and c, etc.? >> >>> R. Alan Monroe suggested a different way. Instead of cards, you would >>> would >>> have cardrank and type. To get the cardrank and type you would do a % 4, >>> and for the type a % 13. It would work, only how would you keep two >> > identical cards from showing up? >> >> Good question. But notice that your code has the same problem. Nothing >> stops the (dramatically unlikely) even that a-u all get assigned the same >> card. Over 6 cards, it will certainly turn up that you have given the >> same >> card twice with this code, too. (The way I figure it: >> >> >>> ( (52**6) - (52*51*50*49*48*47.0) ) / (52**6) >> 0.25858966166881681 >> >> 25% of the time.) >> >> Say you go with your method of defining a deck (cards above) and then >> making random choices from it. Try something like this (untested code): >> >> cards = ["Ace of ...",] # As above >> cards_dealt = [] >> def get_card(): >> while True: >> new_card = random.choice(cards)] >> if new_card not in cards_dealt: >> cards_dealt.append(new_card) >> break >> return new_card >> >> while True: >> cd = #as before >> if cd == 9: >> break >> elif cd in range(1, 7): >> the_deal = [] >> for i in range(cd): >> the_deal.append(get_card()) >> else: >> print "Read the instructions, please." >> >> >> This could still be improved a lot (it was off the cuff). For instance, >> get_card might in theory take 1000's of attempts to get a 'fresh' card. >> There are much more efficient ways. But it might be a shorter step from >> the code you have. Small improvements are small, but they are also >> improvements. >> >> I really suggest you take make a closer examination of Danny's coin >> example. >> >> Best, >> >> Brian vdB >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Tue Aug 9 22:14:18 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 14:14:18 -0600 Subject: [Tutor] (OT) Info on card games. Message-ID: Hey all, I marked it off-topic, but it is necessary to mail this to the mailing list. People asked questions when I first put up my blackjack game(the beginning code of it anyway), so here is a site that has the rules of card games, since I'll be writing them on Python. It's http://www.pagat.com/ and I found it very useful when I did my research on Blackjack, Poker and Cribbage. Nathan. --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- P.S. Is this signature better than the last one? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/8b23a79b/attachment.htm From tomcloyd at bestmindhealth.com Tue Aug 9 22:19:13 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Tue, 09 Aug 2005 13:19:13 -0700 Subject: [Tutor] surprising len() results ??? In-Reply-To: <1ff2dfbf050809033345e53aaa@mail.gmail.com> References: <1ff2dfbf050809033345e53aaa@mail.gmail.com> Message-ID: Michael and List, You suggestion (see foot of email trail, below) is a bit over my head. As I stated, I removed ActivePython 2.4.1 installed Python 2.4.1 from python.org, and now my program doesn't work, where before it did. I don't understand this. When isn't Python 2.4.1 == Python 2.4.1? Is this a Python level problem, or something in my script? At the head of my script I explicitly set coding to utf-8, but that't not new. Do I need to change a parameter somewhere? More to the point, what do I have to do to get going again. I really don't know. Thanks in advance for any help! Tom C. On Tue, 09 Aug 2005 03:33:11 -0700, Michael Janssen wrote: > On 8/9/05, Tom Cloyd wrote: > >> print len('()??????????????????????????') >> print len('--AaAAaaCcEEeeIIiiNnOOooUUuu') >> >> the result: >> >> 54 >> 28 >> >> I'm completely mystified by this. All of it. None of it makes sense. >> This >> program was working fine. Now it doesn't. And those two parameter string >> are plainly the same length, but Python doesn't think so. > > on my computer (python 2.3): >>>> s = '?' # a-umlaut >>>> len(s) > 1 >>>> len(s.decode('latin-1')) # prepare for utf-8 encoding > 1 >>>> len(s.decode('latin-1').encode('utf-8')) > 2 >>>> len('a'.decode('latin-1').encode('utf-8')) > 1 > > seems like len returns the number of bytes and some encodings uses > more than one byte for certain chars. You can proberbly decode your > strings from utf-8 (or whatever encoding you use (and perhaps encode > it back into a one-char-one-byte encoding [on my system the decoded > (unicode) string is just fine]). > > regards > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- ====================================================== Tom Cloyd, MS MA, LMHC Private practice Psychotherapist Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com / tc at bestmindhealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From wesc at fuzzyorange.com Tue Aug 9 22:28:20 2005 From: wesc at fuzzyorange.com (Wesley Chun) Date: Tue, 9 Aug 2005 13:28:20 -0700 Subject: [Tutor] ANN: Python training, Aug 29-31, San Francisco Message-ID: <200508092029.j79KSKKp027825@freesia.deirdre.org> hi all, just wanted to announce my next public Python course. it's a 3-day course held near the San Francisco airport. please sign up quickly as there are only 10 more open spots! let me know if you have any questions. the website is http://cyberwebconsulting.com (click "Python training"), but more info is given in the annoucenment below. thanks, -wesley What: Python Programming I: Introduction to Python When: August 29-31, 2005 Where: San Francisco, CA, USA Already know Java, Perl, C/C++, JavaScript, PHP, or TCL/Tk, but want to learn Python because you've been hearing about how Google, Yahoo!, Industrial Light & Magic, Red Hat, Zope, NASA, and IronPort are using this object-oriented, open source applications and systems development language? Python is rapidly gaining momentum worldwide and seeing more new users each year. While similar to those other languages, Python differentiates itself with a robust yet simple-as-VB syntax which allows for shorter development time and improved group collaboration. Need to get up-to-speed with Python as quickly as possible? Come join us in beautiful Northern California the week before Labor Day. We are proud to announce another rigorous Python training event taught by software engineer and "Core Python Programming" author, Wesley Chun. This is an intense introduction to Python programming geared towards those who have some proficiency in another high-level language. Topics include: * Python's Objects and Memory Model * Data Types, Operators, and Methods * Errors and Exception Handling * Files and Input/Output * Functions and Functional Programming * Modules and Packages * Classes, Methods, and Class Instances * Callable and Executable Objects This course will take place daily August 29-31, 2005 (Monday through Wednesday, 9am - 5pm) in San Bruno, CA, right near the San Francisco International Airport at the: Staybridge Suites San Francisco Airport 1350 Huntington Ave San Bruno, CA 94066 650-588-0770 This venue provides free shuttles to/from the airport and has easy access to public transit (BART, CalTrain, SamTrans) to help you get all over the Bay Area. Afterwards, feel free to enjoy the holiday weekend in the greatest city by the Bay... bring your families!! Sign up quickly as we can only take 15-20 enrollees! For more information and registration, just go to http://cyberwebconsulting.com and click on the "Python Training" link. If you have any questions, feel free to contact us at cyberweb-at-rocketmail.com. From falcon3166 at hotmail.com Tue Aug 9 22:52:23 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 14:52:23 -0600 Subject: [Tutor] deck dealing program References: <004201c59be3$c15805e0$aa0ca8c0@luke> Message-ID: Thanks Luke. You've helped me out of a jam that I was going to ask without even asking. Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: luke To: tutor at python.org Sent: Monday, August 08, 2005 12:38 AM Subject: [Tutor] deck dealing program from random import randint def identify_card(n): cardname = "" royals = ["Jack","Queen","King","Ace"] temp = n % 13 if temp > 8: cardname += royals[temp-9] else: cardname += str(temp+2) cardname += " of " suits = ["Spades","Hearts","Diamonds","Clubs"] cardname += suits[n/13] return cardname def main(): deck = range(52) cards = [] while 1: x = raw_input("how many cards do you want? ") try: x = int(x) except ValueError: print "Invalid value exiting for I have no error code. Please use an int next time." raise SystemExit if x <= 52 and x >= 0: y = 0 while y < x: cards.append(identify_card(deck.pop(randint(0,len(deck)-1)))) y += 1 break print cards if __name__ == "__main__": main() #Luke ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/d4d4a8e0/attachment.htm From bvande at po-box.mcgill.ca Tue Aug 9 23:23:39 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 09 Aug 2005 17:23:39 -0400 Subject: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? In-Reply-To: References: <42F6D9A2.4010805@po-box.mcgill.ca> Message-ID: <42F91EDB.5010004@po-box.mcgill.ca> Nathan Pinno said unto the world upon 2005-08-09 15:35: > Hey all, > > I just fixed it so that it prints. The problem was that it returned the > cards instead of printing them. > > Nathan > >> Hey Brian and all, >> >> Just coded in and tried your program Brian. Doesn't print a thing. >> Hi Nathan, yes, I should have pointed out that I made it return the cards dealt rather than printing them and explained why I made it do that. But, I just did it out of force of habit, so I didn't notice I'd changed the functionality. Sorry about that. So, why do that? Well, it might not matter too much in this case, but the idea is to make each function responsible for one thing. That has several advantages. The two main ones IMO: 1) it keeps the functions small which aids comprehension and debugging, and 2) it makes the functions easier to string together to do other things. For instance, if what you want right now is for the cards to be printed, it is easy enough to use something like my code[*] and then have another function which calls the dealing function and prints the results. If later you should want to use the results of a deal in a more elaborate manner than just printing them (like if you make a card game which needs to know what was dealt) you've got the deal returned and you can do with it what you want to. If you don't return and just print from the sort of code I gave, new uses will probably require changing the code rather than just adding new function to work with it. One approach would say don't add it now; instead do the minimal thing that meets your needs because just thinking you will need it later doesn't mean you will. But, in the case at hand, the future need is pretty likely, and the modularity of functions (one chunk doing the generation, the other doing the processing of the results) also speaks for doing it the return way. [*] But don't use my code. I was doing by hand what Roel pointed out can be done by the random module itself. (Thanks, Roel! I didn't know about random.sample.) Since whoever added sample to random is a better programmer than you or I, use sample :-) >> I thought the odds were more like 6/52! or 1/(1.3443029195*10^84). >>> Good question. But notice that your code has the same problem. Nothing >>> stops the (dramatically unlikely) even that a-u all get assigned the >>> same >>> card. Over 6 cards, it will certainly turn up that you have given the >>> same >>> card twice with this code, too. (The way I figure it: >>> >>> >>> ( (52**6) - (52*51*50*49*48*47.0) ) / (52**6) >>> 0.25858966166881681 >>> >>> 25% of the time.) I don't think I got the math wrong. My thinking is there are 52**6 ways to choose 6 items from 52 if you don't care about duplicates, and 52*51*50*49*48*47 ways to choose if you do. (The first card can be any one of 52, the second any one of the 51 left, etc. 52! by contrast gives you all the ways 52 items can be ordered in a non-repeating sequence.) Here is a very quick (and I am sure not too efficient) bit of code to give empirical support to my analysis: import random def get_choice(n, source): '''Returns a sequence of n independent random choices from source''' choice = [] for i in range(n): choice.append(random.choice(source)) return choice def has_dups(sequence): '''Returns True if sequence contains duplicates, False otherwise''' for i in sequence[:-1]: # No point checking the last member if sequence.count(i) > 1: # We can bail, as duplicate found return True return False def get_dup_percentage(runs, choice_length, source_length): '''Returns percentage of duplicates in a series of choices over a sequence. The function make runs many choices of length choice_length from a sequence of length source_length and returns percentage of those choices that contain duplication.''' count = 0.0 # 0.0 for type coercion dups = 0 source_sequence = range(source_length) while count < runs: choice_sequence = get_choice(choice_length, source_sequence) if has_dups(choice_sequence): dups += 1 count += 1 return dups / count * 100 print get_dup_percentage(100000, 6, 52) Run that and I think you will find the values cluster around 25.85%. (The code was written to be general. Play around with the values in the final [print] line. I get that 9 choices are enough over a 52 termed sequence to give you more than 50% odds of duplicates.) Best, Brian vdB From falcon3166 at hotmail.com Tue Aug 9 23:35:30 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 15:35:30 -0600 Subject: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? References: <42F6D9A2.4010805@po-box.mcgill.ca> <42F91EDB.5010004@po-box.mcgill.ca> Message-ID: It printed 25.973 as the result. --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: "Brian van den Broek" To: "Nathan Pinno" Cc: "Tutor mailing list" Sent: Tuesday, August 09, 2005 3:23 PM Subject: Re: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? > Nathan Pinno said unto the world upon 2005-08-09 15:35: >> Hey all, >> >> I just fixed it so that it prints. The problem was that it returned the >> cards instead of printing them. >> >> Nathan > > > > >> Hey Brian and all, > >> > >> Just coded in and tried your program Brian. Doesn't print a thing. > >> > > > Hi Nathan, > > yes, I should have pointed out that I made it return the cards dealt > rather than printing them and explained why I made it do that. But, I just > did it out of force of habit, so I didn't notice I'd changed the > functionality. Sorry about that. > > So, why do that? Well, it might not matter too much in this case, but the > idea is to make each function responsible for one thing. That has several > advantages. The two main ones IMO: 1) it keeps the functions small which > aids comprehension and debugging, and 2) it makes the functions easier to > string together to do other things. > > For instance, if what you want right now is for the cards to be printed, > it is easy enough to use something like my code[*] and then have another > function which calls the dealing function and prints the results. If later > you should want to use the results of a deal in a more elaborate manner > than just printing them (like if you make a card game which needs to know > what was dealt) you've got the deal returned and you can do with it what > you want to. If you don't return and just print from the sort of code I > gave, new uses will probably require changing the code rather than just > adding new function to work with it. > > One approach would say don't add it now; instead do the minimal thing that > meets your needs because just thinking you will need it later doesn't mean > you will. But, in the case at hand, the future need is pretty likely, and > the modularity of functions (one chunk doing the generation, the other > doing the processing of the results) also speaks for doing it the return > way. > > [*] But don't use my code. I was doing by hand what Roel pointed out can > be done by the random module itself. (Thanks, Roel! I didn't know about > random.sample.) Since whoever added sample to random is a better > programmer than you or I, use sample :-) > > >>> I thought the odds were more like 6/52! or 1/(1.3443029195*10^84). > > > >>>> Good question. But notice that your code has the same problem. Nothing >>>> stops the (dramatically unlikely) even that a-u all get assigned the >>>> same >>>> card. Over 6 cards, it will certainly turn up that you have given the >>>> same >>>> card twice with this code, too. (The way I figure it: >>>> >>>> >>> ( (52**6) - (52*51*50*49*48*47.0) ) / (52**6) >>>> 0.25858966166881681 >>>> >>>> 25% of the time.) > > I don't think I got the math wrong. My thinking is there are 52**6 ways to > choose 6 items from 52 if you don't care about duplicates, and > 52*51*50*49*48*47 ways to choose if you do. (The first card can be any one > of 52, the second any one of the 51 left, etc. 52! by contrast gives you > all the ways 52 items can be ordered in a non-repeating sequence.) > > Here is a very quick (and I am sure not too efficient) bit of code to give > empirical support to my analysis: > > > import random > > def get_choice(n, source): > '''Returns a sequence of n independent random choices from source''' > choice = [] > for i in range(n): > choice.append(random.choice(source)) > return choice > > def has_dups(sequence): > '''Returns True if sequence contains duplicates, False otherwise''' > for i in sequence[:-1]: > # No point checking the last member > if sequence.count(i) > 1: > # We can bail, as duplicate found > return True > return False > > def get_dup_percentage(runs, choice_length, source_length): > '''Returns percentage of duplicates in a series of choices over a > sequence. > > The function make runs many choices of length choice_length from a > sequence > of length source_length and returns percentage of those choices that > contain duplication.''' > count = 0.0 # 0.0 for type coercion > dups = 0 > source_sequence = range(source_length) > while count < runs: > choice_sequence = get_choice(choice_length, source_sequence) > if has_dups(choice_sequence): > dups += 1 > count += 1 > return dups / count * 100 > > print get_dup_percentage(100000, 6, 52) > > > Run that and I think you will find the values cluster around 25.85%. > > (The code was written to be general. Play around with the values in the > final [print] line. I get that 9 choices are enough over a 52 termed > sequence to give you more than 50% odds of duplicates.) > > Best, > > Brian vdB > > From moparfan90 at gmail.com Tue Aug 9 23:45:07 2005 From: moparfan90 at gmail.com (Dan Deternova) Date: Tue, 9 Aug 2005 17:45:07 -0400 Subject: [Tutor] help Message-ID: <9560d3c050809144572133bd7@mail.gmail.com> ok. i know python and want to turn all my programs i made when i was learning python into Tkinter programs. i dont know how to make if satments and display the output like this in python: if cmd == quit: print "press exit to quit" i have no idea how to do that in Tkinter please help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/5d319b38/attachment.htm From bvande at po-box.mcgill.ca Wed Aug 10 00:01:59 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 09 Aug 2005 18:01:59 -0400 Subject: [Tutor] Use functions re avoid Re: Can the following algorithmbe improved? In-Reply-To: References: <42F6D9A2.4010805@po-box.mcgill.ca> <42F91EDB.5010004@po-box.mcgill.ca> Message-ID: <42F927D7.2040401@po-box.mcgill.ca> Nathan Pinno said unto the world upon 2005-08-09 17:35: > It printed 25.973 as the result. >> I don't think I got the math wrong. My thinking is there are 52**6 >> ways to choose 6 items from 52 if you don't care about duplicates, and >> 52*51*50*49*48*47 ways to choose if you do. (The first card can be any >> one of 52, the second any one of the 51 left, etc. 52! by contrast >> gives you all the ways 52 items can be ordered in a non-repeating >> sequence.) >> >> Here is a very quick (and I am sure not too efficient) bit of code to >> give empirical support to my analysis: >> >> >> >> >> Run that and I think you will find the values cluster around 25.85%. >> >> (The code was written to be general. Play around with the values in >> the final [print] line. I get that 9 choices are enough over a 52 >> termed sequence to give you more than 50% odds of duplicates.) >> >> Best, >> >> Brian vdB Well, Nathan, 25.973 seems like a number that could well be in a cluster around 25.85 to me. :-) Run it multiple times; you'll get different numbers each run. (It is a randomized process, after all!) They will be in a cluster around 25.85. Run it enough times, and you'd eventually get 100, and 0 and everything in between. But, with 100000 runs, I don't feel like waiting for either case! Lower the runs value to get wider fluctuations. (I ran it about 50 times with the values as coded just to check behaviour before posting. All my results were between 25.5'ish and 26.1'ish.) Best, Brian vdB From jfouhy at paradise.net.nz Wed Aug 10 00:13:08 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 10 Aug 2005 10:13:08 +1200 (NZST) Subject: [Tutor] help In-Reply-To: <9560d3c050809144572133bd7@mail.gmail.com> References: <9560d3c050809144572133bd7@mail.gmail.com> Message-ID: <1123625588.42f92a7435ea9@www.paradise.net.nz> Quoting Dan Deternova : > ok. i know python and want to turn all my programs i made when i was > learning python into Tkinter programs. i dont know how to make if > satments and display the output like this in python: > if cmd == quit: > print "press exit to quit" > i have no idea how to do that in Tkinter please help. Have a look at "Thinking in Tkinter": http://www.ferg.org/thinking_in_tkinter/ If you work through it, it should hopefully give you a better idea of how Tkinter programs work. -- John. From alan.gauld at freenet.co.uk Wed Aug 10 00:11:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 9 Aug 2005 23:11:59 +0100 Subject: [Tutor] (OT) Info on card games. References: Message-ID: <032c01c59d2f$5fc5cef0$bea68651@xp> > Nathan. >--------------------------------------------------------------- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. >--Benjamin Franklin >------------------------------------------------------------------- > P.S. Is this signature better than the last one? There was nothing wrong with the last one so far as I know, as to whether this is better I'll leave the literary experts to argue over that! :-) Alan G. From falcon3166 at hotmail.com Wed Aug 10 01:59:31 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 17:59:31 -0600 Subject: [Tutor] What can I do with this code? Message-ID: I coded the following just for fun: import random cool = ['Cool math!','Awesome!','Way to go!','Happy problem solving!'] while 1: start = raw_input("Do you want to do some math? Yes or No") if start == "Yes": x = int(raw_input("First number:")) y = int(raw_input("Second number:")) print x*y print random.choice(cool) elif start == "No": break print "Goodbye and happy problem solving!" What can I do with it, other than let it be a fun example of coding? Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/2b5146d1/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050809/2b5146d1/PinnoNathanPaul.vcf From amonroe at columbus.rr.com Wed Aug 10 02:16:33 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 9 Aug 2005 20:16:33 -0400 Subject: [Tutor] What can I do with this code? In-Reply-To: References: Message-ID: <92696282931.20050809201633@columbus.rr.com> > print random.choice(cool) > What can I do with it, other than let it be a fun example of coding? Make a Magic 8 ball! :^) Alan From falcon3166 at hotmail.com Wed Aug 10 02:38:52 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 18:38:52 -0600 Subject: [Tutor] How do I fix this ValueError? Message-ID: Here is the error: Traceback (most recent call last): File "D:\Python24\password.py", line 91, in -toplevel- save_file(sitelist) File "D:\Python24\password.py", line 22, in save_file for site,ID,passcard in sitelist.items(): ValueError: need more than 2 values to unpack Here is the code: #This is for a password protected program to store passwords. import getpass password = "hello" sitelist = {} def load_file(pw): import os filename = 'passcard.txt' if os.path.exists(filename): store = open(filename,'r') for line in store: site = line.strip() ID = line.strip() passcard = store.next().strip() pw[site] = ID and passcard else: store = open(filename,'w') # create new empty file store.close() def save_file(pw): store = open('passcard.txt',"w") for site,ID,passcard in sitelist.items(): store.write(site + '\n') store.write(ID + '\n') store.write(passcard + '\n') store.close() def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "9) Save and Exit" def add_site(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID: ") passcard = getpass.getpass("Password: ") sitelist[site] = [ID,passcard] def lookup_site(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitlist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_site(): print "Remove a login info card" site = raw_input("Site: ") if sitelist.has_key(site): del sitelist[site] else: print site," was not found." def print_login_info(): print "Login Info" for site in sitelist.keys(): print "Site: ",site," \tID: ",sitelist[site][0]," \tPassword: ",sitelist[site][1],"\n" print "The Password Program" print "By Nathan Pinno" print load_file(sitelist) answer = getpass.getpass("What is the password? ") while password != answer: print "The password is incorrect." answer = getpass.getpass("What is the password? ") print "Welcome to the second half of the program." while 1: main_menu() menu_choice = int(raw_input("Choose an option (1-4, or 9: ")) if menu_choice == 1: add_site() elif menu_choice == 2: lookup_site() elif menu_choice == 3: remove_site() elif menu_choice == 4: print_login_info() elif menu_choice == 9: break else: print "That's not an option!" save_file(sitelist) print "Have a nice day!" How do I fix the program, so that it will save the info without raising any errors? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/9c9e14e1/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050809/9c9e14e1/PinnoNathanPaul-0001.vcf From jfouhy at paradise.net.nz Wed Aug 10 03:13:11 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 10 Aug 2005 13:13:11 +1200 (NZST) Subject: [Tutor] How do I fix this ValueError? In-Reply-To: References: Message-ID: <1123636391.42f954a77dc36@www.paradise.net.nz> Quoting Nathan Pinno : > Here is the error: > > Traceback (most recent call last): > File "D:\Python24\password.py", line 91, in -toplevel- > save_file(sitelist) > File "D:\Python24\password.py", line 22, in save_file > for site,ID,passcard in sitelist.items(): > ValueError: need more than 2 values to unpack > > Here is the code: > > sitelist = {} sitelist is a dictionary. Let's see what the .items() method on dictionaries does: >>> d = { 1:'foo', 2:'bar', 3:'baz' } >>> d.items() [(1, 'foo'), (2, 'bar'), (3, 'baz')] So, if we iterate over d.items(), we are iterating over a list of tuples, each two elements long. >>> for item in d.items(): ... print item ... (1, 'foo') (2, 'bar') (3, 'baz') Now, we can "unpack" tuples. For example: >>> t = (1, 2) >>> x, y = t >>> x 1 >>> y 2 This only works if both sides of the = have the same number of things. >>> t = (1, 2, 3) >>> x, y = t # Not enough variables on the left hand side. Traceback (most recent call last): File "", line 1, in ? ValueError: too many values to unpack >>> x, y, z, w = t # Too many variables on the left hand side. Traceback (most recent call last): File "", line 1, in ? ValueError: need more than 3 values to unpack Now can you figure out what the ValueError you were getting means? -- John. From falcon3166 at hotmail.com Wed Aug 10 03:21:41 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 19:21:41 -0600 Subject: [Tutor] How do I fix this ValueError? References: <1123636391.42f954a77dc36@www.paradise.net.nz> Message-ID: I think it means that I can't store the data as a dictionary unless I store both the username and passcard as username|passcard. Am I right? --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: To: "Tutor mailing list" Sent: Tuesday, August 09, 2005 7:13 PM Subject: Re: [Tutor] How do I fix this ValueError? > Quoting Nathan Pinno : > >> Here is the error: >> >> Traceback (most recent call last): >> File "D:\Python24\password.py", line 91, in -toplevel- >> save_file(sitelist) >> File "D:\Python24\password.py", line 22, in save_file >> for site,ID,passcard in sitelist.items(): >> ValueError: need more than 2 values to unpack >> >> Here is the code: >> >> sitelist = {} > > sitelist is a dictionary. Let's see what the .items() method on > dictionaries does: > >>>> d = { 1:'foo', 2:'bar', 3:'baz' } >>>> d.items() > [(1, 'foo'), (2, 'bar'), (3, 'baz')] > > So, if we iterate over d.items(), we are iterating over a list of tuples, > each > two elements long. > >>>> for item in d.items(): > ... print item > ... > (1, 'foo') > (2, 'bar') > (3, 'baz') > > Now, we can "unpack" tuples. For example: > >>>> t = (1, 2) >>>> x, y = t >>>> x > 1 >>>> y > 2 > > This only works if both sides of the = have the same number of things. > >>>> t = (1, 2, 3) >>>> x, y = t # Not enough variables on the left hand side. > Traceback (most recent call last): > File "", line 1, in ? > ValueError: too many values to unpack >>>> x, y, z, w = t # Too many variables on the left hand side. > Traceback (most recent call last): > File "", line 1, in ? > ValueError: need more than 3 values to unpack > > Now can you figure out what the ValueError you were getting means? > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From negroup at gmail.com Wed Aug 10 03:46:02 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 10 Aug 2005 03:46:02 +0200 Subject: [Tutor] Question on classes/instances Message-ID: <2fdabf190508091846660efc9c@mail.gmail.com> Hi, Sorry for the subject a bit generic. This question comes from a simple program I'm doing. I could have a working solution, but considering my inexperience, I'm just asking if my approach is acceptable. This is a simple class to manage (actually to create and save) categories of things. Categories are represented as directories, while descriptions of categories are stored inside a file called .description inside the category directory. Look at the code.. class Category: def __init__(self, name=None, description=None): self.description = description if name: self.name = name else: return 'Value expected' def save(self): from os import access, F_OK, mkdir path = 'categories/%s' % self.name if access(path, F_OK): return 'Category already present' else: mkdir(path) if self.description: f = file('%s/.description' % path, 'w') f.write(self.description) f.close() and this is a simple function to get a list of categories, inside the same module of Category: def get_categories(): from os import listdir return listdir('categories') I would instead, that get_categories returns a list of instances of Category class instead of a list of strings, so that I can handle categories with proper APIs. I found this way: def get_categories(): from os import listdir # return listdir('categories') path = 'categories' categories = [Category(name, file('%s/%s/.description' % (path, name)).read()) for name in listdir('categories')] return categories Is it a good way to solve the problem? Otherwise, I would be glad if you could propose better solutions. Thanks for any clarification. From falcon3166 at hotmail.com Wed Aug 10 03:46:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 19:46:36 -0600 Subject: [Tutor] How to I make it save the data properly? (was Re: How do I fix this ValueError?) References: <1123636391.42f954a77dc36@www.paradise.net.nz> Message-ID: I tried fixing it. Here is the new code: #This is for a password protected program to store passwords. import getpass password = "hello" sitelist = {} def load_file(pw): import os filename = 'passcard.txt' if os.path.exists(filename): store = open(filename,'r') for line in store: site = line.strip() ID = line.strip().strip() pw[site] = ID else: store = open(filename,'w') # create new empty file store.close() def save_file(pw): store = open('passcard.txt',"w") for site,ID in sitelist.items(): store.write(site + '\n') store.write(ID + '\n') store.close() def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "9) Save and Exit" def add_site(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID and passcard, seperated by |: ") sitelist[site] = ID def lookup_site(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print site,sitelist[site] else: print site," was not found." def remove_site(): print "Remove a login info card" site = raw_input("Site: ") if sitelist.has_key(site): del sitelist[site] else: print site," was not found." def print_login_info(): print "Login Info" for site in sitelist.keys(): print "Site: ",site," \tID|Passcard: ",sitelist[site]+"\n" print "The Password Program" print "By Nathan Pinno" print load_file(sitelist) answer = getpass.getpass("What is the password? ") while password != answer: print "The password is incorrect." answer = getpass.getpass("What is the password? ") print "Welcome to the second half of the program." while 1: main_menu() menu_choice = int(raw_input("Choose an option (1-4, or 9: ")) if menu_choice == 1: add_site() elif menu_choice == 2: lookup_site() elif menu_choice == 3: remove_site() elif menu_choice == 4: print_login_info() elif menu_choice == 9: break else: print "That's not an option!" save_file(sitelist) print "Have a nice day!" Here is the screenshot when I ran it (I've turned my password into stars for security) It's in the IDLE if anyone's wondering: >>> The Password Program By Nathan Pinno Warning: Problem with getpass. Passwords may be echoed. What is the password? hello Welcome to the second half of the program. 1) Add a login info card 2) Lookup a login info card 3) Remove a login info card 4) Print Login info list 9) Save and Exit Choose an option (1-4, or 9: 1 Add a login info card Site: MSN Passport User ID and passcard, seperated by |: falcon3166 at hotmail.com|******** 1) Add a login info card 2) Lookup a login info card 3) Remove a login info card 4) Print Login info list 9) Save and Exit Choose an option (1-4, or 9: 4 Login Info Site: MSN Passport ID|Passcard: falcon3166 at hotmail.com|******** 1) Add a login info card 2) Lookup a login info card 3) Remove a login info card 4) Print Login info list 9) Save and Exit Choose an option (1-4, or 9: 9 Have a nice day! >>> ================================ RESTART >>> ================================ >>> The Password Program By Nathan Pinno Warning: Problem with getpass. Passwords may be echoed. What is the password? hello Welcome to the second half of the program. 1) Add a login info card 2) Lookup a login info card 3) Remove a login info card 4) Print Login info list 9) Save and Exit Choose an option (1-4, or 9: 4 Login Info Site: MSN Passport ID|Passcard: MSN Passport Site: falcon3166 at hotmail.com|******** ID|Passcard: falcon3166 at hotmail.com|******** 1) Add a login info card 2) Lookup a login info card 3) Remove a login info card 4) Print Login info list 9) Save and Exit Choose an option (1-4, or 9: 9 Have a nice day! >>> It's almost as it's saving the data seperately, instead of together. Why would it be doing this, and how do I fix it? --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- From jfouhy at paradise.net.nz Wed Aug 10 04:05:13 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 10 Aug 2005 14:05:13 +1200 (NZST) Subject: [Tutor] How to I make it save the data properly? (was Re: How do I fix this ValueError?) In-Reply-To: References: <1123636391.42f954a77dc36@www.paradise.net.nz> Message-ID: <1123639513.42f960d96517c@www.paradise.net.nz> Quoting Nathan Pinno : > I tried fixing it. Here is the new code: There are two likely places where you could have a problem: In your save function, or in your load function. Have you tried looking at the file where it saved the information? If the file doesn't contain the data it should, then your save function probably has an error. Otherwise, your load function probably has an error. Once you've got an idea of where the problem is, you can try to isolate it, so that you can fix the problem without having to plow through the rest of your code all the time. -- John. From falcon3166 at hotmail.com Wed Aug 10 04:24:51 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 20:24:51 -0600 Subject: [Tutor] How to I make it save the data properly? (was Re: How do Ifix this ValueError?) References: <1123636391.42f954a77dc36@www.paradise.net.nz> Message-ID: I fixed it. The problem was this line: ID = line.strip().strip() I fixed it so that it now reads: ID = store.next().strip() As a result, the program runs perfectly. Nathan Pinno --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: "Nathan Pinno" To: "Tutor mailing list" Sent: Tuesday, August 09, 2005 7:46 PM Subject: [Tutor] How to I make it save the data properly? (was Re: How do Ifix this ValueError?) >I tried fixing it. Here is the new code: > > #This is for a password protected program to store passwords. > import getpass > password = "hello" > sitelist = {} > > def load_file(pw): > import os > filename = 'passcard.txt' > if os.path.exists(filename): > store = open(filename,'r') > for line in store: > site = line.strip() > ID = line.strip().strip() > pw[site] = ID > else: > store = open(filename,'w') # create new empty file > store.close() > > def save_file(pw): > store = open('passcard.txt',"w") > for site,ID in sitelist.items(): > store.write(site + '\n') > store.write(ID + '\n') > store.close() > > > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "9) Save and Exit" > > def add_site(): > print "Add a login info card" > site = raw_input("Site: ") > ID = raw_input("User ID and passcard, seperated by |: ") > sitelist[site] = ID > > def lookup_site(): > print "Lookup a login info card" > site = raw_input("Site: ") > if sitelist.has_key(site): > print site,sitelist[site] > else: > print site," was not found." > > def remove_site(): > print "Remove a login info card" > site = raw_input("Site: ") > if sitelist.has_key(site): > del sitelist[site] > else: > print site," was not found." > > def print_login_info(): > print "Login Info" > for site in sitelist.keys(): > print "Site: ",site," \tID|Passcard: ",sitelist[site]+"\n" > > > print "The Password Program" > print "By Nathan Pinno" > print > load_file(sitelist) > answer = getpass.getpass("What is the password? ") > while password != answer: > print "The password is incorrect." > answer = getpass.getpass("What is the password? ") > > print "Welcome to the second half of the program." > while 1: > main_menu() > menu_choice = int(raw_input("Choose an option (1-4, or 9: ")) > if menu_choice == 1: > add_site() > elif menu_choice == 2: > lookup_site() > elif menu_choice == 3: > remove_site() > elif menu_choice == 4: > print_login_info() > elif menu_choice == 9: > break > else: > print "That's not an option!" > save_file(sitelist) > print "Have a nice day!" > > Here is the screenshot when I ran it (I've turned my password into stars > for > security) It's in the IDLE if anyone's wondering: > >>>> > The Password Program > By Nathan Pinno > > Warning: Problem with getpass. Passwords may be echoed. > What is the password? hello > Welcome to the second half of the program. > 1) Add a login info card > 2) Lookup a login info card > 3) Remove a login info card > 4) Print Login info list > 9) Save and Exit > Choose an option (1-4, or 9: 1 > Add a login info card > Site: MSN Passport > User ID and passcard, seperated by |: falcon3166 at hotmail.com|******** > 1) Add a login info card > 2) Lookup a login info card > 3) Remove a login info card > 4) Print Login info list > 9) Save and Exit > Choose an option (1-4, or 9: 4 > Login Info > Site: MSN Passport ID|Passcard: falcon3166 at hotmail.com|******** > > 1) Add a login info card > 2) Lookup a login info card > 3) Remove a login info card > 4) Print Login info list > 9) Save and Exit > Choose an option (1-4, or 9: 9 > Have a nice day! >>>> ================================ RESTART >>>> ================================ >>>> > The Password Program > By Nathan Pinno > > Warning: Problem with getpass. Passwords may be echoed. > What is the password? hello > Welcome to the second half of the program. > 1) Add a login info card > 2) Lookup a login info card > 3) Remove a login info card > 4) Print Login info list > 9) Save and Exit > Choose an option (1-4, or 9: 4 > Login Info > Site: MSN Passport ID|Passcard: MSN Passport > > Site: falcon3166 at hotmail.com|******** ID|Passcard: > falcon3166 at hotmail.com|******** > > 1) Add a login info card > 2) Lookup a login info card > 3) Remove a login info card > 4) Print Login info list > 9) Save and Exit > Choose an option (1-4, or 9: 9 > Have a nice day! >>>> > > It's almost as it's saving the data seperately, instead of together. Why > would it be doing this, and how do I fix it? > --------------------------------------------------------------- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. > --Benjamin Franklin > ------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Wed Aug 10 05:31:01 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 9 Aug 2005 21:31:01 -0600 Subject: [Tutor] Question on listing cards, then deleting one or more items by user's choice. Message-ID: Say I deal 5 cards, and then list them. How would I print the list of cards, with the numbers of each card(the position in the list)? Then delete a certain card or cards, based upon the user's choice?. Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050809/ec8540ee/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050809/ec8540ee/PinnoNathanPaul-0001.vcf From alan.gauld at freenet.co.uk Wed Aug 10 05:50:11 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 10 Aug 2005 04:50:11 +0100 Subject: [Tutor] How do I fix this ValueError? References: Message-ID: <036601c59d5e$9f3c6830$bea68651@xp> Nathan, > for site,ID,passcard in sitelist.items(): > ValueError: need more than 2 values to unpack The line is asking a dictionary (sitelist) to return 3 values (site, ID and passcard) from its items() method. But A dictionary stores things as name/value pairs so you can only get 2 items back not 3. Yopu need to change the code to read the key/value from the dictionary, and then, unpack the value data into the individual pieces. -------------------------- def save_file(pw): store = open('passcard.txt',"w") for site,ID,passcard in sitelist.items(): store.write(site + '\n') store.write(ID + '\n') store.write(passcard + '\n') store.close() def add_site(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID: ") passcard = getpass.getpass("Password: ") sitelist[site] = [ID,passcard] ---------------------------- You see here? you store ID and passcard as a list, so items() will return that list alomng with the key. You need to unpick them from the list. You might be better investigating the shelve module which allows you to store a dictionaruy to a file and access it as if it were still a dictionary. Shelve would be pretty much ideal for this application. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Wed Aug 10 07:14:01 2005 From: rabidpoobear at gmail.com (luke) Date: Wed, 10 Aug 2005 00:14:01 -0500 Subject: [Tutor] Question on listing cards, then deleting one or more items by user's choice. References: Message-ID: <004001c59d6a$53537600$aa0ca8c0@luke> >Say I deal 5 cards, and then list them. How would I print the list of cards, with the numbers >of each card(the position in the list)? Then delete a certain card or cards, based upon the >user's choice?. hope this points you in the right direction Nathan. -Luke #start of program #------------------------------ alist = ["1","2","3","4","5"] avar = '' while 1: if len(alist) == 0: break for item in range(len(alist)): print "item at list index ", item, " == ", alist[item] avar = raw_input("type -1 to exit or type the index of the item you want to remove ") try: avar = int(avar) if avar == -1: break elif avar > len(alist): print "oops error. indexOutOfRange" else: del(alist[avar]) except ValueError: print "oops error. please enter an integer value." #-------------------------------------------------- And the output: #------------------------ item at list index 0 == 1 item at list index 1 == 2 item at list index 2 == 3 item at list index 3 == 4 item at list index 4 == 5 type -1 to exit or type the index of the item you want to remove 0 item at list index 0 == 2 item at list index 1 == 3 item at list index 2 == 4 item at list index 3 == 5 type -1 to exit or type the index of the item you want to remove 3 item at list index 0 == 2 item at list index 1 == 3 item at list index 2 == 4 type -1 to exit or type the index of the item you want to remove 2 item at list index 0 == 2 item at list index 1 == 3 type -1 to exit or type the index of the item you want to remove 0 item at list index 0 == 3 type -1 to exit or type the index of the item you want to remove -1 From ml.cyresse at gmail.com Wed Aug 10 09:42:32 2005 From: ml.cyresse at gmail.com (mailing list) Date: Wed, 10 Aug 2005 19:42:32 +1200 Subject: [Tutor] help In-Reply-To: <1123625588.42f92a7435ea9@www.paradise.net.nz> References: <9560d3c050809144572133bd7@mail.gmail.com> <1123625588.42f92a7435ea9@www.paradise.net.nz> Message-ID: Also, you may want to consider something like easygui - http://www.ferg.org/easygui/ if all you need is simple dialogs. You may also want to consider Pythoncard - pythoncard.sourceforge.net, it's quite capable of more elaborate GUI stuff, but it's built on wxPython, which can be a little intimidating. That said, for 90% of stuff involving GUIs, Pythoncard would be fine, and the other 10% is generally stuff Tkinter can't do anyways. Good luck, Liam Clarke On 8/10/05, jfouhy at paradise.net.nz wrote: > Quoting Dan Deternova : > > > ok. i know python and want to turn all my programs i made when i was > > learning python into Tkinter programs. i dont know how to make if > > satments and display the output like this in python: > > if cmd == quit: > > print "press exit to quit" > > i have no idea how to do that in Tkinter please help. > > Have a look at "Thinking in Tkinter": http://www.ferg.org/thinking_in_tkinter/ > > If you work through it, it should hopefully give you a better idea of how > Tkinter programs work. > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Wed Aug 10 09:51:08 2005 From: ml.cyresse at gmail.com (mailing list) Date: Wed, 10 Aug 2005 19:51:08 +1200 Subject: [Tutor] Question on classes/instances In-Reply-To: <2fdabf190508091846660efc9c@mail.gmail.com> References: <2fdabf190508091846660efc9c@mail.gmail.com> Message-ID: Hi Negroup, First off, you may want to use os.path.join to create paths - path = 'categories/%s' % self.name could be - path = os.path.join(categories, self.name) This will ensure minimum hassle if you ever want to use this across multiple OS. Also, it looks a little tidier, and IMAO, tidier code is easier to maintain. As for what you're wanting to do with the list comprehension, once again I'd use os.path.join, but otherwise your comprehension looks workable. On 8/10/05, Negroup - wrote: > Hi, Sorry for the subject a bit generic. This question comes from a > simple program I'm doing. I could have a working solution, but > considering my inexperience, I'm just asking if my approach is > acceptable. > > This is a simple class to manage (actually to create and save) > categories of things. Categories are represented as directories, while > descriptions of categories are stored inside a file called > .description inside the category directory. Look at the code.. > > class Category: > def __init__(self, name=None, description=None): > self.description = description > if name: > self.name = name > else: > return 'Value expected' > > def save(self): > from os import access, F_OK, mkdir > > path = 'categories/%s' % self.name > if access(path, F_OK): > return 'Category already present' > else: > mkdir(path) > if self.description: > f = file('%s/.description' % path, 'w') > f.write(self.description) > f.close() > > and this is a simple function to get a list of categories, inside the > same module of Category: > def get_categories(): > from os import listdir > return listdir('categories') > > I would instead, that get_categories returns a list of instances of > Category class instead of a list of strings, so that I can handle > categories with proper APIs. I found this way: > > def get_categories(): > from os import listdir > # return listdir('categories') > path = 'categories' > categories = [Category(name, file('%s/%s/.description' % > (path, name)).read()) for name in listdir('categories')] > return categories > > Is it a good way to solve the problem? Otherwise, I would be glad if > you could propose better solutions. > > Thanks for any clarification. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Wed Aug 10 09:52:09 2005 From: ml.cyresse at gmail.com (mailing list) Date: Wed, 10 Aug 2005 19:52:09 +1200 Subject: [Tutor] Question on classes/instances In-Reply-To: References: <2fdabf190508091846660efc9c@mail.gmail.com> Message-ID: Erk, I of course meant - path = os.path.join('categories', self.name) On 8/10/05, mailing list wrote: > Hi Negroup, > > First off, you may want to use os.path.join to create paths - > > path = 'categories/%s' % self.name > > could be - > > path = os.path.join(categories, self.name) > > This will ensure minimum hassle if you ever want to use this across > multiple OS. > Also, it looks a little tidier, and IMAO, tidier code is easier to maintain. > > As for what you're wanting to do with the list comprehension, once > again I'd use os.path.join, but otherwise your comprehension looks > workable. > > On 8/10/05, Negroup - wrote: > > Hi, Sorry for the subject a bit generic. This question comes from a > > simple program I'm doing. I could have a working solution, but > > considering my inexperience, I'm just asking if my approach is > > acceptable. > > > > This is a simple class to manage (actually to create and save) > > categories of things. Categories are represented as directories, while > > descriptions of categories are stored inside a file called > > .description inside the category directory. Look at the code.. > > > > class Category: > > def __init__(self, name=None, description=None): > > self.description = description > > if name: > > self.name = name > > else: > > return 'Value expected' > > > > def save(self): > > from os import access, F_OK, mkdir > > > > path = 'categories/%s' % self.name > > if access(path, F_OK): > > return 'Category already present' > > else: > > mkdir(path) > > if self.description: > > f = file('%s/.description' % path, 'w') > > f.write(self.description) > > f.close() > > > > and this is a simple function to get a list of categories, inside the > > same module of Category: > > def get_categories(): > > from os import listdir > > return listdir('categories') > > > > I would instead, that get_categories returns a list of instances of > > Category class instead of a list of strings, so that I can handle > > categories with proper APIs. I found this way: > > > > def get_categories(): > > from os import listdir > > # return listdir('categories') > > path = 'categories' > > categories = [Category(name, file('%s/%s/.description' % > > (path, name)).read()) for name in listdir('categories')] > > return categories > > > > Is it a good way to solve the problem? Otherwise, I would be glad if > > you could propose better solutions. > > > > Thanks for any clarification. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From python-tutor at toddmaynard.com Wed Aug 10 10:47:33 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Wed, 10 Aug 2005 04:47:33 -0400 Subject: [Tutor] What can I do with this code? In-Reply-To: References: Message-ID: <200508100447.33555.python-tutor@toddmaynard.com> How about changing it into a math quiz program? You have the program output random problems ("What is 14 * 3 ?") And then you can output appropriate random insults, words of encouragement, or praise as appropriate until the user gets the answer right. Just be careful with division. You probably don't want to randomly generate a problem like ("What is 22 / 7 ?") (unless you are going to ask for the remainder too...) A trick to get around this problem is to use multiplication to pick a dividend. Psuedocode: Answer = randomNum Divisor = randomNum Dividend = Answer * Divisor Print "What is (Dividend) / (Divisor) ?" Have fun.... --Todd On Tuesday 09 August 2005 07:59 pm, Nathan Pinno wrote: > I coded the following just for fun: > > import random > cool = ['Cool math!','Awesome!','Way to go!','Happy problem solving!'] > while 1: > start = raw_input("Do you want to do some math? Yes or No") > if start == "Yes": > x = int(raw_input("First number:")) > y = int(raw_input("Second number:")) > print x*y > print random.choice(cool) > elif start == "No": > break > print "Goodbye and happy problem solving!" > > What can I do with it, other than let it be a fun example of coding? > > Nathan > --------------------------------------------------------------- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. > --Benjamin Franklin > ------------------------------------------------------------------- From negroup at gmail.com Wed Aug 10 10:52:40 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 10 Aug 2005 10:52:40 +0200 Subject: [Tutor] Customized endswith/startswith version Message-ID: <2fdabf19050810015255064f92@mail.gmail.com> Hi. >>> f = open('codes.txt') >>> # valid codes starts with 'abc' or '123' or 'ff5' >>> [valid for valid in f.readlines() if valid.startswith('abc') or valid.startswith('123') or valid.startswith('ff5')] This is just an example, in my application I don't need to check strings against a huge number of cases. If however it would happen, how to modify startswith in order to make it accept a list instead of a simple string? [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] Thanks From mi.janssen at gmail.com Wed Aug 10 12:23:30 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Wed, 10 Aug 2005 12:23:30 +0200 Subject: [Tutor] Customized endswith/startswith version In-Reply-To: <2fdabf19050810015255064f92@mail.gmail.com> References: <2fdabf19050810015255064f92@mail.gmail.com> Message-ID: <1ff2dfbf0508100323436f8a71@mail.gmail.com> On 8/10/05, Negroup - wrote: > >>> f = open('codes.txt') > >>> # valid codes starts with 'abc' or '123' or 'ff5' > >>> [valid for valid in f.readlines() if valid.startswith('abc') or > valid.startswith('123') or valid.startswith('ff5')] > > This is just an example, in my application I don't need to check > strings against a huge number of cases. If however it would happen, > how to modify startswith in order to make it accept a list instead of > a simple string? > > [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] the easy way is not to use the string method startwith but write your own function. So it looks like: [valid for valid in f.readlines() if startswith(valid, ['abc', '123', 'ff5'])] (I suppose you have your fun, writing a startswith-function for yourself?) The hard way is to subclass from str and ovewrite the default startswith function (or add your own function). Whilst subclassing isn't hard, here it can be, because strings are immutable types, which means that a new string is created ervery time we "mutate" one. Which in turn means that you have to know how to subclass from immutable types (using __new__ instead of __init__ and things like that I can't remember and allways have a hard time to figure it out again). And then you might want to subclass your file-object so that it spit out strings of your own class? regards Michael From kent37 at tds.net Wed Aug 10 13:11:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 07:11:44 -0400 Subject: [Tutor] Customized endswith/startswith version In-Reply-To: <1ff2dfbf0508100323436f8a71@mail.gmail.com> References: <2fdabf19050810015255064f92@mail.gmail.com> <1ff2dfbf0508100323436f8a71@mail.gmail.com> Message-ID: <42F9E0F0.4070808@tds.net> Michael Janssen wrote: > On 8/10/05, Negroup - wrote: >>how to modify startswith in order to make it accept a list instead of >>a simple string? >> >>[valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] > > > the easy way is not to use the string method startwith but write your > own function. So it looks like: > > [valid for valid in f.readlines() if startswith(valid, ['abc', '123', 'ff5'])] > > (I suppose you have your fun, writing a startswith-function for yourself?) Besides the obvious way to write this function (checking each item in the list using startswith()) you can use a regular expression to do this: re.match('abc|123|ff5', valid) > > The hard way is to subclass from str and ovewrite the default > startswith function (or add your own function). Whilst subclassing > isn't hard, here it can be, because strings are immutable types, which > means that a new string is created ervery time we "mutate" one. Which > in turn means that you have to know how to subclass from immutable > types (using __new__ instead of __init__ and things like that I can't > remember and allways have a hard time to figure it out again). And > then you might want to subclass your file-object so that it spit out > strings of your own class? You don't want to do this. The problem is that it's hard to get the behaviour you want. For example if you have class MyString and you do 'abc' + MyString('def') you probably want the result to be a MyString but it won't be. Some languages (Ruby and Objective-C at least) let you modify built-in classes like str by adding methods, but AFAIK Python doesn't allow that. Kent From negroup at gmail.com Wed Aug 10 14:41:21 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 10 Aug 2005 14:41:21 +0200 Subject: [Tutor] Customized endswith/startswith version In-Reply-To: <1ff2dfbf0508100323436f8a71@mail.gmail.com> References: <2fdabf19050810015255064f92@mail.gmail.com> <1ff2dfbf0508100323436f8a71@mail.gmail.com> Message-ID: <2fdabf1905081005416a431970@mail.gmail.com> 2005/8/10, Michael Janssen : > On 8/10/05, Negroup - wrote: > > > >>> f = open('codes.txt') > > >>> # valid codes starts with 'abc' or '123' or 'ff5' > > >>> [valid for valid in f.readlines() if valid.startswith('abc') or > > valid.startswith('123') or valid.startswith('ff5')] [cut] > The hard way is to subclass from [cut] > And then you might want to subclass your file-object so that it spit out > strings of your own class? Thanks for your reply. My solution is: foo.py class MyStr(str): def myStartsWith(self, options=[]): if (type(options) != type([]) or not options): return 'Error' else: for option in options: if self.startswith(option): return self return False class MyFile(file): def get_valid(self, options): return [MyStr(valid).myStartsWith(options) for valid in self.readlines() if MyStr(valid).myStartsWith(options)] codes.txt ff6 #ff5 123is a test abc another test abc last one >>> from foo import MyStr, MyFile >>> f = MyFile('codes.txt') >>> f.get_valid(['abc', '123', 'ff5']) ['123is a test\n', 'abc another test\n', 'abc last one\n'] From kent37 at tds.net Wed Aug 10 15:22:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 09:22:22 -0400 Subject: [Tutor] Customized endswith/startswith version In-Reply-To: <2fdabf1905081005416a431970@mail.gmail.com> References: <2fdabf19050810015255064f92@mail.gmail.com> <1ff2dfbf0508100323436f8a71@mail.gmail.com> <2fdabf1905081005416a431970@mail.gmail.com> Message-ID: <42F9FF8E.2030509@tds.net> Negroup - wrote: > My solution is: > foo.py > class MyStr(str): > def myStartsWith(self, options=[]): > if (type(options) != type([]) or not options): > return 'Error' > else: > for option in options: > if self.startswith(option): > return self > return False > > class MyFile(file): > def get_valid(self, options): > return [MyStr(valid).myStartsWith(options) for valid in > self.readlines() if MyStr(valid).myStartsWith(options)] > Hmm... This seems like a lot of work. If the only use for this class is to call myStartsWith(), I would just make a standalone myStartsWith() function and not enclose it in a class. It will be less code for the definition and at point of call. MyFile has the same problem - it isn't really giving any return on the investment of creating a class, you could just have a standalone get_valid function. Instead of returning 'Error' for a bad argument you should raise an exception, TypeError or ValueError or maybe both if you want to be really literal about what the exceptions mean. In fact, your current code is a good example of why exceptions are a good idea. The way you have it now, a caller must explicitly check for the string 'Error'. Your MyFile class doesn't do this and it will happily accept any 'valid' if options is None or not a list. Also, you can't distinguish between the result of MyStr('Error').myStartsWith(None) and MyStr('Error').myStartsWith(['E'). Raising an exception solves both these problems. Oh, you might want to settle on a naming style, either camelCase or embedded_underscores but not both... Kent From 3dbernard at gmail.com Wed Aug 10 17:11:54 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 10 Aug 2005 11:11:54 -0400 Subject: [Tutor] SSH commands in Python on Linux Message-ID: <61d0e2b4050810081127a958ad@mail.gmail.com> Hello, I'm trying to make a script to send a SSH command from a Linux computer to another Linux compter. The Python syntax I'm using... import os os.system( 'ssh root at 192.168.10.204 "ls"' ) Now the problem is that I'm always asked for the password. So my question is two-fold: 1- Is there a way to not be asked for the root password? 2- If not, then is it possible to feed the SSH password input with my Python script? I have about stdin redirection, but I have to admit that I'm a bit lost and I don't know if it applies to SSH input as well. Right now I'm using the ls command to list processes, however ultimately I want to be able to kill some processes within a loop (this is for render farm management). Thanks Bernard From python-tutor at toddmaynard.com Wed Aug 10 17:53:20 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Wed, 10 Aug 2005 11:53:20 -0400 Subject: [Tutor] SSH commands in Python on Linux In-Reply-To: <61d0e2b4050810081127a958ad@mail.gmail.com> References: <61d0e2b4050810081127a958ad@mail.gmail.com> Message-ID: <200508101153.20905.python-tutor@toddmaynard.com> Ignoring the python stuff for the moment.... In answer to Question 1., You want to use Public Key authentication...this will let you log in without a password. Google for SSH Public Key Authentication will give you several hits for the howto's One pretty good one was http://www.puddingonline.com/~dave/publications/SSH-with-Keys-HOWTO/document/html-one-page/SSH-with-Keys-HOWTO.html If you have access to Linux Journal magazine, they just had a great article about it in the Sept issue. Good luck and have fun, Todd On Wednesday 10 August 2005 11:11 am, Bernard Lebel wrote: > Hello, > > I'm trying to make a script to send a SSH command from a Linux > computer to another Linux compter. > > The Python syntax I'm using... > > > import os > os.system( 'ssh root at 192.168.10.204 "ls"' ) > > > Now the problem is that I'm always asked for the password. So my > question is two-fold: > > 1- Is there a way to not be asked for the root password? > 2- If not, then is it possible to feed the SSH password input with my > Python script? I have about stdin redirection, but I have to admit > that I'm a bit lost and I don't know if it applies to SSH input as > well. > > Right now I'm using the ls command to list processes, however > ultimately I want to be able to kill some processes within a loop > (this is for render farm management). > > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lists at janeden.org Wed Aug 10 17:56:25 2005 From: lists at janeden.org (Jan Eden) Date: Wed, 10 Aug 2005 17:56:25 +0200 Subject: [Tutor] Untainting CGI parameters Message-ID: Hi, I would like to untaint all parameters with which my CGI script is called. Example: if parameters.has_key('type'): match = re.search('\w+', parameters['type'].value) type = match.group() else: type = 'page' In Perl, I used the ternary operator to write it like this: my $type = ($parameters{type} && ($parameters{type} =~ /^(\w+)$/)) ? $1 : 'page'; While this is not the most beautiful code to look at, I have a weakness for compact programs - so can I shorten the Python equivalent somehow? Thanks, Jan -- A good programmer is someone who looks both ways before crossing a one-way street. - Doug Linder From kent37 at tds.net Wed Aug 10 18:32:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 12:32:38 -0400 Subject: [Tutor] Untainting CGI parameters In-Reply-To: References: Message-ID: <42FA2C26.60308@tds.net> Jan Eden wrote: > Hi, > > I would like to untaint all parameters with which my CGI script is called. Example: > > if parameters.has_key('type'): > match = re.search('\w+', parameters['type'].value) > type = match.group() > else: type = 'page' OK, I don't know much Perl but I don't think these two snippets do the same thing. For one thing the regexes are different, second in the Python you need to check if the match succeeds. I would write it as type = 'page' if parameters.has_key('type'): match = re.search('^\w+$', parameters['type'].value) if match: type = match.group() or maybe try: match = re.search('^\w+$', parameters['type'].value) type = match.group() except KeyError, AttributeError: type = 'page' > In Perl, I used the ternary operator to write it like this: > > my $type = ($parameters{type} && ($parameters{type} =~ /^(\w+)$/)) ? $1 : 'page'; > > While this is not the most beautiful code to look at, I have a > weakness for compact programs - so can I shorten the Python > equivalent somehow? mmm, not sure how to do that...Python doesn't put such a premium on compactness. If you have to do it a lot just put it in a function and call that... Kent From dyoo at hkn.eecs.berkeley.edu Wed Aug 10 19:46:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 10 Aug 2005 10:46:54 -0700 (PDT) Subject: [Tutor] Customized endswith/startswith version In-Reply-To: <2fdabf19050810015255064f92@mail.gmail.com> Message-ID: > This is just an example, in my application I don't need to check strings > against a huge number of cases. If however it would happen, how to > modify startswith in order to make it accept a list instead of a simple > string? > > [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] Hello, Conceptually, we can define our own true/false functions ("predicates") to help make it easy to express this. As a concrete example, let's simplify the problem a bit. Let's say that we'd like to show all numbers between 0-100 that are divisible by two, three, and five: ####### def divisibleBy(m, n): """Returns true if m is divisible by n.""" return m % n == 0 def divisibleByTwoThreeAndFive(x): return divisibleBy(x, 2) and divisibleBy(x, 3) and divisibleBy(x, 5) print [n for n in range(100) if divisibleByTwoThreeAndFive(n)] ####### We don't have something builtin that tells us if a number is divisible by two, three, and five: we can define our own functions to do this. divisibleBy() tells us if one number is divisible by another, and we can use that to help us. But it might seem weird that we have a custom function to take those three hardcoded numbers. divisibleByTwoThreeAndFive() is a bit of a mouthful. Let's fix that: we'll add one more parameter that takes a list of arguments: ####### def divisibleByAll(n, listOfNumbers): """Returns true if n is divisible by all of the numbers in listOfNumbers.""" for divisor in listOfNumbers: if not divisibleBy(n, divisor): return False return True ####### And now we can say: ####### print [n for n in range(100) if divisibleByAll(n, [2, 3, 5])] ####### Does this make sense? Please feel free to ask more questions about this. From bvande at po-box.mcgill.ca Wed Aug 10 08:11:21 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 10 Aug 2005 02:11:21 -0400 Subject: [Tutor] Question on listing cards, then deleting one or more items by user's choice. In-Reply-To: References: Message-ID: <42F99A89.4020300@po-box.mcgill.ca> Nathan Pinno said unto the world upon 2005-08-09 23:31: > Say I deal 5 cards, and then list them. How would I print the list > of cards, with the numbers of each card(the position in the list)? > Then delete a certain card or cards, based upon the user's choice?. > > > Nathan Nathan, I write this not in the spirit of "I told you so" but to point out what I meant before. If you have your card-dealing function just print out the cards as it picks them, then later on in your program, the information about what cards were picked is not available. If instead, your deal function returns them, binds the return value to a name (as my code of yesterday did), the information is still kicking around in the name to which the returned card selection was bound. If you look at Luke's example, he started it all off with binding the name alist to a sequence which the rest of his code drew on to facilitate the user's choosing things out of. Replace Luke's alist = ["1","2","3","4","5"] with cards_dealt = function_that_returns_a_deal() and you're making progress. With a "prints but does not return" dealing function, you cannot do this. Best, Brian vdB From jeffpeery at yahoo.com Wed Aug 10 21:50:26 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 10 Aug 2005 12:50:26 -0700 (PDT) Subject: [Tutor] distutils? Message-ID: <20050810195026.57099.qmail@web30514.mail.mud.yahoo.com> Hello, I was wondering what is the difference between the distutils core and py2exe... they look the same to me? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050810/c27d7558/attachment.htm From mwalsh at groktech.org Wed Aug 10 22:04:42 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Wed, 10 Aug 2005 16:04:42 -0400 Subject: [Tutor] SSH commands in Python on Linux In-Reply-To: <61d0e2b4050810081127a958ad@mail.gmail.com> References: <61d0e2b4050810081127a958ad@mail.gmail.com> Message-ID: <42FA5DDA.9050905@groktech.org> Bernard Lebel wrote: > Hello, Hi Bernard, > I'm trying to make a script to send a SSH command from a Linux > computer to another Linux compter. > > The Python syntax I'm using... > > > import os > os.system( 'ssh root at 192.168.10.204 "ls"' ) > > > Now the problem is that I'm always asked for the password. So my > question is two-fold: > > 1- Is there a way to not be asked for the root password? > 2- If not, then is it possible to feed the SSH password input with my > Python script? I have about stdin redirection, but I have to admit > that I'm a bit lost and I don't know if it applies to SSH input as > well. you might also have a look at the pexpect module, found here: http://pexpect.sourceforge.net/, I've found it to be a very useful tool for working with interactive shell apps. There are a few ssh examples provided in a separate download (pexpect-examples.tgz http://sourceforge.net/project/showfiles.php?group_id=59762) HTH, Marty From kent37 at tds.net Wed Aug 10 22:06:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 16:06:58 -0400 Subject: [Tutor] distutils? In-Reply-To: <20050810195026.57099.qmail@web30514.mail.mud.yahoo.com> References: <20050810195026.57099.qmail@web30514.mail.mud.yahoo.com> Message-ID: <42FA5E62.7050506@tds.net> Jeff Peery wrote: > Hello, I was wondering what is the difference between the distutils core > and py2exe... they look the same to me? thanks. distutils.core basically installs the .py files needed by an application or library. It can also build extension modules, but it doesn't try to install Python or other libraries you may depend on. It is cross-platform and intended for installation on a system that already has Python and any needed libs. py2exe bundles up everything needed to run an app, including Python and any referenced libraries. It creates a package that can run on a system without Python installed. Also py2exe is for Windows executables only. Kent From kent37 at tds.net Wed Aug 10 22:23:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 16:23:24 -0400 Subject: [Tutor] distutils? In-Reply-To: <42FA5E62.7050506@tds.net> References: <20050810195026.57099.qmail@web30514.mail.mud.yahoo.com> <42FA5E62.7050506@tds.net> Message-ID: <42FA623C.3000304@tds.net> I should add that distutils gives you some help on the packaging end of things, too - not just for installing. And py2exe is an addon to distutils. Kent Kent Johnson wrote: > Jeff Peery wrote: > >>Hello, I was wondering what is the difference between the distutils core >>and py2exe... they look the same to me? thanks. > > > distutils.core basically installs the .py files needed by an application or library. It can also build extension modules, but it doesn't try to install Python or other libraries you may depend on. It is cross-platform and intended for installation on a system that already has Python and any needed libs. > > py2exe bundles up everything needed to run an app, including Python and any referenced libraries. It creates a package that can run on a system without Python installed. Also py2exe is for Windows executables only. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jonasmg at SoftHome.net Wed Aug 10 23:47:39 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Wed, 10 Aug 2005 22:47:39 +0100 Subject: [Tutor] Net mask in hex. to dec. Message-ID: <42FA75FB.1090206@SoftHome.net> Hi, I get the netmask (mask="0xffffff00") from ifconfig in openbsd, and i would convert it to decimal (255.255.255.0) I think that socket module doesn't help on this. So I'll have to make something as this for separate 'mask' [s[i:i+2] for i in range(0, len(s), 2)] then i could use int('', 16) From alan.gauld at freenet.co.uk Wed Aug 10 23:54:32 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 10 Aug 2005 22:54:32 +0100 Subject: [Tutor] Customized endswith/startswith version References: <2fdabf19050810015255064f92@mail.gmail.com> Message-ID: <03c001c59df6$176c0d00$bea68651@xp> | >>> [valid for valid in f.readlines() if valid.startswith('abc') or | valid.startswith('123') or valid.startswith('ff5')] | | how to modify startswith in order to make it accept a list instead of | a simple string? | | [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] If the strings are all three chars you could do: [valid for valid in f if valid[:3] in ['abc', '123', 'ff5'] ] HTH, Alan G. From alan.gauld at freenet.co.uk Wed Aug 10 23:59:17 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 10 Aug 2005 22:59:17 +0100 Subject: [Tutor] SSH commands in Python on Linux References: <61d0e2b4050810081127a958ad@mail.gmail.com> Message-ID: <03da01c59df6$c131a8e0$bea68651@xp> import os os.system( 'ssh root at 192.168.10.204 "ls"' ) system is probably the wrong thing to use here since it doesn't return any output only a final error code. > 1- Is there a way to not be asked for the root password? Yes but you need to set up user security keys and such. The ssh man pages explain it in fairly dense detail. > 2- If not, then is it possible to feed the SSH password > input with my Python script? Yes but you probably need the python version of expect module. Not part of the standard library but available on source-forge I believe. Alan G. From alan.gauld at freenet.co.uk Thu Aug 11 00:04:33 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 10 Aug 2005 23:04:33 +0100 Subject: [Tutor] Untainting CGI parameters References: Message-ID: <03e201c59df7$80294b40$bea68651@xp> > I would like to untaint all parameters with which my CGI script is > called. Example: Can you explain 'untaint'??? Not a term I'm familiar with... > if parameters.has_key('type'): > match = re.search('\w+', parameters['type'].value) > type = match.group() > else: type = 'page' I Python "it's better to ask forgiveness than permission" so... try: type = re.search('\w+', parameters['type'].value).group() except KeyError: type = 'page' HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From danf_1979 at yahoo.es Thu Aug 11 02:47:21 2005 From: danf_1979 at yahoo.es (_ Dan _) Date: Thu, 11 Aug 2005 02:47:21 +0200 (CEST) Subject: [Tutor] AppendText as new lines In-Reply-To: Message-ID: <20050811004721.59589.qmail@web25207.mail.ukl.yahoo.com> Hi, to all. Well, I have some list results that I must write to a Window. This is what I have tu show: (('Name1',), ('Name2',)) This is my "show function" def Listar_Mostrar(self,event): connect = MySQLdb.connect(host,user,passwd,db) cursor = connect.cursor() cursor.execute("SELECT nombres FROM apiterapia") result = cursor.fetchall() for record in result: self.text_ctrl_listar.AppendText(record[0]) The results are shown in the text window as: Name1Name2 And what I really want to do is something like this: Name1 Name2 Anybody knows how this can be done? Thanks to all of you. ______________________________________________ Renovamos el Correo Yahoo! Nuevos servicios, m?s seguridad http://correo.yahoo.es From kent37 at tds.net Thu Aug 11 03:06:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Aug 2005 21:06:33 -0400 Subject: [Tutor] AppendText as new lines In-Reply-To: <20050811004721.59589.qmail@web25207.mail.ukl.yahoo.com> References: <20050811004721.59589.qmail@web25207.mail.ukl.yahoo.com> Message-ID: <42FAA499.2050708@tds.net> _ Dan _ wrote: > for record in result: > > self.text_ctrl_listar.AppendText(record[0]) > > The results are shown in the text window as: > Name1Name2 > > And what I really want to do is something like this: > Name1 > Name2 Looks like you need some newlines: self.text_ctrl_listar.AppendText(record[0]) self.text_ctrl_listar.AppendText('\n') Kent From srini_iyyer_bio at yahoo.com Thu Aug 11 06:41:37 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 10 Aug 2005 21:41:37 -0700 (PDT) Subject: [Tutor] pls. help me in sorting and choosing Message-ID: <20050811044137.24519.qmail@web53505.mail.yahoo.com> Dear Group: After cutting short a lot of gory detail, I finally arrived at atomic level of my problem and here I crash. I guess this crash is due to not so strong logic (hopefully i get better with more and more exerise in solving problems). I have a file with two columns: Column A (accession number) and column B scores of that identifier: NM_004619.2 4910.8 NM_004619.2 2716.3 NM_145759.1 4805.7 NM_145759.1 2716.3 XM_378692.1 56.00 By looking at this small table, I see that NM_004619.2 and NM_145759.1 are better and high scoring elements. Whereas, XM_378692.1 is a low scoring guy when compared to two others. I want to pick NM_004619.2 and NM_145759.1 and leave XM_ guy. If for instance I have another guy with 1005.6, then I would also pick that. My question is how can I code to distinguish all high scoring group and all low scoring group. Any one, please help me on this issue. Thank you in advance. Srini ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From jfouhy at paradise.net.nz Thu Aug 11 06:59:28 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 11 Aug 2005 16:59:28 +1200 (NZST) Subject: [Tutor] pls. help me in sorting and choosing In-Reply-To: <20050811044137.24519.qmail@web53505.mail.yahoo.com> References: <20050811044137.24519.qmail@web53505.mail.yahoo.com> Message-ID: <1123736368.42fadb3025816@www.paradise.net.nz> Quoting Srinivas Iyyer : > My question is how can I code to distinguish all high > scoring group and all low scoring group. One thing you need to decide is what it means to be high scoring. Is an element high scoring if its score is above some threshhold, or it a percentage? Or something else? (eg: "an element is high scoring if its score is > 1000" or "an element is high scoring if it is in the top 20% when ranked by score") Do you know how to read your data in from your file? If you have a file looking like this: NM_004619.2 4910.8 NM_004619.2 2716.3 NM_145759.1 4805.7 NM_14 5759.1 2716.3 XM_378692.1 56.00 then I would convert that into a list of tuples: [("NM_004619.2", 4910.8), ("NM_004619.2", 2716.3), ("NM_145759.1", 4805.7), ("NM_14 5759.1", 2716.3), ("XM_378692.1", 56.00)] If you can do this, then it is easy to ask python to sort it for you. >>> data = [("NM_004619.2", 4910.8), ("NM_004619.2", 2716.3), ("NM_145759.1", 4805.7), ("NM_14 5759.1", 2716.3), ("XM_378692.1", 56.00)] >>> data.sort(key=lambda x: x[1], reverse=True) >>> data [('NM_004619.2', 4910.8000000000002), ('NM_145759.1', 4805.6999999999998), ('NM_004619.2', 2716.3000000000002), ('NM_14 5759.1', 2716.3000000000002), ('XM_378692.1', 56.0)] Now, the first elements in the list have the highest score, and you can decide how far down to go. Alternatively, you could ask for all elements above a certain score: >>> [x for x in data if x[1] > 3000] [('NM_004619.2', 4910.8000000000002), ('NM_145759.1', 4805.6999999999998)] HTH! (note: key= and reverse= arguments to sort() are a new feature in Python2.4. If you are using an earlier Python, you will have to do things slightly differently. Probably the easiest change to make would be to have the score be the first element in the tuples) -- John. From srini_iyyer_bio at yahoo.com Thu Aug 11 07:23:07 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 10 Aug 2005 22:23:07 -0700 (PDT) Subject: [Tutor] pls. help me in sorting and choosing In-Reply-To: <1123736368.42fadb3025816@www.paradise.net.nz> Message-ID: <20050811052307.75526.qmail@web53501.mail.yahoo.com> Hi John: thank you for your reply: There is no cutoff. I would choose top 20% of the all the scores. 2. I know how to read a tab delim txt file as list but not into the tupeles. Apologies for my inexperience. can you please help me further. thanks srini --- jfouhy at paradise.net.nz wrote: > Quoting Srinivas Iyyer : > > > My question is how can I code to distinguish all > high > > scoring group and all low scoring group. > > One thing you need to decide is what it means to be > high scoring. Is an element > high scoring if its score is above some threshhold, > or it a percentage? Or > something else? > > (eg: "an element is high scoring if its score is > > 1000" or "an element is high > scoring if it is in the top 20% when ranked by > score") > > Do you know how to read your data in from your file? > If you have a file looking > like this: > > NM_004619.2 4910.8 > NM_004619.2 2716.3 > NM_145759.1 4805.7 > NM_14 5759.1 2716.3 > XM_378692.1 56.00 > > then I would convert that into a list of tuples: > > [("NM_004619.2", 4910.8), ("NM_004619.2", 2716.3), > ("NM_145759.1", 4805.7), > ("NM_14 5759.1", 2716.3), ("XM_378692.1", 56.00)] > > If you can do this, then it is easy to ask python to > sort it for you. > > >>> data = [("NM_004619.2", 4910.8), ("NM_004619.2", > 2716.3), ("NM_145759.1", > 4805.7), ("NM_14 5759.1", 2716.3), ("XM_378692.1", > 56.00)] > >>> data.sort(key=lambda x: x[1], reverse=True) > >>> data > [('NM_004619.2', 4910.8000000000002), > ('NM_145759.1', 4805.6999999999998), > ('NM_004619.2', 2716.3000000000002), ('NM_14 > 5759.1', 2716.3000000000002), > ('XM_378692.1', 56.0)] > > Now, the first elements in the list have the highest > score, and you can decide > how far down to go. > > Alternatively, you could ask for all elements above > a certain score: > > >>> [x for x in data if x[1] > 3000] > [('NM_004619.2', 4910.8000000000002), > ('NM_145759.1', 4805.6999999999998)] > > HTH! > > (note: key= and reverse= arguments to sort() are a > new feature in Python2.4. If > you are using an earlier Python, you will have to do > things slightly > differently. Probably the easiest change to make > would be to have the score be > the first element in the tuples) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From jfouhy at paradise.net.nz Thu Aug 11 07:34:47 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 11 Aug 2005 17:34:47 +1200 (NZST) Subject: [Tutor] pls. help me in sorting and choosing In-Reply-To: <20050811052307.75526.qmail@web53501.mail.yahoo.com> References: <20050811052307.75526.qmail@web53501.mail.yahoo.com> Message-ID: <1123738487.42fae3774dffd@www.paradise.net.nz> Quoting Srinivas Iyyer : > 2. I know how to read a tab delim txt file as list but > not into the tupeles. Apologies for my inexperience. How are you currently reading the file? --- can you show us some code? You can create tuples directly. For example: >>> x = 3 >>> y = 7 >>> t = (x, y) >>> t (3, 7) or: >>> squares = [] >>> for i in range(10): ... squares.append((i, i**2)) # Note the double parentheses! ... >>> squares [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)] You can read more about tuples in the python tutorial; section 5.3. (see http://www.python.org/) -- John. From rdm at rcblue.com Thu Aug 11 08:33:35 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 10 Aug 2005 23:33:35 -0700 Subject: [Tutor] PyChecker: Installing and or Using Message-ID: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> It appears to me that I've found a bug in PyChecker (see below). Am I correct? Dick Resending my last post: Kent Johnson wrote at 06:13 8/9/2005: >Dick Moores wrote: > > Win XP. Python2.4. > > > > Javier Ruere suggested getting PyChecker or PyLint. I found PyChecker > and > > put the pychecker-0.8.14 folder in > > C:\Python24\Lib\site-packages\PyChecker. I don't really know what I'm > > doing (obviously?), but I added > > C:\Python24\Lib\site-packages\PyChecker\pychecker-0.8.14\pychecker to > > PYTHONPATH. > >You should only do one of these; packages in site-packages are already >in the path, though you have too many levels of directories...the >install should do this right. > > > My probably dumb question is, how do I "do" those things? I've tried > > "python setup.py install" at the command line (at Run, I entered cmd and > > then at the prompt in the window I entered python setup.py install. No > > good. Then I tried python pychecker/checker.py . I got: > > > > C:\Documents and Settings\Dick>python pychecker/checker.py > > 'python' is not recognized as an internal or external command, > > operable program or batch file. > >You have to add 'C:\Python24' to your PATH environment variable, or give >the full path in the command line as >C:\Python24\python setup.py install > >Also when you run setup.py you will have to be in the directory >containing setup.py. OK, I got it to install. But now, when I try to use checker.py I get: Warning (from warnings module): File "C:\Python24\lib\site-packages\pychecker\checker.py", line 609 m = imp.init_builtin(moduleName) DeprecationWarning: the regex module is deprecated; please use the re module That line 609 is in this function in checker.py: def fixupBuiltinModules(needs_init=0): for moduleName in sys.builtin_module_names : if needs_init: _ = Module(moduleName, 0) module = _allModules.get(moduleName, None) if module is not None : try : m = imp.init_builtin(moduleName) except ImportError : pass else : extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, []) module.attributes = [ '__dict__' ] + dir(m) + extra_attrs >>> import sys >>> sys.builtin_module_names ('__builtin__', '__main__', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_csv', '_heapq', '_hotshot', '_locale', '_multibytecodec', '_random', '_sre', '_subprocess', '_symtable', '_weakref', '_winreg', 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', 'collections', 'datetime', 'errno', 'exceptions', 'gc', 'imageop', 'imp', 'itertools', 'marshal', 'math', 'md5', 'mmap', 'msvcrt', 'nt', 'operator', 'parser', 'regex', 'rgbimg', 'sha', 'signal', 'strop', 'struct', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport') >>> What now? Dick From dyoo at hkn.eecs.berkeley.edu Thu Aug 11 09:06:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 Aug 2005 00:06:28 -0700 (PDT) Subject: [Tutor] pls. help me in sorting and choosing In-Reply-To: <20050811052307.75526.qmail@web53501.mail.yahoo.com> Message-ID: On Wed, 10 Aug 2005, Srinivas Iyyer wrote: > There is no cutoff. I would choose top 20% of the all the scores. Hi Srinivas, Those are GenBank accessions, aren't they? > 2. I know how to read a tab delim txt file as list but not into the > tupeles. Can you write a function that takes a line of the list, and turns it into a single tuple? That is, given: ###### line = "NM_004619.2 2716.3" ###### can you write a function that takes that tab-delimited line and extracts a tuple from it? If you can write that function, then you should be in business. Alternatively, have you looked at the CSV library yet? http://www.python.org/doc/lib/module-csv.html Good luck! From lists at janeden.org Thu Aug 11 09:21:35 2005 From: lists at janeden.org (Jan Eden) Date: Thu, 11 Aug 2005 09:21:35 +0200 Subject: [Tutor] Untainting CGI parameters In-Reply-To: <42FA2C26.60308@tds.net> Message-ID: Hi Kent, hi Alan, Kent Johnson wrote on 10.08.2005: >OK, I don't know much Perl but I don't think these two snippets do >the same thing. For one thing the regexes are different, second in >the Python you need to check if the match succeeds. > >>my $type = ($parameters{type} && ($parameters{type} =~ /^(\w+)$/)) ? >>$1 : 'page'; >> Ok, you got me - the regexes were indeed not identical, and only the Perl code included a check if the match was successful. Alan G wrote on 10.08.2005: >>I would like to untaint all parameters with which my CGI script is >>called. Example: > >Can you explain 'untaint'??? Not a term I'm familiar with... "Untainting" CGI parameters is derived from Perl's taint mode - turning on this mode makes Perl assume that all input coming from the user of a script is probably evil and needs to be hand-checked before using it for anything outside the script itself (e.g. calling external programs, removing files, sending mail etc.) > >>if parameters.has_key('type'): match = re.search('\w+', >>parameters['type'].value) type = match.group() else: type = 'page' > >I Python "it's better to ask forgiveness than permission" so... > >try: type = re.search('\w+', parameters['type'].value).group() except >KeyError: type = 'page' > Thank you - that wraps up two lines in one, just as I intended to. I tried it before but most have mixed up something when calling the group() method on the object returned by the search method immediately. I will combine Kent's and your suggestion, because he included a check for an AttributeError: try: type = re.search('\w+', parameters['type'].value).group() except except KeyError, AttributeError: type = 'page' Thank you both, Jan -- Remember: use logout to logout. From alan.gauld at freenet.co.uk Thu Aug 11 10:06:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 11 Aug 2005 09:06:52 +0100 Subject: [Tutor] Untainting CGI parameters References: Message-ID: <042501c59e4b$a2e3efb0$bea68651@xp> > I will combine Kent's and your suggestion, because he included a > check for an AttributeError: > OK, as a slightly more perl-ish solution to the no Attribute problem you could also do this: try: type = re.search('\w+', parameters['type'].value).group() or 'page' except KeyError: type = 'page' HTH Alan G. From starryhaze at hotmail.com Thu Aug 11 10:58:06 2005 From: starryhaze at hotmail.com (Hazel Bard) Date: Thu, 11 Aug 2005 08:58:06 +0000 Subject: [Tutor] (no subject) Message-ID: Hi, ive not been programming in python very long, but im using the wxPython to do GUI stuff. Ive been looking at some basic applications, and ive been having some funny problems with them. First of all, which is the best way to import wxPython, because some people seem to use 'import wx' and some us 'from wxPython.wx import *'. If i load the program with one of them, it doesn't run, and then i change it to the other and it runs, but then the next time i load the program with that one it will not work but if i change it to the first one it does run. Sorry if that sounds confusing... its hard to explain, but i just don't know why it does that! Also, i looked at a simple program, with a frame and a menu with file and exit. The first time you get the program to run, it all works fine, but if you exit the program, and then run it again the exit and other buttons stop working. The next time you run the program though it all works again... it seems to be that when you load the program, it is only the first, third, fifth etc time you run the program that it works, and i really dont know why it does that either! any suggestions? is it to do with python, or the platform or the program because it seems to do it with every program i run... Thankyou From lists at janeden.org Thu Aug 11 11:43:17 2005 From: lists at janeden.org (Jan Eden) Date: Thu, 11 Aug 2005 11:43:17 +0200 Subject: [Tutor] Untainting CGI parameters In-Reply-To: <042501c59e4b$a2e3efb0$bea68651@xp> Message-ID: Hi Alan, Alan G wrote on 11.08.2005: >> I will combine Kent's and your suggestion, because he included a >> check for an AttributeError: >> > >OK, as a slightly more perl-ish solution to the no Attribute problem >you could also do this: > >try: > type = re.search('\w+', parameters['type'].value).group() or >'page' >except KeyError: > type = 'page' > Are you sure? >>> a = 'abcd' >>> import re >>> type = re.search('\d+',a).group() or 'page' Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'group' If the search does not succeed, the returned object has the value None, which has no attribute group. Thanks, Jan -- There are two major products that come out of Berkeley: LSD and UNIX. We don't believe this to be a coincidence. - Jeremy S. Anderson From kent37 at tds.net Thu Aug 11 13:45:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Aug 2005 07:45:32 -0400 Subject: [Tutor] pls. help me in sorting and choosing In-Reply-To: <1123736368.42fadb3025816@www.paradise.net.nz> References: <20050811044137.24519.qmail@web53505.mail.yahoo.com> <1123736368.42fadb3025816@www.paradise.net.nz> Message-ID: <42FB3A5C.3040302@tds.net> jfouhy at paradise.net.nz wrote: > If you can do this, then it is easy to ask python to sort it for you. > > >>>>data = [("NM_004619.2", 4910.8), ("NM_004619.2", 2716.3), ("NM_145759.1", > > 4805.7), ("NM_14 5759.1", 2716.3), ("XM_378692.1", 56.00)] > >>>>data.sort(key=lambda x: x[1], reverse=True) You don't need a lambda here, you can use itertools.itemgetter(1). itemgetter() was added to Python 2.4 for this purpose. Kent From kent37 at tds.net Thu Aug 11 13:55:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Aug 2005 07:55:20 -0400 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> References: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> Message-ID: <42FB3CA8.9030700@tds.net> Dick Moores wrote: > It appears to me that I've found a bug in PyChecker (see below). Am I > correct? > Warning (from warnings module): > File "C:\Python24\lib\site-packages\pychecker\checker.py", line 609 > m = imp.init_builtin(moduleName) > DeprecationWarning: the regex module is deprecated; please use the re module > > That line 609 is in this function in checker.py: > > def fixupBuiltinModules(needs_init=0): > for moduleName in sys.builtin_module_names : > if needs_init: > _ = Module(moduleName, 0) > module = _allModules.get(moduleName, None) > if module is not None : > try : > m = imp.init_builtin(moduleName) > except ImportError : > pass > else : > extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, []) > module.attributes = [ '__dict__' ] + dir(m) + extra_attrs > > >>> import sys > >>> sys.builtin_module_names > ('__builtin__', '__main__', '_bisect', '_codecs', '_codecs_cn', > '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', > '_codecs_tw', '_csv', '_heapq', '_hotshot', '_locale', '_multibytecodec', > '_random', '_sre', '_subprocess', '_symtable', '_weakref', '_winreg', > 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', > 'collections', 'datetime', 'errno', 'exceptions', 'gc', 'imageop', 'imp', > 'itertools', 'marshal', 'math', 'md5', 'mmap', 'msvcrt', 'nt', > 'operator', 'parser', 'regex', 'rgbimg', 'sha', 'signal', 'strop', > 'struct', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport') > >>> > > What now? It's just a warning so you can go ahead and use PyChecker. It's hard to call this a bug in PyChecker since it isn't explicitly referring to the regex module; for some reason it is importing all the builtin modules and adding a list of names to the module. It would be nice if PyChecker trapped the warning and didn't show it. There is already a bug report filed on sourceforge - http://sourceforge.net/tracker/index.php?func=detail&aid=1236534&group_id=24686&atid=382217 - so I would ignore it and move on. Kent From rdm at rcblue.com Thu Aug 11 14:10:43 2005 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Aug 2005 05:10:43 -0700 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <42FB3CA8.9030700@tds.net> References: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> <42FB3CA8.9030700@tds.net> Message-ID: <6.2.1.2.2.20050811050157.056eecd0@rcblue.com> Kent Johnson wrote at 04:55 8/11/2005: >Dick Moores wrote: > > It appears to me that I've found a bug in PyChecker (see below). Am I > > correct? > > Warning (from warnings module): > > File "C:\Python24\lib\site-packages\pychecker\checker.py", line 609 > > m = imp.init_builtin(moduleName) > > DeprecationWarning: the regex module is deprecated; please use the re > module > > > > That line 609 is in this function in checker.py: > > > > def fixupBuiltinModules(needs_init=0): > > for moduleName in sys.builtin_module_names : > > if needs_init: > > _ = Module(moduleName, 0) > > module = _allModules.get(moduleName, None) > > if module is not None : > > try : > > m = imp.init_builtin(moduleName) > > except ImportError : > > pass > > else : > > extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, []) > > module.attributes = [ '__dict__' ] + dir(m) + > extra_attrs > > > > >>> import sys > > >>> sys.builtin_module_names > > ('__builtin__', '__main__', '_bisect', '_codecs', '_codecs_cn', > > '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', > > '_codecs_tw', '_csv', '_heapq', '_hotshot', '_locale', '_multibytecodec', > > '_random', '_sre', '_subprocess', '_symtable', '_weakref', '_winreg', > > 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', > > 'collections', 'datetime', 'errno', 'exceptions', 'gc', 'imageop', 'imp', > > 'itertools', 'marshal', 'math', 'md5', 'mmap', 'msvcrt', 'nt', > > 'operator', 'parser', 'regex', 'rgbimg', 'sha', 'signal', 'strop', > > 'struct', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport') > > >>> > > > > What now? > >It's just a warning so you can go ahead and use PyChecker. It's hard to >call this a bug in PyChecker since it isn't explicitly referring to the >regex module; for some reason it is importing all the builtin modules >and adding a list of names to the module. > >It would be nice if PyChecker trapped the warning and didn't show it. >There is already a bug report filed on sourceforge - >http://sourceforge.net/tracker/index.php?func=detail&aid=1236534&group_id=24686&atid=382217 >- so I would ignore it and move on. > >Kent Thanks, Kent. But how do I move on? All I get is the above warning. For example, I put "import pychecker.checker" at the top of mycalc.py, my collection of functions. Does getting only that warning mean that mycalc.py has no problems? I've tried inserting some obvious errors, but then Python refuses to execute mycalc, as it should. Dick From jorge at bcs.org.uk Thu Aug 11 14:24:07 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Thu, 11 Aug 2005 13:24:07 +0100 Subject: [Tutor] Python hosting again Message-ID: Hello, I'm interested in writing with my own Python implementation of a Jabber IM server and client. Anyone knows where I could host my Python Jabber IM server for a reasonable monlthy fee? It doesn't need to be a top-notch place since my goal is to test something else, not the scalability of the application. chrs j. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050811/e5d30818/attachment.htm From kent37 at tds.net Thu Aug 11 14:27:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Aug 2005 08:27:18 -0400 Subject: [Tutor] Default class in module In-Reply-To: References: Message-ID: <42FB4426.3060609@tds.net> Jan Eden wrote: > Hi, > > I'd like to pack some modules in a package. Each module contains a single class, which forces me to > > from Pythonsite.Show import Page > page = Page() > ... > > class Page(Site.DB): #class DB from module Site in package Pythonsite > ... > > Is there a way to define a default class for a module which would me allow to > > from Pythonsite import Show > page = Show() #page as an instance of default class in Show > > class Page(Site): #Page as a subclass of default class in Site I don't know of any way to do exactly what you ask. However you can use the __init__.py module of the package to promote classes to package level visibility. For example suppose you have mypackage/ __init__.py - empty myclass.py - defines MyClass myotherclass.py - defines MyOtherClass To use this you would for example from mypackage.myclass import MyClass mc = MyClass() But if you put these lines in __init__.py: from mypackage.myclass import MyClass from mypackage.myotherclassimport MyOtherClass this brings the class names into the module namespace. Now you can say from mypackage import MyClass mc = MyClass() I suppose you could do your example by including this line in __init__.py: from Pythonsite import Show Show = Show.Page Then clients that say from Pythonsite import Show will actually get Show.Page which is what Pythonsite.Show is now bound to, but that seems unneccesarily twisted and obscure to me. HTH Kent From kent37 at tds.net Thu Aug 11 14:31:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Aug 2005 08:31:36 -0400 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <6.2.1.2.2.20050811050157.056eecd0@rcblue.com> References: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> <42FB3CA8.9030700@tds.net> <6.2.1.2.2.20050811050157.056eecd0@rcblue.com> Message-ID: <42FB4528.6090903@tds.net> Dick Moores wrote: > But how do I move on? All I get is the above warning. > > For example, I put "import pychecker.checker" at the top of mycalc.py, my > collection of functions. Does getting only that warning mean that > mycalc.py has no problems? I've tried inserting some obvious errors, but > then Python refuses to execute mycalc, as it should. According to the docs importing pychecker only checks modules that are imported *after* the module containing the import. If you have a single-file program try using pychecker from the command line. When you insert errors as a test, of course you have to use errors that are more subtle than syntax errors - things that would cause runtime errors. For example: def f(): x = y Kent From jnoller at gmail.com Thu Aug 11 14:47:59 2005 From: jnoller at gmail.com (Jesse Noller) Date: Thu, 11 Aug 2005 08:47:59 -0400 Subject: [Tutor] SSH commands in Python on Linux In-Reply-To: <61d0e2b4050810081127a958ad@mail.gmail.com> References: <61d0e2b4050810081127a958ad@mail.gmail.com> Message-ID: <4222a8490508110547885df33@mail.gmail.com> On 8/10/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > I'm trying to make a script to send a SSH command from a Linux > computer to another Linux compter. > > The Python syntax I'm using... > > > import os > os.system( 'ssh root at 192.168.10.204 "ls"' ) > > > Now the problem is that I'm always asked for the password. So my > question is two-fold: > > 1- Is there a way to not be asked for the root password? > 2- If not, then is it possible to feed the SSH password input with my > Python script? I have about stdin redirection, but I have to admit > that I'm a bit lost and I don't know if it applies to SSH input as > well. > > Right now I'm using the ls command to list processes, however > ultimately I want to be able to kill some processes within a loop > (this is for render farm management). > > > > Thanks > Bernard Some of the things you are going to be bit by you've already ran into - the first of which is authentication. I would recommend looking at the following utilities: http://www.theether.org/pssh/ http://sourceforge.net/projects/pyssh Setting up private/public key authentication is going to allow for a greate amount of secure automation. Barring that, use the pexpect module to do the prompt handling, pexpect is bad simply due to the fact you'll need to store your passwords plaintext within your program which is a seriously risk. Also note you'll need to take into account basic flow control for Stdin, Stdout and Stderr - you need to watch for hosts that are not found/don't exist and ssh commands that may or may not hang. The PSSH program has excellent work arounds for all of these within it. -jesse From 3dbernard at gmail.com Thu Aug 11 15:18:31 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 11 Aug 2005 09:18:31 -0400 Subject: [Tutor] SSH commands in Python on Linux In-Reply-To: <4222a8490508110547885df33@mail.gmail.com> References: <61d0e2b4050810081127a958ad@mail.gmail.com> <4222a8490508110547885df33@mail.gmail.com> Message-ID: <61d0e2b40508110618665b8fc0@mail.gmail.com> Ok thanks everyone for the recommandations, I'll check them out. Bernard On 8/11/05, Jesse Noller wrote: > On 8/10/05, Bernard Lebel <3dbernard at gmail.com> wrote: > > Hello, > > > > I'm trying to make a script to send a SSH command from a Linux > > computer to another Linux compter. > > > > The Python syntax I'm using... > > > > > > import os > > os.system( 'ssh root at 192.168.10.204 "ls"' ) > > > > > > Now the problem is that I'm always asked for the password. So my > > question is two-fold: > > > > 1- Is there a way to not be asked for the root password? > > 2- If not, then is it possible to feed the SSH password input with my > > Python script? I have about stdin redirection, but I have to admit > > that I'm a bit lost and I don't know if it applies to SSH input as > > well. > > > > Right now I'm using the ls command to list processes, however > > ultimately I want to be able to kill some processes within a loop > > (this is for render farm management). > > > > > > > > Thanks > > Bernard > > Some of the things you are going to be bit by you've already ran into > - the first of which is authentication. > > I would recommend looking at the following utilities: > > http://www.theether.org/pssh/ > http://sourceforge.net/projects/pyssh > > Setting up private/public key authentication is going to allow for a > greate amount of secure automation. Barring that, use the pexpect > module to do the prompt handling, pexpect is bad simply due to the > fact you'll need to store your passwords plaintext within your program > which is a seriously risk. > > Also note you'll need to take into account basic flow control for > Stdin, Stdout and Stderr - you need to watch for hosts that are not > found/don't exist and ssh commands that may or may not hang. > > The PSSH program has excellent work arounds for all of these within it. > > -jesse > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From 3dbernard at gmail.com Thu Aug 11 15:31:41 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 11 Aug 2005 09:31:41 -0400 Subject: [Tutor] OT: PHP-MySQL, and Python if possible Message-ID: <61d0e2b405081106311ebc08ef@mail.gmail.com> Hello, Sorry for off-topic. I'm looking to buy a book about PHP, to build interface for MySQL tables. Since my current script library is in Python, something is also relevant to Python would definitely be nice. Looking for suggestions. Thanks in advance. Bernard From rdm at rcblue.com Thu Aug 11 16:17:03 2005 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Aug 2005 07:17:03 -0700 Subject: [Tutor] PyChecker: Installing and or Using In-Reply-To: <42FB4528.6090903@tds.net> References: <6.2.1.2.2.20050810233059.06ddc3f0@rcblue.com> <42FB3CA8.9030700@tds.net> <6.2.1.2.2.20050811050157.056eecd0@rcblue.com> <42FB4528.6090903@tds.net> Message-ID: <6.2.1.2.2.20050811070215.06001de0@rcblue.com> Kent Johnson wrote at 05:31 8/11/2005: >According to the docs importing pychecker only checks modules that are >imported *after* the module containing the import. If you have a >single-file program try using pychecker from the command line. > >When you insert errors as a test, of course you have to use errors that >are more subtle than syntax errors - things that would cause runtime >errors. For example: > >def f(): > x = y > >Kent OK, thanks, Kent. Thanks for sticking with me. Finally got it working. I ran pychecker on mycalc.py and got what looks like a lot of useful feedback (I put your function is at the top; line 3 is your "x = y"): ==================================== C:\Python24>lib\site-packages\pychecker\checker.py mycalc.py Processing mycalc... Warnings... mycalc.py:3: Local variable (x) not used mycalc.py:3: No global (y) found mycalc.py:9: (max) shadows builtin mycalc.py:9: (min) shadows builtin mycalc.py:16: (min) shadows builtin mycalc.py:18: (min) shadows builtin mycalc.py:24: (max) shadows builtin mycalc.py:42: No global (regularizeFirstGroup) found mycalc.py:46: No global (computeIllionNum) found mycalc.py:47: No global (illionNumToName) found mycalc.py:49: No global (stripZeros) found mycalc.py:55: Function returns a value and also implicitly returns None mycalc.py:148: (max) shadows builtin mycalc.py:171: Module (mycalc) imports itself mycalc.py:260: Module (mycalc) imports itself C:\Python24> ================================== Dick From alan.gauld at freenet.co.uk Thu Aug 11 19:10:07 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 11 Aug 2005 18:10:07 +0100 Subject: [Tutor] Untainting CGI parameters References: Message-ID: <042c01c59e97$86dce140$bea68651@xp> >>> type = re.search('\d+',a).group() or 'page' Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'group' > If the search does not succeed, the returned object has the value > None, which has no attribute group. Ah yes! I forgot about the call to group(). I was just thinking if we got a None match. Ironic since it was me tagged the group call on in the first place! try/except it needs to be then... Alan G. From jeffpeery at yahoo.com Thu Aug 11 20:13:04 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 11 Aug 2005 11:13:04 -0700 (PDT) Subject: [Tutor] changes made if IDLE not updating when application executed? Message-ID: <20050811181304.14549.qmail@web30503.mail.mud.yahoo.com> Hello, I am running a script I wrote with IDLE. if I edit the script them hit 'F5' to run it again, it seems to run the old script prior to the last save. I have to close down the IDLE then start it again and hit 'F5' to get the changes to execute. is there a way to fix this? Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050811/6176155a/attachment.htm From geon at post.cz Thu Aug 11 20:42:49 2005 From: geon at post.cz (geon) Date: Thu, 11 Aug 2005 20:42:49 +0200 Subject: [Tutor] help In-Reply-To: <9560d3c05080816487b0b46c2@mail.gmail.com> References: <9560d3c05080816487b0b46c2@mail.gmail.com> Message-ID: <42FB9C29.3050509@post.cz> Dan Deternova napsal(a): > i am making a simple script to get the hang of Tkinter. i want to use > the input of the user from a Entry and calcuate the area. i have > tryied many way... as you can see in my script. the Entry is under > def area(): and the output i want is under def cal(): ... please > help me fix my code and explain to me what you did.. thanks in advance. > > here is corrected script, I just correct the area funciton and all what belongs to it. Instead of DoubleVar, you could also use IntVar, if you prefer.... #program made and maintained by Dan Deternova #start of program from Tkinter import * # tells computer we are using Tkinter modual from tkMessageBox import * def cal(): win4 = Toplevel print 'area = ', w.get()*h.get() def notyet(): showerror('not yet avalable') win = Tk() # makes windows and has value for Tk def makemenu(Tk): top = Menu(win) win.config(menu=top) file = Menu(top) file.add_command(label='save your name', command=newwin, underline=0) file.add_command(label='quit', command=win.destroy, underline=0) file.add_command(label='quit all', command=win.quit, underline=0) top.add_cascade(label='file', menu=file, underline=0) edit = Menu(top, tearoff=0) edit.add_command(label='copy', command=notyet, underline=0) edit.add_command(label='paste', command=notyet, underline=0) edit.add_command(label='quit', command=win.destroy, underline=0) top.add_cascade(label='edit', menu=edit, underline=0) def newwin(): # callback to define button newwin. win2 = Toplevel() # makes new window when button is pressed. named win2 widget = Label(win2, text='your name here').pack() # line 'type your name here' is printed on top of entry name = StringVar() widget = Entry(win2, textvariable=name).pack() # makes entry in new window at the top. widget = Label(win2, text='age here').pack() # prints the line 'age here' age = StringVar() widget = Entry(win2, textvariable=age).pack() # makes entry widget = Label(win2, text='type your address here').pack() address = StringVar() widget = Entry(win2, textvariable=address).pack() def save(): f=file('fname','a') f.write(name.get()+'\n') f.write(age.get()+'\n') f.write(address.get()+'\n') widget = Button(win2, text='save', command=save).pack(side=LEFT) widget = Button(win2, text='quit', command=win2.destroy).pack(side=RIGHT) def area(): global w,h win3 = Toplevel() widget = Label(win3, text='type hieght here: ').pack() h = DoubleVar() widget = Entry(win3, textvariable=h).pack() widget = Label(win3, text='type width here: ').pack() w = DoubleVar() widget = Entry(win3, textvariable=w).pack() widget = Button(win3, text=' calculate ', command=cal).pack(side=BOTTOM, expand=YES, fill=BOTH) fontentry = ('times', 20, 'bold') # (font, size, style) defonision for fontentry. will be used later on in the program widget = Entry(win, text='type here') # makes entry point in 'win' makemenu(win) widget.config(font=fontentry) # makes the font of entry equal to 'fontentry' widget.config(bg='blue', fg='yellow') # makes the background (bg) black and the forground (text) yellow widget.pack(side=TOP, expand=YES, fill=BOTH) # 'packs' the entry on top of win and expands and fill the Y axes widget = Button(win, text="your name", command=newwin).pack(side=LEFT, expand=YES, fill=BOTH)# creates button that says 'your name'. see newwin callback for output. widget = Button(win, text='quit all', command=win.quit).pack(side=BOTTOM, expand=YES, fill=BOTH) widget = Button(win, text='quit', command=win.destroy).pack(side=RIGHT, expand=YES, fill=BOTH) widget = Button(win, text='area', command=area).pack(side=LEFT, expand=YES, fill=BOTH) win.title('my program') #end of program -- geon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050811/10f38745/attachment.htm From tvbare at socket.net Thu Aug 11 22:10:19 2005 From: tvbare at socket.net (->Terry<-) Date: Thu, 11 Aug 2005 15:10:19 -0500 (CDT) Subject: [Tutor] Problem with Learning Python example Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I'm working my way through Learning Python 2nd Ed. and I've ran across something I don't understand in Chapter 27, page 482, in Timing section. I checked the errata on O'Reilly's web-site and it only mentions a missing comma in the print statement in timings.py, which I caught when I first ran the program. I've proof-read these 2 files several times and even had the wife proof-read it and I'm fairly confident I'm not missing any errors. Can someone guide me in the right direction? My system is Slackware 10.1 and Python version is 2.4.1 - -------------------------------- * makezeros.py - -------------------------------- def lots_of_appends(): zeros = [] for i in range(10000): zeros.append(0) def one_multiply(): zeros = [0] * 10000 - -------------------------------- * timings.py - -------------------------------- import time, makezeros def do_timing(num_times, *funcs): totals = {} for func in funcs: totals[func] = 0.0 starttime = time.clock() # record starting time for x in range(num_times): for func in funcs: apply(func) stoptime = time.clock() # record ending time elapsed = stoptime - starttime # difference yields time elapsed totals[func] = totals[func] + elapsed for func in funcs: print "Running %s %d times took %.3f seconds" % (func.__name__, num_times, totals[func]) do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) - ------------------------------- * error message - ------------------------------- Traceback (most recent call last): File "timings.py", line 16, in ? do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) File "timings.py", line 9, in do_timing apply(func) TypeError: 'tuple' object is not callable Thanks, - -- Terry ,-~~-.___. Terry Randall / | ' \ < ) 0 Linux Counter Project User# 98233 \_/, ,-----' ==== // / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware... =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown (Best viewed with a mono-spaced font.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFC+7CwQvSnsfFzkV0RAqVoAJwIodb3VcBEYlneak47zjrIJdsLagCgg0xL lss+Go8izUgD9ekCE7B5nKE= =fzYk -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Thu Aug 11 22:25:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 Aug 2005 13:25:12 -0700 (PDT) Subject: [Tutor] Problem with Learning Python example In-Reply-To: Message-ID: Hi Terry, Ok, let's take a look at the problem. First, let's look at the error message again: > Traceback (most recent call last): > File "timings.py", line 16, in ? > do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) > File "timings.py", line 9, in do_timing > apply(func) > TypeError: 'tuple' object is not callable This kind of error will happen if 'func' is weird. For example: ####### >>> def sayHi(): ... print "hi" ... >>> apply(sayHi) hi >>> apply(42) Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable ####### The first call to apply() works because we give apply a function. The second call to apply() doesn't work, because 42 isn't something that can be practically applied as a callable function. Going back to the bug, let's assume for the moment that in: apply(func) that 'func' really is a tuple, and see how things get that way... ah, I see it now. > def do_timing(num_times, *funcs): [body cut] Ok, this defines a function called do_timing. The second argument will collect any other arguments passed to do_timing and make a tuple out of them. So good so far. This means that if we call dotimings like this: do_timings(5, f1, f2, f3, f4) that num_times=5 and funcs=(f1, f2, f3, f4). Likewise if we do: do_timings(7, f1) then num_times=7 aand funcs=(f1,). That is, funcs is a tuple with just one element in it. Ok, let's see how the program calls dotiming. > do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ah! Ok, that's what's going on. You mean to do this instead: do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) What has happened is similar to what happens if we do this: do_timings(19, (f1, f2)) which, from our previous examples, allows us to see that this sets num_times=19, funcs=((f1, f2),). That is, funcs was a tuple of tuples, and that's what provokes the problem. If you have any questions abou this, please feel free to ask. From bgailer at alum.rpi.edu Thu Aug 11 22:45:39 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 11 Aug 2005 14:45:39 -0600 Subject: [Tutor] Problem with Learning Python example In-Reply-To: References: Message-ID: <6.1.2.0.0.20050811143930.02f08ec0@mail.mric.net> At 02:10 PM 8/11/2005, ->Terry<- wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hello, > >I'm working my way through Learning Python 2nd Ed. and >I've ran across something I don't understand in Chapter >27, page 482, in Timing section. I checked the errata on >O'Reilly's web-site and it only mentions a missing comma >in the print statement in timings.py, which I caught when >I first ran the program. I've proof-read these 2 files >several times and even had the wife proof-read it and I'm >fairly confident I'm not missing any errors. Can someone >guide me in the right direction? > >My system is Slackware 10.1 and Python version is 2.4.1 > >- -------------------------------- >* makezeros.py >- -------------------------------- > >def lots_of_appends(): > zeros = [] > for i in range(10000): > zeros.append(0) > >def one_multiply(): > zeros = [0] * 10000 > > >- -------------------------------- >* timings.py >- -------------------------------- > >import time, makezeros >def do_timing(num_times, *funcs): *funcs means treat the rest of the arguments passed to the function as a tuple. So given a call like: do_timing(100, func1, func2), funcs = (func1, func2), and for func in funcs yields func1, then func2 whereas a call like you are using: do_timing(100, (func1, func2)), funcs = ((func1, func2)), and for func in funcs yields (func1, func2) so change do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) to do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) > totals = {} > for func in funcs: > totals[func] = 0.0 > starttime = time.clock() # record starting time > for x in range(num_times): > for func in funcs: > apply(func) > stoptime = time.clock() # record ending time > elapsed = stoptime - starttime # difference yields time elapsed > totals[func] = totals[func] + elapsed > for func in funcs: > print "Running %s %d times took %.3f seconds" % (func.__name__, > num_times, totals[func]) > >do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) > > >- ------------------------------- >* error message >- ------------------------------- > >Traceback (most recent call last): > File "timings.py", line 16, in ? > do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) > File "timings.py", line 9, in do_timing > apply(func) >TypeError: 'tuple' object is not callable > > >Thanks, >- -- > Terry > > ,-~~-.___. Terry Randall > / | ' \ > < ) 0 Linux Counter Project User# 98233 > \_/, ,-----' > ==== // > / \-'~; /~~~(0) > / __/~| / | If only Snoopy had Slackware... > =( ______| (________| > >"He is your friend, your partner, your defender, your dog. >You are his life, his love, his leader. He will be yours, >faithful and true, to the last beat of his heart. You owe >it to him to be worthy of such devotion." -- Unknown > > (Best viewed with a mono-spaced font.) > >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.2.7 (GNU/Linux) > >iD8DBQFC+7CwQvSnsfFzkV0RAqVoAJwIodb3VcBEYlneak47zjrIJdsLagCgg0xL >lss+Go8izUgD9ekCE7B5nKE= >=fzYk >-----END PGP SIGNATURE----- > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer at alum.rpi.edu 303 442 2625 home 720 938 2625 cell From alan.gauld at freenet.co.uk Thu Aug 11 22:45:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 11 Aug 2005 21:45:43 +0100 Subject: [Tutor] changes made if IDLE not updating when application executed? References: <20050811181304.14549.qmail@web30503.mail.mud.yahoo.com> Message-ID: <049601c59eb7$e32dcac0$bea68651@xp> Jeff, > Hello, I am running a script I wrote with IDLE. > if I edit the script them hit 'F5' to run it again, > it seems to run the old script prior to the last save. Can you just confirm the sequence here please? 1) You are editing a script in IDLE loaded from a file. 2) You hit Save 3) You hit F5 4) The output in the shell window reflects the version prior to your save? The most obvious things to check are that you are remembering step 2. And that you are not importing the module you are editing at the >>> prompt. If the latter what happens if you type reload(myModule) at the >>> prompt before hitting F5? (I'm not sure whether this would have the result you see but its all I can think of!) Finally, what version of Python/IDLE and which OS? Alan G. From alan.gauld at freenet.co.uk Thu Aug 11 22:45:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 11 Aug 2005 21:45:43 +0100 Subject: [Tutor] changes made if IDLE not updating when application executed? References: <20050811181304.14549.qmail@web30503.mail.mud.yahoo.com> Message-ID: <048901c59eb5$a531f130$bea68651@xp> Jeff, > Hello, I am running a script I wrote with IDLE. > if I edit the script them hit 'F5' to run it again, > it seems to run the old script prior to the last save. Can you just confirm the sequence here please? 1) You are editing a script in IDLE loaded from a file. 2) You hit Save 3) You hit F5 4) The output in the shell window reflects the version prior to your save? The most obvious things to check are that you are remembering step 2. And that you are not importing the module you are editing at the >>> prompt. If the latter what happens if you type reload(myModule) at the >>> prompt before hitting F5? (I'm not sure whether this would have the result you see but its all I can think of!) Finally, what version of Python/IDLE and which OS? Alan G. From tvbare at socket.net Fri Aug 12 03:25:37 2005 From: tvbare at socket.net (->Terry<-) Date: Thu, 11 Aug 2005 20:25:37 -0500 (CDT) Subject: [Tutor] More problems with Learning Python example Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Thanks Danny and Bob. Your explanations not only helped me solve the error, but understand why i got the error. Unfortunately, I have run into another problem with the same example. Here is where I'm at now: My system is Slackware 10.1 and Python version is 2.4.1 - -------------------------------- * makezeros.py - -------------------------------- def lots_of_appends(): zeros = [] for i in range(10000): zeros.append(0) def one_multiply(): zeros = [0] * 10000 - -------------------------------- * corrected timings.py - -------------------------------- import time, makezeros def do_timing(num_times, *funcs): totals = {} for func in funcs: totals[func] = 0.0 starttime = time.clock() # record starting time for x in range(num_times): for func in funcs: apply(func) stoptime = time.clock() # record ending time elapsed = stoptime - starttime # difference yields time elapsed totals[func] = totals[func] + elapsed for func in funcs: print "Running %s %d times took %.3f seconds" % (func.__name__, num_times, totals[func]) do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) - ------------------------------- * new error message - ------------------------------- Traceback (most recent call last): File "timings.py", line 16, in ? do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) File "timings.py", line 12, in do_timing totals[func] = totals[func] + elapsed KeyError: help(KeyError) tells me Mapping key not found. Have I stumbled on another error in the book? I don't know how to proceed in tracking this down. any suggestions? Thanks again, - -- Terry ,-~~-.___. Terry Randall / | ' \ < ) 0 Linux Counter Project User# 98233 \_/, ,-----' ==== // / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware... =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown (Best viewed with a mono-spaced font.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFC+/qWQvSnsfFzkV0RAmPzAJ9bsffZryIZebPZzhTQg7GfR+vPbwCeN6qc spEguzDew7DkhvxleyoZ+Zs= =QTh6 -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Fri Aug 12 04:00:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 Aug 2005 19:00:59 -0700 (PDT) Subject: [Tutor] More problems with Learning Python example In-Reply-To: Message-ID: > Traceback (most recent call last): > File "timings.py", line 16, in ? > do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply) > File "timings.py", line 12, in do_timing > totals[func] = totals[func] + elapsed > KeyError: > help(KeyError) tells me Mapping key not found. Have I stumbled on > another error in the book? I don't know how to proceed in tracking this > down. any suggestions? Hi Terry, This looks a little unusual, for code in the book to be so bad. *grin* The logic error is that 'func' is being reused in a way that isn't clear. There's several nested loops that look a bit unusual. Let me cut out the particularly funky section: > for func in funcs: > totals[func] = 0.0 > starttime = time.clock() # record starting time > for x in range(num_times): > for func in funcs: > apply(func) Note that the innermost loop here reuses the same 'func' variable, which breaks the assumption of the rest of the code: The code logic suggests that the innermost loop really shouldn't be there. From a high-level point of view, the program is doing this: ####### def do_timing(...): for each function to be timed: record start time do some time trials record end time ... ####### And, at least from the high level view, 'do some time trials" should not touch 'funcs' at all: it should only concentrate on the particular function that's being exercised. The fact that the innermost loop in: > for func in funcs: > totals[func] = 0.0 > starttime = time.clock() # record starting time > for x in range(num_times): > for func in funcs: > apply(func) is touching data that is irrelevant to what it should be doing is the clue: it strongly suggests that a logic bug is there. Developing this further, it might be a good thing to explicitely write a helper to run a function n times. If we imagine that we have something like this: ###### def time_trial(func, num_times): """Applies a function func num_times.""" ... # fill me in ###### then the logic of the block in do_timing() reduces to: #### for func in funcs: totals[func] = 0.0 time_trial(func, num_times) #### I'm still a little shocked that Learning Python would have such code, though. Can anyone double check this? We should be sending errata reports if there are serious bugs like this in the book.. If you have any questions on this, please ask questions. Good luck! From vinayvinay at gmail.com Fri Aug 12 09:11:25 2005 From: vinayvinay at gmail.com (Vinay Reddy) Date: Fri, 12 Aug 2005 07:11:25 +0000 Subject: [Tutor] pattern matching is too slow Message-ID: <537f59d1050812001160666f27@mail.gmail.com> Hi, I am writing a front-end for an application (mplayer). I used the popen2 call to open pipes for bi-directional communication. I set the output pipe from the application to non-blocking mode using: fcntl.fcntl(self.mplayerOut, fcntl.F_SETFL, os.O_NONBLOCK) The problem is that it takes about 10 seconds just to parse through the inital dump of mplayer (during which mplayer stops playing). I'm using the following code to read from 'mplayerOut': while True: try: temp = self.mplayerOut.readline() print temp if re.compile("^A:").search(temp): print "abc" except StandardError: break If the remove the re.compile() statement, then the output is instantaneous and there is no delay. Why is pattern matching so slow? It's increasing the time almost by 1 second per line of output. How can I get it to run faster? Any help will be appreciated. Regards, Vinay Reddy PS: This is my first python program. From dyoo at hkn.eecs.berkeley.edu Fri Aug 12 09:58:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 12 Aug 2005 00:58:57 -0700 (PDT) Subject: [Tutor] More problems with Learning Python example (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 12 Aug 2005 00:29:00 -0500 (CDT) From: "->Terry<-" To: Danny Yoo Subject: Re: [Tutor] More problems with Learning Python example -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Today (Aug 11, 2005) at 7:00pm, Danny Yoo spoke these wise words: - ->Developing this further, it might be a good thing to explicitely write a - ->helper to run a function n times. If we imagine that we have something - ->like this: - -> - ->###### - ->def time_trial(func, num_times): - -> """Applies a function func num_times.""" - -> ... # fill me in - ->###### - -> - -> - ->then the logic of the block in do_timing() reduces to: - -> - ->#### - ->for func in funcs: - -> totals[func] = 0.0 - -> time_trial(func, num_times) - ->#### - -> - -> - ->I'm still a little shocked that Learning Python would have such code, - ->though. Can anyone double check this? We should be sending errata - ->reports if there are serious bugs like this in the book.. - -> - -> - ->If you have any questions on this, please ask questions. Good luck! Ok, I struck out on my own here and using your advice, I came up with the following: - -------------------------------- * makezeros.py - -------------------------------- def lots_of_appends(): zeros = [] for i in range(10000): zeros.append(0) def one_multiply(): zeros = [0] * 10000 - -------------------------------- * my_timings.py - -------------------------------- #!/usr/bin/python import time, makezeros def time_trial(func, num_times): total = 0.0 starttime = time.clock() for num in range(num_times): apply(func) stoptime = time.clock() elapsed = stoptime - starttime total = total + elapsed return total tries = 100 funcs = [makezeros.lots_of_appends, makezeros.one_multiply] for func in funcs: took = time_trial(func, tries) print "Running %s %d times took %.3f seconds." % (func.__name__, tries, took) Entering: python my_timings.py >> results.txt in a shell 10 times I get the following: Running lots_of_appends 100 times took 0.400 seconds. Running one_multiply 100 times took 0.020 seconds. Running lots_of_appends 100 times took 0.460 seconds. Running one_multiply 100 times took 0.000 seconds. <<----- ? Running lots_of_appends 100 times took 0.440 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.390 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.450 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.450 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.440 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.440 seconds. Running one_multiply 100 times took 0.010 seconds. Running lots_of_appends 100 times took 0.460 seconds. Running one_multiply 100 times took 0.020 seconds. Running lots_of_appends 100 times took 0.410 seconds. Running one_multiply 100 times took 0.010 seconds. Is the indicated result a fluke value which I can just disregard or is there a problem with my code? The 0.000 value shows up about once in every 25-30 runs. Any other comments? This whole thing really had me going in circles. Surely others have run into this problem. Again, many thanks to Bob and especially to Danny for being so helpful and spending time helping me. Sincerely, - -- Terry ,-~~-.___. Terry Randall / | ' \ < ) 0 Linux Counter Project User# 98233 \_/, ,-----' ==== // / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware... =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown (Best viewed with a mono-spaced font.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFC/DOhQvSnsfFzkV0RAoMGAJ0dPAZsnQHraHcTUi/Plm6GFl5z5wCeJude mS9NbsMjKxViRI0j6NfqsSU= =P4MJ -----END PGP SIGNATURE----- From lists at janeden.org Fri Aug 12 10:02:39 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 12 Aug 2005 10:02:39 +0200 Subject: [Tutor] Default class in module In-Reply-To: <42FB4426.3060609@tds.net> Message-ID: Hi Kent, Kent Johnson wrote on 11.08.2005: >I don't know of any way to do exactly what you ask. However you can >use the __init__.py module of the package to promote classes to >package level visibility. > Nice - that's a good start. Thank you, Jan -- Common sense is what tells you that the world is flat. From enas_khalil at yahoo.com Fri Aug 12 10:46:15 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Fri, 12 Aug 2005 01:46:15 -0700 (PDT) Subject: [Tutor] i want to build my own arabic training corpus data and use the NLTK to deal with In-Reply-To: Message-ID: <20050812084615.43128.qmail@web50309.mail.yahoo.com> hi Danny, Thanks for this help It is now ok to tokenize my text but the next step i want is to use tagger class to tag my text with own tags how can i start this Also for any NLTK further help is there a specific mailing list i could go on many thanks Danny Yoo wrote: On Wed, 3 Aug 2005, enas khalil wrote: > i want to build my own arabic training corpus data and use the NLTK to > parse and make test for unkown data Hi Enas, By NLTK, I'll assume that you mean the Natural Language Toolkit at: http://nltk.sourceforge.net/ Have you gone through the introduction and tutorials from the NLTK web page? http://nltk.sourceforge.net/getting_started.html http://nltk.sourceforge.net/tutorial/index.html > how can i build this file and make it available to treat with it using > different NLTK classes Your question is a bit specialized, so we may not be the best people to ask about this. The part that you may want to think about is how to break a corpus into a sequence of tokens, since tokens are primarily what the NLTK classes work with. This may or may not be immediately easy, depending on how much you can take advantage of existing NLTK classes. As the documentation in NLTK mentions: """If we turn to languages other than English, segmenting words can be even more of a challenge. For example, in Chinese orthography, characters correspond to monosyllabic morphemes. Many morphemes are words in their own right, but many words contain more than one morpheme; most of them consist of two morphemes. However, there is no visual representation of word boundaries in Chinese text.""" I don't know how Arabic works, so I'm not sure if the caveat above is something that we need to worry about. There are a few built-in NLTK tokenizers that break a corpus into tokens, including a WhitespaceTokenizer and a RegexpTokenizer class, both introduced here: http://nltk.sourceforge.net/tutorial/tokenization/nochunks.html For example: ###### >>> import nltk.token >>> mytext = nltk.token.Token(TEXT="hello world this is a test") >>> mytext ###### At the moment, this is a single token. We can use a naive approach in breaking this into words by using whitespace as our delimiter: ###### >>> import nltk.tokenizer >>> nltk.tokenizer.WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(mytext) >>> mytext <[, , , , , ]> ###### And now our text is broken into a sequence of discrete tokens, where we can now play with the 'subtokens' of our text: ###### >>> mytext['WORDS'] [, , , , , ] >>> len(mytext['WORDS']) 6 ###### If Arabic follows conventions that fit closely with the assumptions of those tokenizers, you should be in good shape. Otherwise, you'll probably have to do some work to build your own customized tokenizers. --------------------------------- Start your day with Yahoo! - make it your home page -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050812/0945a21b/attachment.htm From alan.gauld at freenet.co.uk Fri Aug 12 10:48:50 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 12 Aug 2005 09:48:50 +0100 Subject: [Tutor] More problems with Learning Python example References: Message-ID: <05e401c59f1a$a9bdc700$bea68651@xp> Something odd here... > def do_timing(num_times, *funcs): > totals = {} > for func in funcs: Here you assign func to each function in turn. > totals[func] = 0.0 And here you create a key with it > starttime = time.clock() # record starting time > for x in range(num_times): > for func in funcs: And the same here, but the result will be that when you exit this loop func will always be the last function. > totals[func] = totals[func] + elapsed But you won't have created a key for the last function so this falls over. > Traceback (most recent call last): > File "timings.py", line 16, in ? > do_timing(100, makezeros.lots_of_appends, > makezeros.one_multiply) > File "timings.py", line 12, in do_timing > totals[func] = totals[func] + elapsed > KeyError: I'm not quite sure what the second funcs loop is doing, but thats the reason for the key error. HTH, Alan G. From alan.gauld at freenet.co.uk Fri Aug 12 10:58:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 12 Aug 2005 09:58:59 +0100 Subject: [Tutor] More problems with Learning Python example (fwd) References: Message-ID: <05ee01c59f1c$143c6450$bea68651@xp> > Running lots_of_appends 100 times took 0.460 seconds. > Running one_multiply 100 times took 0.000 seconds. <<----- ? > Running lots_of_appends 100 times took 0.440 seconds. > Running one_multiply 100 times took 0.010 seconds. > > Is the indicated result a fluke value which I can just > disregard or is there a problem with my code? The 0.000 > value shows up about once in every 25-30 runs. As you can see the multiply function is much faster and the 0.000 figure just means the timing was so small it didn't register - maybe your PC just happened not to be doing anything else at the time so the code was still in RAM or somesuch.... This is a good example of why timing tests must be done over many repetitions and averaged. Since you are running near the limit of recordability you might increase the number of loop iterations to 1000... Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Aug 12 11:16:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 12 Aug 2005 02:16:08 -0700 (PDT) Subject: [Tutor] pattern matching is too slow In-Reply-To: <537f59d1050812001160666f27@mail.gmail.com> Message-ID: On Fri, 12 Aug 2005, Vinay Reddy wrote: > I'm using the following code to read from 'mplayerOut': > > while True: > try: > temp = self.mplayerOut.readline() > print temp > if re.compile("^A:").search(temp): > print "abc" > except StandardError: > break > > If the remove the re.compile() statement, then the output is > instantaneous and there is no delay. Why is pattern matching so slow? Hi Vinay, Compiling a regular expression object can be expensive. Doing the compilation it over and over is probably what's killing the performance here. I'd recommend yanking the regular expression compilation out of the inner loop, and just reuse the regex object after you compile it once. ###### pattern = re.compile("^A:") while True: try: temp = self.mplayerOut.readline() print temp if pattern.search(temp): print "abc" except StandardError: break ###### By the way, there are other things in this program that should be fixed. The way it reads lines from the file is non-idiomatic. For an example of what people will usually do to go through a file's lines, see a tutorial like Alan Gauld's "Learning to Program": http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm For more details about regular expressions, you may find the Regular Expression HOWTO guide useful: http://www.amk.ca/python/howto/regex/ If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Aug 12 11:32:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 12 Aug 2005 02:32:12 -0700 (PDT) Subject: [Tutor] i want to build my own arabic training corpus data and use the NLTK to deal with In-Reply-To: <20050812084615.43128.qmail@web50309.mail.yahoo.com> Message-ID: On Fri, 12 Aug 2005, enas khalil wrote: > hi Danny, Thanks for this help It is now ok to tokenize my text but the > next step i want is to use tagger class to tag my text with own tags. > how can i start this? Hi Enas, I'd strongly recommend you really go through the NTLK tutorials: the developers of NLTK have spent a lot of effort into making an excellent set of tutorials. It would be a shame to waste their work. http://nltk.sourceforge.net/tutorial/index.html The tutorial on Tagging seems to answer your question affirmatively. > Also for any NLTK further help is there a specific mailing list i could > go on I think you're looking for the nltk forums: http://sourceforge.net/forum/?group_id=30982 As a warning: again, read through the tutorials first before jumping in there. I suspect that many of the people who work with NTLK are researchers; they may want to see that you've done your "homework" before they answer your questions. In general, the guidelines in: http://www.catb.org/~esr/faqs/smart-questions.html will probably apply here. Good luck to you. From alan.gauld at freenet.co.uk Fri Aug 12 10:54:51 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 12 Aug 2005 09:54:51 +0100 Subject: [Tutor] pattern matching is too slow References: <537f59d1050812001160666f27@mail.gmail.com> Message-ID: <05ec01c59f1b$81f86440$bea68651@xp> while True: try: temp = self.mplayerOut.readline() print temp if re.compile("^A:").search(temp): The point of re.compile is to compile the re once *outside* the loop. Compiling the re is slow so you should only do it outside. As a first step replace re.compile with re.search if re.search("^A:",temp): print "abc" except StandardError: break As a second step move the compile before the loop reg = re.compile("^A:") Then inside the loop use the compiled expression if reg.search(temp): The first step should be faster, the second step faster still. Finally, lookaing at tyour regex you might be better using a simple string method - startswith() if temp.startswith("A"): That should be even faster still. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From duncan at thermal.esa.int Fri Aug 12 15:14:35 2005 From: duncan at thermal.esa.int (Duncan Gibson) Date: Fri, 12 Aug 2005 15:14:35 +0200 Subject: [Tutor] pychecker: x is None or x == None Message-ID: <20050812131435.4B0222332@zeeman.thermal.esa.int> We've been programming in Python for about a year. Initially we had a lot of tests of the form if x == None: do_something() but then someone thought that we should really change these to if x is None: do_something() However. if you run pychecker on these two snippets of code, it complains about the second, and not the first: x.py:6: Using is None, may not always work So the question is, which one should we really be using? If it is the second, how do I get pychecker to shut up? I've hunted around in the documentation, and if there is a clear discussion about this issue, I must have missed it. Cheers Duncan From kent37 at tds.net Fri Aug 12 15:51:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Aug 2005 09:51:14 -0400 Subject: [Tutor] pychecker: x is None or x == None In-Reply-To: <20050812131435.4B0222332@zeeman.thermal.esa.int> References: <20050812131435.4B0222332@zeeman.thermal.esa.int> Message-ID: <42FCA952.4050603@tds.net> Duncan Gibson wrote: > We've been programming in Python for about a year. Initially we had a > lot of tests of the form > > if x == None: > do_something() > > but then someone thought that we should really change these to > > if x is None: > do_something() > > However. if you run pychecker on these two snippets of code, it > complains about the second, and not the first: > > x.py:6: Using is None, may not always work > > So the question is, which one should we really be using? > If it is the second, how do I get pychecker to shut up? Searching comp.lang.python for 'pychecker "is None"' finds this discussion: http://groups.google.com/group/comp.lang.python/browse_frm/thread/a289d565a40fa435/9afaeb22763aadff?q=pychecker+%22is+None%22&rnum=1&hl=en#9afaeb22763aadff which says that pychecker is confused by the comparison to a constant and you should ignore it. There is a pychecker test (test_input\test90.py and test_output\test90) which shows pychecker ignoring 'is not None' so I think this is a pychecker bug in Python 2.4. It is in the bug tracker here: https://sourceforge.net/tracker/?group_id=24686&atid=382217&func=detail&aid=1227538 The bug references PEP 290 which clearly says that 'is None' is the preferred test: http://www.python.org/peps/pep-0290.html#testing-for-none I don't see a way to turn off this test but I haven't looked in detail at the config options. Kent From winglion at 21cn.com Fri Aug 12 16:17:48 2005 From: winglion at 21cn.com (=?gb2312?B?zPrKrw==?=) Date: Fri, 12 Aug 2005 22:17:48 +0800 Subject: [Tutor] how to run pdb in idle Message-ID: I am a newbie to python.I use pdb in command line quite well. In idle, I open the tree.py file, and type: >>>pdb.run('tree.py') > (1)?() (Pdb) l [EOF] (Pdb) list 10 [EOF] (Pdb) As you see, it didn't work as it was in comand line. Can some body tell me why? (tree.py was a file download from net,that runs well,I just try to get understand how it work.) ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡winglion at 21cn.com ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2005-08-12 From alan.gauld at btinternet.com Fri Aug 12 19:44:24 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Aug 2005 18:44:24 +0100 Subject: [Tutor] how to run pdb in idle References: Message-ID: "Ìúʯ" wrote in message news:zw949187777996.07579 at send6.inner-21cn.com... > I am a newbie to python.I use pdb in command > line quite well. pdb is really best used in the normal OS window. > In idle, I open the tree.py file, and type: >>>>pdb.run('tree.py') >> (1)?() > (Pdb) l While I have used pdb inside IDLE its not great, you are much better off using the graphical debugger built into IDLE. Its not quite as powerful as pDB but it is easier to use! If you are on windows the pythonwin debugger is better than either pdb or IDLE... Alan G From hugonz-lists at h-lab.net Fri Aug 12 20:29:57 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 12 Aug 2005 13:29:57 -0500 Subject: [Tutor] pattern matching is too slow (a little OT) In-Reply-To: <537f59d1050812001160666f27@mail.gmail.com> References: <537f59d1050812001160666f27@mail.gmail.com> Message-ID: <42FCEAA5.7070505@h-lab.net> Hi again =) That's exactly why I use "quiet" with MPlayer, because the output is simply too much to be parsed, and MPlayer will block waiting for you to read the buffer (so it stops playing) My suggestion is: forget about parsing the huge amounts of output MPlayer gives, and use its slave mode instead to know where in the video you are) Vinay Reddy wrote: > Hi, > I am writing a front-end for an application (mplayer). I used the > popen2 call to open pipes for bi-directional communication. > > I set the output pipe from the application to non-blocking mode using: > fcntl.fcntl(self.mplayerOut, fcntl.F_SETFL, os.O_NONBLOCK) > > The problem is that it takes about 10 seconds just to parse through > the inital dump of mplayer (during which mplayer stops playing). > > I'm using the following code to read from 'mplayerOut': > > while True: > try: > temp = self.mplayerOut.readline() > print temp > if re.compile("^A:").search(temp): > print "abc" > except StandardError: > break > > If the remove the re.compile() statement, then the output is > instantaneous and there is no delay. Why is pattern matching so slow? > It's increasing the time almost by 1 second per line of output. How > can I get it to run faster? > > Any help will be appreciated. > > Regards, > Vinay Reddy > > PS: This is my first python program. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Fri Aug 12 20:35:18 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 12 Aug 2005 13:35:18 -0500 Subject: [Tutor] pattern matching is too slow In-Reply-To: <537f59d1050812001160666f27@mail.gmail.com> References: <537f59d1050812001160666f27@mail.gmail.com> Message-ID: <42FCEBE6.40103@h-lab.net> hi Vinay, Reading through other posts, looks like you got somewhare with the nonblocking IO. Can you comment on what you did to get it working? The whole fcntl thing? Thanks, Hugo Vinay Reddy wrote: > Hi, > I am writing a front-end for an application (mplayer). I used the > popen2 call to open pipes for bi-directional communication. > > I set the output pipe from the application to non-blocking mode using: > fcntl.fcntl(self.mplayerOut, fcntl.F_SETFL, os.O_NONBLOCK) > > The problem is that it takes about 10 seconds just to parse through > the inital dump of mplayer (during which mplayer stops playing). > > I'm using the following code to read from 'mplayerOut': > > while True: > try: > temp = self.mplayerOut.readline() > print temp > if re.compile("^A:").search(temp): > print "abc" > except StandardError: > break > > If the remove the re.compile() statement, then the output is > instantaneous and there is no delay. Why is pattern matching so slow? > It's increasing the time almost by 1 second per line of output. How > can I get it to run faster? > > Any help will be appreciated. > > Regards, > Vinay Reddy > > PS: This is my first python program. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From vinayvinay at gmail.com Fri Aug 12 20:42:38 2005 From: vinayvinay at gmail.com (Vinay Reddy) Date: Fri, 12 Aug 2005 18:42:38 +0000 Subject: [Tutor] pattern matching is too slow In-Reply-To: <42FCEBE6.40103@h-lab.net> References: <537f59d1050812001160666f27@mail.gmail.com> <42FCEBE6.40103@h-lab.net> Message-ID: <537f59d105081211425d4d3615@mail.gmail.com> > Reading through other posts, looks like you got somewhare with the > nonblocking IO. Can you comment on what you did to get it working? The > whole fcntl thing? I am able to use non-blocking I/O, but I am unable to get the mplayer status messages. It's just not there in the mplayer output pipe. I just posted on the mplayer community regarding this. To use non-blocking I/O: fcntl.fcntl(, fcntl.F_SETFL, os.O_NONBLOCK) is enough. If there's nothing to read from a pipe, instead of blocking, an exception is generated. Regards, Vinay From alan.gauld at btinternet.com Fri Aug 12 21:13:35 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Aug 2005 20:13:35 +0100 Subject: [Tutor] Curses example on Linux? References: <01d801c59cb4$132538e0$bea68651@xp> Message-ID: "Hossein Movahhedian" wrote in message news:Pine.LNX.4.58.0508091603050.5555 at Rakhsh.Rostam.Dastan... > "ky = chr(msvcrt.getch())". The other problem is that when > the program is finished the previous terminal state is not > restored (I am using xterm on Linux). OK, experimenting with the Linux stty command shows that $ stty echo -nl will restore the terminal to the proper settings. I still haven't figured out how to do it from inside python/curses - that's my next step! Alan G. From alan.gauld at freenet.co.uk Sat Aug 13 12:50:40 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 13 Aug 2005 11:50:40 +0100 Subject: [Tutor] pychecker: x is None or x == None References: <20050812131435.4B0222332@zeeman.thermal.esa.int> Message-ID: <06b301c59ff4$dd04e7d0$bea68651@xp> > if x == None: > do_something() > > but then someone thought that we should really change these to > > if x is None: > do_something() > > However. if you run pychecker on these two snippets of code, it > complains about the second, and not the first: Personally I'd use if not x: do_something() No idea what pyChecker thinks of that though! :-) And of course it's slightly different to a specific check for None, it will catch 0, [], '',"", etc... Of the two forms you suggest I'd stick with equality since the identity test (is) assumes that only one instance of None ever exists which could potentially change in some future exotic version of Python... You really are interested in the value of x not its identity. Alan G. From davholla2002 at yahoo.co.uk Sat Aug 13 14:18:26 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat, 13 Aug 2005 13:18:26 +0100 (BST) Subject: [Tutor] python and xml Message-ID: <20050813121826.50676.qmail@web25402.mail.ukl.yahoo.com> What is a good way of using xml and python ? I tried to install PyXML but I get this as an error message :- python setup.py Traceback (most recent call last): File "setup.py", line 127, in ? config_h_vars = parse_config_h(open(config_h)) IOError: [Errno 2] No such file or directory: '/usr/include/python2.3/pyconfig.h BTW there is a competition to make a sudoku solve ?500 for the best entry see here if you are interested :- http://www.linuxformat.co.uk/index.php?name=PNphpBB2&file=viewtopic&t=559&sid=2e3eec3b842c470b497aabc853ace21c ___________________________________________________________ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com From davholla2002 at yahoo.co.uk Sat Aug 13 14:19:26 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat, 13 Aug 2005 13:19:26 +0100 (BST) Subject: [Tutor] Python and xml Message-ID: <20050813121926.58302.qmail@web25403.mail.ukl.yahoo.com> I forgot to say that I am using knoppix 3.9 ___________________________________________________________ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com From geek_show at dsl.pipex.com Sat Aug 13 18:18:22 2005 From: geek_show at dsl.pipex.com (joe_schmoe) Date: Sat, 13 Aug 2005 17:18:22 +0100 Subject: [Tutor] Invoking bash from within a python program Message-ID: <42FE1D4E.4080505@dsl.pipex.com> Hi Pythoneers I'm sure that somewhere in the dim and distant past this was asked, but I'll be b***ered if I can find reference to it, and google searches haven't been too illuminating yet. Anyway, how do I call bash to run a program - e.g. slocate - from within a python program. I believe that I have to import the OS first (or do I?) and I was thinking something like: ... sh slocate file_name > python_defined_list ... This is to populate a list which would then become the filename list for the remove file command to iterate through sequentially and delete, as in: for i in python_defined_list: rm -fr i How the heck do I set that kind of interaction between bash and python and the user home directory content up? Any thoughts? /j From vinayvinay at gmail.com Sat Aug 13 19:29:30 2005 From: vinayvinay at gmail.com (Vinay Reddy) Date: Sat, 13 Aug 2005 17:29:30 +0000 Subject: [Tutor] Invoking bash from within a python program In-Reply-To: <42FE1D4E.4080505@dsl.pipex.com> References: <42FE1D4E.4080505@dsl.pipex.com> Message-ID: <537f59d1050813102918391c69@mail.gmail.com> > I'm sure that somewhere in the dim and distant past this was asked, but > I'll be b***ered if I can find reference to it, and google searches > haven't been too illuminating yet. Anyway, how do I call bash to run a > program - e.g. slocate - from within a python program. I believe that I > have to import the OS first (or do I?) and I was thinking something like: > > ... > sh slocate file_name > python_defined_list You can directly run slocate (or any other program) using the os.popen* command. Refer to: http://docs.python.org/lib/os-newstreams.html. And you do need to import the os module. The function call will be something like: inStream, outStream = os.popen2("slocate file_name") You can then read the output from outStream. HTH, Vinay Reddy From jonasmg at SoftHome.net Sat Aug 13 20:20:58 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Sat, 13 Aug 2005 19:20:58 +0100 Subject: [Tutor] iterating in the same line Message-ID: <42FE3A0A.9030700@SoftHome.net> I would check 3 words at the starting of a line s=['foo','bar','qwe'] if ln.startswith(s): (this is bad) what is the best way for making it? if max(map(ln.startswith,s)): or reduce(lambda m,n:m or n, map(ln.startswith, s)) Thanks! From dyoo at hkn.eecs.berkeley.edu Sat Aug 13 22:03:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 13 Aug 2005 13:03:31 -0700 (PDT) Subject: [Tutor] Invoking bash from within a python program In-Reply-To: <537f59d1050813102918391c69@mail.gmail.com> Message-ID: On Sat, 13 Aug 2005, Vinay Reddy wrote: > > Anyway, how do I call bash to run a program - e.g. slocate - from > > within a python program. I believe that I have to import the OS first > > (or do I?) and I was thinking something like: > > > > ... > > sh slocate file_name > python_defined_list > > You can directly run slocate (or any other program) using the > os.popen* command. Refer to: > http://docs.python.org/lib/os-newstreams.html. > And you do need to import the os module. Hi Joe, Also, if you have a recent version of Python (Python 2.4), the 'subprocess' module might be worth a look: http://www.python.org/doc/lib/module-subprocess.html > > This is to populate a list which would then become the filename list > > for the remove file command to iterate through sequentially and > > delete, as in: > > > > for i in python_defined_list: > > rm -fr i 'shutil' and its rmtree() function may be helpful for you: http://www.python.org/doc/lib/module-shutil.html Good luck! From ja_roush at mminternet.com Sat Aug 13 22:28:31 2005 From: ja_roush at mminternet.com (Jim Roush) Date: Sat, 13 Aug 2005 13:28:31 -0700 Subject: [Tutor] Sorting a list of lists aka nested lists Message-ID: <42FE57EF.3000502@mminternet.com> I have a python script that creates a list of lists like so: Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 0, 0 ] ) After Quant is created, I want to sort it by MTD. If I use a simple Quant.sort(), I assume its going to sort by 'db_ticker' which is not what I want. I've been trying to figure out how to use the cmp() in a list sort method and I have failed to understand. Please help. -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.338 / Virus Database: 267.10.8/71 - Release Date: 8/12/2005 From dyoo at hkn.eecs.berkeley.edu Sat Aug 13 22:35:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 13 Aug 2005 13:35:11 -0700 (PDT) Subject: [Tutor] iterating in the same line In-Reply-To: <42FE3A0A.9030700@SoftHome.net> Message-ID: On Sat, 13 Aug 2005, Jonas Melian wrote: > I would check 3 words at the starting of a line > > s=['foo','bar','qwe'] > > if ln.startswith(s): (this is bad) Hi Jonas, Just checking: is this similar to a question brought up a few days ago? http://mail.python.org/pipermail/tutor/2005-August/040592.html Do you really need to do this in one line, or would it be sufficient to write a function definition that you can reuse? You mentioned earlier that: > if ln.startswith(s): (this is bad) But the general idea is a good one! You can write your own function called startswithany(), which will then read as: if startswithany(ln, s): ... and writing a simple version of startswithany() should be straightforward. > what is the best way for making it? > > if max(map(ln.startswith,s)): > or > reduce(lambda m,n:m or n, map(ln.startswith, s)) I'm not so sure about this. It does more work than it needs to, and it doesn't scan well for human beings. *grin* If you really want to do it this way, at leeast wrap the it in a well-named function. But if you really insist on getting it done in one line, take a look at the Regular Expression HOWTO: http://www.amk.ca/python/howto/regex/ Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sat Aug 13 22:38:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 13 Aug 2005 13:38:21 -0700 (PDT) Subject: [Tutor] Sorting a list of lists aka nested lists In-Reply-To: <42FE57EF.3000502@mminternet.com> Message-ID: On Sat, 13 Aug 2005, Jim Roush wrote: > I have a python script that creates a list of lists like so: > > Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 0, 0 ] ) > > After Quant is created, I want to sort it by MTD. If I use a simple > Quant.sort(), I assume its going to sort by 'db_ticker' which is not > what I want. > > I've been trying to figure out how to use the cmp() in a list sort > method and I have failed to understand. Hi Jim, AMK has written a nice mini-tutorial on how to use a list's sort() effectively: http://www.amk.ca/python/howto/sorting/sorting.html Does his tutorial make sense, or are there parts in there that are baffling? Please feel free to ask questions on it, and we'll try to help. From ja_roush at mminternet.com Sat Aug 13 23:03:50 2005 From: ja_roush at mminternet.com (Jim Roush) Date: Sat, 13 Aug 2005 14:03:50 -0700 Subject: [Tutor] Sorting a list of lists aka nested lists In-Reply-To: References: Message-ID: <42FE6036.1020304@mminternet.com> Danny Yoo wrote: >On Sat, 13 Aug 2005, Jim Roush wrote: > > > >>I have a python script that creates a list of lists like so: >> >> Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 0, 0 ] ) >> >>After Quant is created, I want to sort it by MTD. If I use a simple >>Quant.sort(), I assume its going to sort by 'db_ticker' which is not >>what I want. >> >>I've been trying to figure out how to use the cmp() in a list sort >>method and I have failed to understand. >> >> > > >Hi Jim, > >AMK has written a nice mini-tutorial on how to use a list's sort() >effectively: > > http://www.amk.ca/python/howto/sorting/sorting.html > >Does his tutorial make sense, or are there parts in there that are >baffling? Please feel free to ask questions on it, and we'll try to help. > > > > > > I actually saw this page this morning, which leads me to believe what I want is something like: Quant.sort(lambda x, y: x-y) except how does x and y relate to the list of lists I created? -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.338 / Virus Database: 267.10.8/71 - Release Date: 8/12/2005 From bgailer at alum.rpi.edu Sun Aug 14 00:49:26 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 13 Aug 2005 16:49:26 -0600 Subject: [Tutor] iterating in the same line In-Reply-To: <42FE3A0A.9030700@SoftHome.net> References: <42FE3A0A.9030700@SoftHome.net> Message-ID: <6.1.2.0.0.20050813164318.02d7eec0@mail.mric.net> At 12:20 PM 8/13/2005, Jonas Melian wrote: >I would check 3 words at the starting of a line > >s=['foo','bar','qwe'] > >if ln.startswith(s): (this is bad) > >what is the best way for making it? Iterations over a list of this nature are most succinctly done using list comprehensions. if [l for l in s if ln.startswith(l)]: Caveat: This will test every word in s. If s is a large list it would be more efficient to break as soon as a match is found: match = False for l in s: if ln.startswith(l): match = True break The 3rd alternative is to use regular expression matching. That is beyond the scope of this thread. [snip] Bob Gailer mailto:bgailer at alum.rpi.edu 303 442 2625 home 720 938 2625 cell From usedtire at pbembattletech.com Sun Aug 14 02:17:19 2005 From: usedtire at pbembattletech.com (Jesse Lands) Date: Sun, 14 Aug 2005 00:17:19 +0000 Subject: [Tutor] re Message-ID: <20050814001719.3be4c4bf.usedtire@pbembattletech.com> I am trying to create a simple GUI that will track a network connection using ping. It's a starter project for me so I am sure there are other easier ways of doing it, but I am learning, so bare with me. I figured out the first part import os ping = os.popen('ping -c 4 10.0.8.200') ping_result = ping.read() I assume I have to use Regular Expression to read the results, but I don't quite understand it. Can someone explain it or point me in a direction to where it's explained better then what I could find with google. TIA Jesse -- JLands Arch Current(Laptop) Slackware 9.1(Server) Slackware Current(Desktop) Registered Linux User #290053 From nequeo at gmail.com Sun Aug 14 07:36:42 2005 From: nequeo at gmail.com (Simon Gerber) Date: Sun, 14 Aug 2005 15:36:42 +1000 Subject: [Tutor] PyGTK, classes and return values? Message-ID: <42FED86A.1080409@gmail.com> Greetings, all. I've been stumbling my way through the PyGTK tutorial, with mixed success. So far I have been able to achieve everything I have set out to achieve, with one rather major exception. I have a class called 'AddAccountWindow' that creates a window asking for hostname, username, password, account-type. That sorta thing. When the user fills out the data and hits 'okay', it creates a class (self.account) with the required parameters. So far, so good. But now, I have no idea how to get that class *out* of AddAccountWindow. I can't seem to find any way to return it. Nor can I successfully pass anything in by reference, change it into the required class, and pass it out again. Any help would be much appreciated. Regards, -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber nequeo at gmail.com From dyoo at hkn.eecs.berkeley.edu Sun Aug 14 07:52:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 13 Aug 2005 22:52:04 -0700 (PDT) Subject: [Tutor] Sorting a list of lists aka nested lists In-Reply-To: <42FE6036.1020304@mminternet.com> Message-ID: > >AMK has written a nice mini-tutorial on how to use a list's sort() > >effectively: > > > > http://www.amk.ca/python/howto/sorting/sorting.html > > > >Does his tutorial make sense, or are there parts in there that are > >baffling? Please feel free to ask questions on it, and we'll try to > >help. > > > I actually saw this page this morning, which leads me to believe what I > want is something like: > > Quant.sort(lambda x, y: x-y) > > except how does x and y relate to the list of lists I created? Hi Jim, Whenever we're sorting lists of objects, we have to tell Python how to detect whenever two things are misordered. Let's make this concrete: say that we have a list of names, like this: ####### >>> names = ['hamlet', 'rosencrantz', 'guildenstern'] ####### We'd like to order things "alphabetically". (... and pretend that we don't know about list.sort() for the moment. *grin*) How could we go about doing this? One way is to scan across the list, pairwise. As we look at adjacent pairs of words, we can check to see if those words are misordered, and if so, swap! I'll step through this just so you get the general idea of what's so useful about a comparison function. Let's start looking at the first two names in the list. ####### >>> names[0], names[1] ('hamlet', 'rosencrantz') ####### Are they in the right order? We know they are, but again, let's pretend that we don't. *grin* So the question really is: how does Python know if they're in the right order? We can ask Python this "are they in order?" question by using the built-in cmp() function: ####### >>> cmp(names[0], names[1]) -1 ####### If cmp gives a negative number, that means that names[0] is "less than" names[1], and so, yes, they are. So we'll leave the first two list elements alone for the moment. Now let's look at the next pair: ###### >>> cmp(names[1], names[2]) 1 ###### Ok, this is different. cmp() gives a positive value if the first argument and the second argument are misordered. They should be swapped around! So let's swap them: ####### >>> names[1], names[2] = names[2], names[1] ####### Intuitively, we've increased the "order" of our list by doing the swap. Just to make sure things are fine, let's cmp() both pairs again, and make sure everything comes out as negative. ####### >>> cmp(names[0], names[1]) 1 ####### Oh, now the first two elements of our list are misordered. Let's swap again. ###### >>> names[0], names[1] = names[1], names[0] ###### Do we have to swap anymore? Let's check again: ###### >>> cmp(names[0], names[1]) -1 >>> cmp(names[1], names[2]) -1 ###### Ok, good. No more need to swap things around anymore. Now that we swapped them, let's look at our list: ####### >>> names ['guildenstern', 'hamlet', 'rosencrantz'] ####### Everything's in the right "alphabetical" order now. Hurrah! What Python actually does in sorting a list is a little different that what we described above. But conceptually, it uses a comparison function to detect disorder, and increases the order of a list by swapping and moving things around, until everything's truly sorted. These techniques are called "comparison-based" sorts, because they compare between two elements at a time. Let's change the problem in a slightly wacky way: what if we'd like to order the names by their third letter? ####### def my_custom_cmp(first_name, second_name): return cmp(first_name[2], second_name[2]) ####### Given any two names, we check to see if their respective third letters are misordered. Notice that we've actually reused the built-in cmp() operator, but got it to concentrate on the third letter of the given names. Let's try it out: ####### >>> my_custom_cmp("danny", "jim") 1 >>> my_custom_cmp("jim", "danny") -1 >>> my_custom_cmp("jim", "jim") 0 ####### Once we have this customized comparison function, we can pass it to sort(), and it'll know to use our comparison operator when it's checking for disorder: ####### >>> names.sort(my_custom_cmp) >>> names ['guildenstern', 'hamlet', 'rosencrantz'] ####### Hmmmm. No change. But that's ok; that's perfectly correct. Ok, let's see if we order by the lengths of words: ####### >>> def another_custom_cmp(w1, w2): ... return cmp(len(w1), len(w2)) ... >>> names.sort(another_custom_cmp) >>> names ['hamlet', 'rosencrantz', 'guildenstern'] ####### We've come full-circle. *grin* But I hope that this makes sense. Please feel free to ask questions on any part of this. Good luck! From tegmine at gmail.com Sun Aug 14 08:57:16 2005 From: tegmine at gmail.com (Luis N) Date: Sat, 13 Aug 2005 23:57:16 -0700 Subject: [Tutor] python and xml In-Reply-To: <20050813121826.50676.qmail@web25402.mail.ukl.yahoo.com> References: <20050813121826.50676.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <77bfa81a05081323576893e7e6@mail.gmail.com> On 8/13/05, David Holland wrote: > What is a good way of using xml and python ? ElementTree? http://effbot.org/zone/element-index.htm or, lxml http://codespeak.net/lxml/ Luis. From alan.gauld at freenet.co.uk Sun Aug 14 09:24:02 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 14 Aug 2005 08:24:02 +0100 Subject: [Tutor] iterating in the same line References: <42FE3A0A.9030700@SoftHome.net> Message-ID: <073301c5a0a1$255e6810$bea68651@xp> Sorry Jonas, I don't understand what you are trying to do at all. The subject line and your code snippets don't seem to match up. > Subject: [Tutor] iterating in the same line >I would check 3 words at the starting of a line > > s=['foo','bar','qwe'] > > if ln.startswith(s): (this is bad) Why is it bad -- other than it doesn't work! I think you mean something like for st in s: if line.startswith(st): do something > if max(map(ln.startswith,s)): But this does something completely different! This selects the 'biggest' line that starts with anything in s. then if the biggest line is not null does something? > reduce(lambda m,n:m or n, map(ln.startswith, s)) And this does something different again. It uses map to create a list containg ln if ln startswith one of the strings in s, then tries to reduce that list to one element(which it already is!) by 'or'ing the elements. I can't even begin to guess from that what it is you are actually trying to do. Can you give us more explanation and maybe some sample data? Alan G. From alan.gauld at freenet.co.uk Sun Aug 14 09:28:08 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 14 Aug 2005 08:28:08 +0100 Subject: [Tutor] Invoking bash from within a python program References: Message-ID: <073901c5a0a1$b8338490$bea68651@xp> > Also, if you have a recent version of Python (Python 2.4), the > 'subprocess' module might be worth a look: > > http://www.python.org/doc/lib/module-subprocess.html > Is it just me or does anyone else think the new subprocess module is making something fairly easy into something fairly complicated? There are an awful lot of options to the Popen call... subprocess looks like the classic example of trying to rationalise many simple things into one and in the process making it much more complicated. But I'm not using 2.4 yet so can only go by the module documentation. How has it been in practice? Alan G. From alan.gauld at freenet.co.uk Sun Aug 14 09:32:48 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 14 Aug 2005 08:32:48 +0100 Subject: [Tutor] Sorting a list of lists aka nested lists References: <42FE57EF.3000502@mminternet.com> Message-ID: <073f01c5a0a2$61cb32a0$bea68651@xp> > Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, > 0, 0 ] ) > > After Quant is created, I want to sort it by MTD. If I use a simple > Quant.sort(), I assume its going to sort by 'db_ticker' which is not > what I want. you need to write your own comparison function. Basically it will take two of your lists and return -1,0 or 1. Or you can use Python's own logic to help def cmplists(lst1,lst2): return cmp(lst1[2],lst2[2]) Now you can sort Quant by passing your function into sort... HTH, Alan G. From jonasmg at SoftHome.net Sun Aug 14 10:46:15 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Sun, 14 Aug 2005 09:46:15 +0100 Subject: [Tutor] iterating in the same line In-Reply-To: <073301c5a0a1$255e6810$bea68651@xp> References: <42FE3A0A.9030700@SoftHome.net> <073301c5a0a1$255e6810$bea68651@xp> Message-ID: <42FF04D7.5020200@SoftHome.net> I'm trying match the lines that starting with someone variable in 's' These sentences: if max(map(ln.startswith,s)): reduce(lambda m,n:m or n, map(ln.startswith, s)): were said me in #python for this proposal. Alan G wrote: > Sorry Jonas, > > I don't understand what you are trying to do at all. > The subject line and your code snippets don't seem to match up. > >> Subject: [Tutor] iterating in the same line > > >> I would check 3 words at the starting of a line >> >> s=['foo','bar','qwe'] >> >> if ln.startswith(s): (this is bad) > > > Why is it bad -- other than it doesn't work! > I think you mean something like > > for st in s: > if line.startswith(st): do something > >> if max(map(ln.startswith,s)): > > > But this does something completely different! > > This selects the 'biggest' line that starts with anything in s. > then if the biggest line is not null does something? > >> reduce(lambda m,n:m or n, map(ln.startswith, s)) > > > And this does something different again. > It uses map to create a list containg ln if ln startswith one of the > strings in s, then tries to reduce that list to one element(which it > already is!) by 'or'ing the elements. > > I can't even begin to guess from that what it is you are actually > trying to do. > > Can you give us more explanation and maybe some sample data? > > Alan G. > > From alan.gauld at freenet.co.uk Sun Aug 14 11:16:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 14 Aug 2005 10:16:24 +0100 Subject: [Tutor] iterating in the same line References: <42FE3A0A.9030700@SoftHome.net> <073301c5a0a1$255e6810$bea68651@xp> <42FF04D7.5020200@SoftHome.net> Message-ID: <074f01c5a0b0$de182620$bea68651@xp> > I'm trying match the lines that starting with someone variable in > 's' In that case this is the simplest approach: >> for st in s: >> if line.startswith(st): do something That means that if you are reading the lines from a file you'd need a neted loop: for line in someFile: for substring in s: if line.startswith(substring): # do something here Alternatively a regular exression match as suggested by others is probably faster. Alan G. From geek_show at dsl.pipex.com Sun Aug 14 12:33:09 2005 From: geek_show at dsl.pipex.com (joe_schmoe) Date: Sun, 14 Aug 2005 11:33:09 +0100 Subject: [Tutor] Invoking bash from within a python program In-Reply-To: References: Message-ID: <42FF1DE5.8030807@dsl.pipex.com> Danny Yoo wrote: > > On Sat, 13 Aug 2005, Vinay Reddy wrote: > > >>>Anyway, how do I call bash to run a program - e.g. slocate - from >>>within a python program. I believe that I have to import the OS first >>>(or do I?) and I was thinking something like: >>> >>>... >>>sh slocate file_name > python_defined_list >> >>You can directly run slocate (or any other program) using the >>os.popen* command. Refer to: >>http://docs.python.org/lib/os-newstreams.html. >>And you do need to import the os module. > > > > Hi Joe, > > Also, if you have a recent version of Python (Python 2.4), the > 'subprocess' module might be worth a look: > > http://www.python.org/doc/lib/module-subprocess.html > > > > >>>This is to populate a list which would then become the filename list >>>for the remove file command to iterate through sequentially and >>>delete, as in: >>> >>>for i in python_defined_list: >>> rm -fr i > > > > 'shutil' and its rmtree() function may be helpful for you: > > http://www.python.org/doc/lib/module-shutil.html > > Good luck! > > Thanks Danny & Vinay If I was to use the subprocess management module (as per Danny's suggestion), it looks like I should be able to invoke it using the shell=True argument. If my reading of http://www.python.org/doc/lib/node230.html is correct, this would enable the output of the command to be run through the shell (bash, in my case) without having to worry about piping the output back to the shell manually. This would then pass the list back to bash for it to iterate through the list to delete the filenames. The basic idea I was toying around with is to create a delete/uninstall program that would take the output of slocate and iterate through that deleting all of the files associated with the program I wanted to uninstall without having to do so manually. Using tar balled source code does not seem to allow for an easy and straight forward way of uninstalling once the source directory has been deleted. I am also going to explore how to do this using bash and some basic shell programming and then work out which would be the better approach. Thanks for your help folks. From bgailer at alum.rpi.edu Sun Aug 14 16:35:00 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 14 Aug 2005 08:35:00 -0600 Subject: [Tutor] re and more ... read on In-Reply-To: <20050814001719.3be4c4bf.usedtire@pbembattletech.com> References: <20050814001719.3be4c4bf.usedtire@pbembattletech.com> Message-ID: <6.1.2.0.0.20050814080111.02cd59d8@mail.mric.net> At 06:17 PM 8/13/2005, Jesse Lands wrote: >I am trying to create a simple GUI that will track a network connection >using ping. It's a starter project for me so I am sure there are other >easier ways of doing it, but I am learning, so bare with me. Are we taking our clothes off? Reminds me of the old Adventure (Colossal Cave) game where the player decides to kill the bear. The response was "What! your bare hands against his *bear* hands?" >I figured out the first part > >import os >ping = os.popen('ping -c 4 10.0.8.200') >ping_result = ping.read() > > >I assume I have to use Regular Expression to read the results, but I don't >quite understand it. Can someone explain it or point me in a direction to >where it's explained better then what I could find with google. I don't know what links you found, but here are a few: http://www.amk.ca/python/howto/regex/ http://www.regular-expressions.info/quickstart.html - this looks like a nice easy start tutorial I suggest you post the output from ping and tell us what part of that you want. Then we can help more. I also suggest learning re as it is a most useful tool. Yesterday I used urllib2 to grab a web page with many links to pdf files on it. SInce my broswer insists on opening instead of downloading such files, I used re to extract the urls from the links, then read and wrote each file. Since I am delighted with this code I post it in full. Notice especially the re.findall(). import urllib2, re x = urllib2.urlopen(r'http://www.cde.state.co.us/cdeassess/csap/as_filelayouts.htm') p = x.readlines() # get just the lines containing '.pdf' the "easy way" pdfs = [l for l in p if '.pdf' in l] # pdfs[0] = '

Grades 3-10 CSAP Mathematics \r\n' linkText = '\n'.join(pdfs) # convert the list to a string for re # here I use re to grab text between the 2 "s pdfs2 = re.findall(r'"(.*)"', linkText) # findall = repeatedly apply the re until end of string # r = treat following string literal as "raw" so one does not need to escape \ # the pattern "(.*)" " = find a "; ( = begin a group . = match any character ; # * = repeat matching the .; # ) = end the group; " = stop matching the . when you find a "; # using () to group ensures that just the part of the string that matches .* will be kept # result is a list of desired strings # pdfs2[0] = '2005/Mathematics%203-10%20DST%20grt%202005.pdf' # In retrospect I could also have used re.findall(r' Message-ID: <076201c5a0e5$9ccd6ab0$bea68651@xp> > import os > ping = os.popen('ping -c 4 10.0.8.200') > ping_result = ping.read() > > > I assume I have to use Regular Expression to read the results, You shouldn't need to. If I call ping I get somethjing like: $ ping www.google.com PING www.l.google.com (66.102.7.147): 56 data bytes 64 bytes from 66.102.7.147: icmp_seq=0 ttl=229 time=220 ms 64 bytes from 66.102.7.147: icmp_seq=1 ttl=229 time=188 ms 64 bytes from 66.102.7.147: icmp_seq=2 ttl=229 time=188 ms So to read that I would just use the string.split() method to break it into fields and the IP address is the 4th field and the time 7th. But it depends on what exactly you want to do with it. If you do want a basic intro to regex you can try my tutorial topic on them. It doesn't cover the deeper bits but gives the 30% I use 70% of the time... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ingarse at broadpark.no Sun Aug 14 18:16:32 2005 From: ingarse at broadpark.no (Kristian Evensen) Date: Sun, 14 Aug 2005 19:16:32 +0300 Subject: [Tutor] Regexp with multiple patterns in Python Message-ID: <000101c5a0eb$89060900$6400a8c0@Kristian> Hello, I am working on a way to parse a file and wondered if there is a way to check for multiple patterns. The reason I wonder this is because it would make everything a lot easier regarding calculations on what words to use and so on. What I want to do is to check for two patterns to make sure all occurrences of pattern1 and pattern2 come in the same order as they do in the file I parse. It it contains a number of computer-games I would like the output to look something like this: PC, Battlefield, Battlefield2 PS2, Battlefield 2: Modern Combat. The file is constructed somewhat similar to this: PC Battlefield, Battfiled2 PS2 Battlefield 2: Modern Combat Using the following expression (and re.findall) I get somewhat closer: pattern8 = re.compile(r'search.asp\?title=battlefield.*?><.*?>(PCCD|XBOX 360|XBOX|PLAYSTATION PSP|PLAYSTATION 2) - TITLE<|game.asp\?id=(\d+).*?><.*?><.*?>(.*?)<') The output is: [('PCCD', '', ''), ('PLAYSTATION 2', '', ''), ('XBOX', '', ''), ('XBOX 360', '', ''), ('PLAYSTATION PSP', '', ''), ('', '4262', ' Battlefield 2: Modern Combat')] I get the last game mentioned in the file, but none of the others. Anybody know how to solve this? Thanks in advance for any help and have a great day! -Kristian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050814/eaa0f212/attachment.htm From jfouhy at paradise.net.nz Mon Aug 15 01:18:26 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 15 Aug 2005 11:18:26 +1200 (NZST) Subject: [Tutor] Sorting a list of lists aka nested lists In-Reply-To: <073f01c5a0a2$61cb32a0$bea68651@xp> References: <42FE57EF.3000502@mminternet.com> <073f01c5a0a2$61cb32a0$bea68651@xp> Message-ID: <1124061506.42ffd14287caa@www.paradise.net.nz> Quoting Alan G : > > Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, > > 0, 0 ] ) > > After Quant is created, I want to sort it by MTD. If I use a simple > > Quant.sort(), I assume its going to sort by 'db_ticker' which is not > > what I want. > you need to write your own comparison function. > Basically it will take two of your lists and return -1,0 or 1. > > Or you can use Python's own logic to help > > def cmplists(lst1,lst2): > return cmp(lst1[2],lst2[2]) > > Now you can sort Quant by passing your function into sort... Note that in Python2.4+, you can use key= instead: def sortKey(lst): return lst[2] Quant.sort(key=sortKey) This is more effient than specifying a different comparison function, because the key function is only called once for each element. -- John. From vinayvinay at gmail.com Mon Aug 15 06:00:53 2005 From: vinayvinay at gmail.com (Vinay Reddy) Date: Mon, 15 Aug 2005 04:00:53 +0000 Subject: [Tutor] Invoking bash from within a python program In-Reply-To: <42FF1DE5.8030807@dsl.pipex.com> References: <42FF1DE5.8030807@dsl.pipex.com> Message-ID: <537f59d105081421004f085f8a@mail.gmail.com> > The basic idea I was toying around with is to create a delete/uninstall > program that would take the output of slocate and iterate through that > deleting all of the files associated with the program I wanted to > uninstall without having to do so manually. Using tar balled source code > does not seem to allow for an easy and straight forward way of > uninstalling once the source directory has been deleted. I am also going > to explore how to do this using bash and some basic shell programming > and then work out which would be the better approach. Why not: slocate |xargs rm -rf Vinay From vinayvinay at gmail.com Mon Aug 15 06:10:42 2005 From: vinayvinay at gmail.com (Vinay Reddy) Date: Mon, 15 Aug 2005 04:10:42 +0000 Subject: [Tutor] parsing through an output stream Message-ID: <537f59d105081421101cde9b74@mail.gmail.com> Hi, I tried running mplayer from a python program using the popen2 command and read the returned output stream in non-blocking mode. But, I did not getting any of the status messages given out by mplayer (I did get the initial dump by mplayer). I am using the following to read the output: try: # get the last line of output for status in self.mplayerOut: if not status: break print status except StandardError: pass MPlayer terminates a status line with a '\r'. Is that the problem? If so, I want python to recognize \r as a line terminator. How do I do this? Any help will be appreciated. Regards, Vinay From w.diaz at spitech.com Mon Aug 15 07:39:26 2005 From: w.diaz at spitech.com (Diaz, Wendell) Date: Mon, 15 Aug 2005 13:39:26 +0800 Subject: [Tutor] UTf-8 to Entity Message-ID: <2091E989C930C64FB8FEE72F88C93A5806FB5D74@spi-mail2003.spitech.com> Hey guys, Hope you can help me on this. I want to make a python program which opens an XML (UTF-8 encoding) and do a search & replace. It will search the Unicode and replace them with their equivalent entity name. The program will read a look-up table (a tab delimited text file) which list the unicodes that needs to be replace with enity names. Example of the look-up table: &nobreakspace; [tab] 000A0 Thanks in advance, Wendell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050815/6f3f0177/attachment.htm From falcon3166 at hotmail.com Mon Aug 15 07:54:22 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 14 Aug 2005 23:54:22 -0600 Subject: [Tutor] Is it possible to... Message-ID: Is it possible to create a def that not only deals cards, but also assigns a value to each rank, except that the Jacks, Queens, and Kings all are the same value as the 10s? If this is possible, how should I go about doing this? Sorry if I'm asking what for most people is a basic question, but this one has been bugging me. Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050814/e6d0fa9c/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050814/e6d0fa9c/PinnoNathanPaul.vcf From falcon3166 at hotmail.com Mon Aug 15 08:22:14 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 15 Aug 2005 00:22:14 -0600 Subject: [Tutor] How can I make this run right? Message-ID: The following code is supposed to take in a number, and print number!: n = int(raw_input("Number: ")) x = n-1 while 1: t = n*x while x > 1: x -= 1 else: break print t Why isn't it working, and how can I make it print out the correct output? Thanks in advance, Nathan --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050815/3f052789/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 783 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050815/3f052789/PinnoNathanPaul.vcf From kabads at gmail.com Mon Aug 15 09:17:27 2005 From: kabads at gmail.com (Adam Cripps) Date: Mon, 15 Aug 2005 08:17:27 +0100 Subject: [Tutor] Python hosting again In-Reply-To: References: Message-ID: On 8/11/05, Jorge Louis De Castro wrote: > > > Hello, > > I'm interested in writing with my own Python implementation of a Jabber IM > server and client. > Anyone knows where I could host my Python Jabber IM server for a reasonable > monlthy fee? It doesn't need to be a top-notch place since my goal is to > test something else, not the scalability of the application. > > chrs > j. > _______________________________________________ I use http://www.dreamhost.com - they have a jabber server already running for you to use - not sure if this would interfere with what you are trying to do. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From gnumathetes at gmail.com Mon Aug 15 09:36:19 2005 From: gnumathetes at gmail.com (Don Parris) Date: Mon, 15 Aug 2005 03:36:19 -0400 Subject: [Tutor] Replacement for 'Find' Module Message-ID: <66926144050815003663d54fa1@mail.gmail.com> On my Windows XP box running Python 2.4, I attempted to use the 'find' module per the example in Programming Python (Ch. 2) - i.e.: >>>import find >>>find.find('*') However, Python didn't find the find module. The docs say it's now deprecated, but don't point to what tool should be used to replace find. My Googling efforts haven't been fruitful so far. Could someone please point me in the right direction? Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com "Hey man, whatever pickles your list!" From alan.gauld at freenet.co.uk Mon Aug 15 09:37:34 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 15 Aug 2005 08:37:34 +0100 Subject: [Tutor] parsing through an output stream References: <537f59d105081421101cde9b74@mail.gmail.com> Message-ID: <083801c5a16c$357076f0$bea68651@xp> > read the returned output stream in non-blocking mode. But, I did > not getting any of the status messages given out by mplayer Traditionally status messages tend to be sent to stderr rather than stdout (this means that they don't break Unix pipelines). But that means that to read them you will need to use popen2 (Or the new subprocess module) to access stderr. I don't know for sure that mplayer is dping that but I'd say its a strong possibility. HTH, Alan G. From jfouhy at paradise.net.nz Mon Aug 15 09:45:58 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 15 Aug 2005 19:45:58 +1200 (NZST) Subject: [Tutor] Is it possible to... In-Reply-To: References: Message-ID: <1124091958.43004836802f8@www.paradise.net.nz> Quoting Nathan Pinno : > Is it possible to create a def that not only deals cards, but also > assigns a value to each rank, except that the Jacks, Queens, and Kings > all are the same value as the 10s? > If this is possible, how should I go about doing this? Nearly everything is possible; you just have to order your thoughts correctly :-) In this case, you're looking for a way of mapping from cards to values. Python has a mapping type built in, called a dictionary. You can read about it here: http://docs.python.org/tut/node7.html#SECTION007500000000000000000 and here: http://docs.python.org/lib/typesmapping.html -- John. From nequeo at gmail.com Mon Aug 15 09:46:02 2005 From: nequeo at gmail.com (Simon Gerber) Date: Mon, 15 Aug 2005 17:46:02 +1000 Subject: [Tutor] Replacement for 'Find' Module In-Reply-To: <66926144050815003663d54fa1@mail.gmail.com> References: <66926144050815003663d54fa1@mail.gmail.com> Message-ID: <667ca7b6050815004618b1f754@mail.gmail.com> You could probably do something like this... (Note: This example is for Linux - but you can adapt it fairly easily to Windows.) # E.g. Find every .inf file on a CD-ROM. path = '/cdrom' # 'E:\\' or whatever for Windows.... inf_list = [] for root, dirs, files in os.walk(path): for current_file in files: if '.inf' in current_file: inf_list.append(os.path.join(root, current_file)) I, too, would be interested in knowing if anyone has a better way to do this :) You would probably combine the 'glob' module with os.walk to grab what you wanted, and build the list of files that way. Lemme know what you figure out. Cheers, On 15/08/05, Don Parris wrote: > On my Windows XP box running Python 2.4, I attempted to use the 'find' > module per the example in Programming Python (Ch. 2) - i.e.: > >>>import find > >>>find.find('*') > > However, Python didn't find the find module. The docs say it's now > deprecated, but don't point to what tool should be used to replace > find. My Googling efforts haven't been fruitful so far. Could > someone please point me in the right direction? > > Don > -- > DC Parris GNU Evangelist > http://matheteuo.org/ > gnumathetes at gmail.com > "Hey man, whatever pickles your list!" > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nequeo at gmail.com Mon Aug 15 09:48:58 2005 From: nequeo at gmail.com (Simon Gerber) Date: Mon, 15 Aug 2005 17:48:58 +1000 Subject: [Tutor] How can I make this run right? In-Reply-To: <667ca7b60508142346183a65ad@mail.gmail.com> References: <667ca7b60508142346183a65ad@mail.gmail.com> Message-ID: <667ca7b60508150048193a0865@mail.gmail.com> I'd do it like this... And there's probably an even quicker way, if you really sat down and thought about it. n = int(raw_input("Number: ")) x = n-1 while x > 1: n *=x x -=1 print n The reason why it isn't working is because of " while x > 1: x -= 1 " When your program hits this point it stays in the while loop, subtracting 1 from x each time, but not multiplying anything anymore, until it hits break. So your program does this. Number: 4 n = 5 x = 4 t = 20 x = 3 x = 2 x = 1 BREAK. Cheers! On 15/08/05, Nathan Pinno wrote: > > The following code is supposed to take in a number, and print number!: > n = int(raw_input("Number: ")) > x = n-1 > while 1: > t = n*x > while x > 1: > x -= 1 > else: > break > print t > > Why isn't it working, and how can I make it print out the correct output? > > Thanks in advance, > Nathan > --------------------------------------------------------------- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. > --Benjamin Franklin > ------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > From alan.gauld at freenet.co.uk Mon Aug 15 10:16:25 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 15 Aug 2005 09:16:25 +0100 Subject: [Tutor] Is it possible to... References: Message-ID: <085001c5a171$a16f27c0$bea68651@xp> > Is it possible to create a def that not only deals cards, but also > assigns a value to each rank, except that the Jacks, Queens, and > Kings > all are the same value as the 10s? Yes. And you probably need to use a dictionary to hold the value against the card. > Sorry if I'm asking what for most people is a basic question, Nope, this is a very good question. I haven't been paying attention to the card dealing functions posted recently but I assume adding in a dictionary to assign a value per card dealt wouldn't be too hard. You could then return the cards as tuples or somesuch... Alan G From alan.gauld at freenet.co.uk Mon Aug 15 10:20:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 15 Aug 2005 09:20:21 +0100 Subject: [Tutor] How can I make this run right? References: Message-ID: <086501c5a172$8187c6f0$bea68651@xp> > The following code is supposed to take in a number, and print > number!: > n = int(raw_input("Number: ")) > x = n-1 > while 1: > t = n*x > while x > 1: > x -= 1 > else: > break > print t > > Why isn't it working, and how can I make it print out the correct > output? So give is a clue! What is it doing wrong? Is there an error message? What output did you expect? What did you get? Without that information we have to read the code and guess what you were trying to do. Then try to guess what might be different to what you expected. Alan G. From alan.gauld at freenet.co.uk Mon Aug 15 10:20:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 15 Aug 2005 09:20:21 +0100 Subject: [Tutor] How can I make this run right? References: Message-ID: <085c01c5a172$2f360420$bea68651@xp> > The following code is supposed to take in a number, and print > number!: > n = int(raw_input("Number: ")) > x = n-1 > while 1: > t = n*x > while x > 1: > x -= 1 > else: > break > print t > > Why isn't it working, and how can I make it print out the correct > output? So give is a clue! What is it doing wrong? Is there an error message? What output did you expect? What did you get? Without that information we have to read the code and guess what you were trying to do. Then try to guess what might be different to what you expected. Alan G. From jorge at bcs.org.uk Mon Aug 15 11:18:26 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Mon, 15 Aug 2005 10:18:26 +0100 Subject: [Tutor] Event handler for optionmenu Message-ID: Hi, I have an optionmenu widget that works just fine except that can't find docs to get hold of events as they happen, kinda like the command=XYZ of other widgets like buttons. The code I'm using for the option menu is the following: OPTIONS = ["en","pt","es","it","fr","de"] self.startw.variable = StringVar() self.startw.variable.set(OPTIONS[0]) # default value self.startw.whis_butt=apply(OptionMenu, (self.startw, self.startw.variable) + tuple(OPTIONS)) self.startw.whis_butt.grid(column=1, row=3) Now I'd like to have a function like: def onChange(self): # do optionmenu specific stuff but can't find how to do it, how to associate/bind onChange with the optionmenu widget. Any help will be highly appreciated. Chrs j -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050815/16d94665/attachment.htm From geon at post.cz Mon Aug 15 11:41:30 2005 From: geon at post.cz (geon) Date: Mon, 15 Aug 2005 11:41:30 +0200 Subject: [Tutor] Event handler for optionmenu In-Reply-To: References: Message-ID: <4300634A.6050900@post.cz> Jorge Louis De Castro napsal(a): > Hi, > > I have an optionmenu widget that works just fine except that can't > find docs to get hold of events as they happen, kinda like the > command=XYZ of other widgets like buttons. > > The code I'm using for the option menu is the following: > > OPTIONS = ["en","pt","es","it","fr","de"] > self.startw.variable = StringVar() > self.startw.variable.set(OPTIONS[0]) # default value > self.startw.whis_butt=apply(OptionMenu, (self.startw, > self.startw.variable) + tuple(OPTIONS)) > self.startw.whis_butt.grid(column=1, row=3) > > Now I'd like to have a function like: > > def onChange(self): > # do optionmenu specific stuff > > but can't find how to do it, how to associate/bind onChange with the > optionmenu widget. > Any help will be highly appreciated. > This art is called Trace Variable and could be used like this (copied and rearranged from one of the prevously posted message from here): from Tkinter import * OPTIONS = [ "egg", "bunny", "chicken" ] def callbackFunc(name, index, mode): #print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) varValue = root.getvar(name) print varValue # modify the value, just to show it can be done #root.setvar(name, varValue) root = Tk() var = StringVar() var.set(OPTIONS[2]) # default value rememberMe = var.trace_variable('w', callbackFunc) # var.trace('w', callbackFunc) # this works, too w = OptionMenu (root, var, *OPTIONS) w.pack() root.mainloop() Hope its what you asked for :-) -- geon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050815/e35fe061/attachment.htm From amonroe at columbus.rr.com Mon Aug 15 13:04:12 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 15 Aug 2005 07:04:12 -0400 Subject: [Tutor] How can I make this run right? In-Reply-To: References: Message-ID: <3748499768.20050815070412@columbus.rr.com> > The following code is supposed to take in a number, and print number!: > n = int(raw_input("Number: ")) > x = n-1 > while 1: > t = n*x > while x > 1: > x -= 1 > else: > break > print t > Why isn't it working, and how can I make it print out the correct output? One thing you might find handy is IDLE's debugger (if you use IDLE). Turn it on under Debug / Debugger. Make sure the "Source" checkbox is checked. Then hit the step button to run your program in "slow motion" so you can see everything it does one step at a time. (You might have to temporarily click the output window to the front when the raw_input wants you to type a number) Alan From paul.hendrick at gmail.com Mon Aug 15 13:24:25 2005 From: paul.hendrick at gmail.com (paul.hendrick@gmail.com) Date: Mon, 15 Aug 2005 12:24:25 +0100 Subject: [Tutor] web gallery Message-ID: <1124105065.3884.5.camel@localhost.localdomain> Hi All, I'd like to write some web gallery software from scratch for my girlfriend. I've looked at the PIL (python imaging library) and I'm using it to generate thumbnails from given images. Something else i'd like to get done now though, is building an index of images. Are there any libs suited for this? basically I want an text index of images, which contains the main image name, the thumbnail name, and a description. a new image can be added to the index either by adding it via ftp, or through an html upload form with the comment in the form. So basically, i'm after advice on indexes. thanks for reading, Paul From fatearthling at gmail.com Mon Aug 15 13:32:41 2005 From: fatearthling at gmail.com (Howard Kao) Date: Mon, 15 Aug 2005 19:32:41 +0800 Subject: [Tutor] Would like some help Message-ID: ----Directly Quoted From the Python Cookbook---- 1.3 Constructing a Dictionary Without Excessive Quoting Credit: Brent Burley 1.3.1 Problem You'd like to construct a dictionary without having to quote the keys. 1.3.2 Solution Once you get into the swing of Python, you may find yourself constructing a lot of dictionaries. However, the standard way, also known as a dictionary display, is just a smidgeon more cluttered than you might like, due to the need to quote the keys. For example: data = { 'red' : 1, 'green' : 2, 'blue' : 3 } When the keys are identifiers, there's a cleaner way: def makedict(**kwargs): return kwargs data = makedict(red=1, green=2, blue=3) You might also choose to forego some simplicity to gain more power. For example: def dodict(*args, **kwds): d = {} for k, v in args: d[k] = v d.update(kwds) return d tada = dodict(*data.items( ), yellow=2, green=4) ----End Quote---- Hi guys, Above is a direct cut & paste from the book (hope I am not violating any thing...). I've read the Python docs and can understand the first def example ok, I suppose. However I would like some detailed explaination about the second example, the dodict one. How exactly does it work? It just puzzles me why this would be more powerful or better, even though I can understand and agree that re-writting programs makes good practice. In fact that's what I am looking for from reading this book. Just hope someone can walk me through this simple code. Thanks for the help. From kent37 at tds.net Mon Aug 15 13:42:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Aug 2005 07:42:14 -0400 Subject: [Tutor] Sorting a list of lists aka nested lists In-Reply-To: <1124061506.42ffd14287caa@www.paradise.net.nz> References: <42FE57EF.3000502@mminternet.com> <073f01c5a0a2$61cb32a0$bea68651@xp> <1124061506.42ffd14287caa@www.paradise.net.nz> Message-ID: <43007F96.3050202@tds.net> jfouhy at paradise.net.nz wrote: > Note that in Python2.4+, you can use key= instead: > > def sortKey(lst): > return lst[2] > Quant.sort(key=sortKey) > > This is more effient than specifying a different comparison function, because > the key function is only called once for each element. And instead of defining your own function you can use itertools.itemgetter() which is intended for this purpose: import itertools Quant.sort(key=itertools.itemgetter(2)) Kent From jobauk at hotmail.com Mon Aug 15 14:06:56 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Mon, 15 Aug 2005 12:06:56 +0000 Subject: [Tutor] Event handler for optionmenu In-Reply-To: <4300634A.6050900@post.cz> Message-ID: Hi, Thanks for your reply. It wasn't lazyness, believe me, I did look around for solutions and found something similar to yours here: http://www.astro.washington.edu/owen/TkinterSummary.html#TracingVariables The problem is that I have a class and it wants the callback function to be a global name (I also can't figure out hot to pass parameters to it) By being a global name I can't access the var with widget.getvar(), and it complains if I use root by saying: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Workplace\python\piim\Tkclient.py", line 312, in doLangChoices varValue = root.getvar(name) AttributeError: Tkclient instance has no attribute 'getvar' The code on the class follows: class StartWin: def initialize(self): self.startw=Tk(className="Login") self.startw.servlab=Label(self.startw, text="Server:") self.startw.servin=Entry(self.startw, width=15) self.startw.servlab.grid(column=0, row=0) self.startw.servin.grid(column=1, row=0) self.startw.portlab=Label(self.startw, text="Port:") self.startw.portin=Entry(self.startw, width=15) self.startw.portlab.grid(column=0, row=1) self.startw.portin.grid(column=1, row=1) self.startw.nicklab=Label(self.startw, text="Nickname:") self.startw.nickin=Entry(self.startw, width=15) self.startw.nicklab.grid(column=0, row=2) self.startw.nickin.grid(column=1, row=2) self.startw.l1=Label(self.startw, text="Language:") self.startw.l1.grid(column=0, row=3) OPTIONS = ["en","pt","es","it","fr","de"] self.startw.variable = StringVar() self.startw.variable.set(OPTIONS[0]) # default value self.startw.variable.trace('w', doLangChoices) # trace choices self.startw.whis_butt=apply(OptionMenu, (self.startw, self.startw.variable) + tuple(OPTIONS)) self.startw.whis_butt.grid(column=1, row=3) self.startw.login_butt=Button(self.startw, text="Login", command=self.login) self.startw.login_butt.grid(column=0, row=4) self.startw.exit_butt=Button(self.startw, text="Exit", command=self.exit) self.startw.exit_butt.grid(column=1, row=4) self.startw.mainloop() #connect client with inserted data def login(self): start_client(self.startw.servin.get(), int(self.startw.portin.get()), self.startw.nickin.get(), self.startw.variable.get()) def exit(self): self.startw.quit() self.startw.destroy() #sys.exit() def doLangChoices(name, index, mode): print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode) # HOW TO ACCESS THE VAR VALUE HERE?? #varValue = root.getvar(name) #print varValue print "Client Started" try: conn=StartWin() conn.initialize() root=Tkclient() thread.start_new_thread(listen_server, (client, root)) root.startWindow() except Exception: print "Client thread aborted" >From: geon >To: Jorge Louis De Castro >CC: tutor at python.org >Subject: Re: [Tutor] Event handler for optionmenu >Date: Mon, 15 Aug 2005 11:41:30 +0200 > >Jorge Louis De Castro napsal(a): > >>Hi, >> I have an optionmenu widget that works just fine except that can't find >>docs to get hold of events as they happen, kinda like the command=XYZ of >>other widgets like buttons. >> The code I'm using for the option menu is the following: >> OPTIONS = ["en","pt","es","it","fr","de"] >>self.startw.variable = StringVar() >>self.startw.variable.set(OPTIONS[0]) # default value >>self.startw.whis_butt=apply(OptionMenu, (self.startw, >>self.startw.variable) + tuple(OPTIONS)) >>self.startw.whis_butt.grid(column=1, row=3) >> Now I'd like to have a function like: >> def onChange(self): >> # do optionmenu specific stuff >> but can't find how to do it, how to associate/bind onChange with the >>optionmenu widget. >>Any help will be highly appreciated. >> > >This art is called Trace Variable and could be used like this (copied and >rearranged from one of the prevously posted message from here): > >from Tkinter import * > >OPTIONS = [ > "egg", > "bunny", > "chicken" >] > >def callbackFunc(name, index, mode): > #print "callback called with name=%r, index=%r, mode=%r" % (name, index, >mode) > varValue = root.getvar(name) > print varValue > # modify the value, just to show it can be done > #root.setvar(name, varValue) > >root = Tk() >var = StringVar() >var.set(OPTIONS[2]) # default value >rememberMe = var.trace_variable('w', callbackFunc) # var.trace('w', >callbackFunc) # this works, too > > > >w = OptionMenu (root, var, *OPTIONS) >w.pack() > > >root.mainloop() > >Hope its what you asked for :-) > >-- >geon From geon at post.cz Mon Aug 15 14:24:54 2005 From: geon at post.cz (geon) Date: Mon, 15 Aug 2005 14:24:54 +0200 Subject: [Tutor] Event handler for optionmenu In-Reply-To: References: Message-ID: <43008996.5010505@post.cz> Jorge Louis de Castro napsal(a): >Hi, > >Thanks for your reply. It wasn't lazyness, believe me, I did look around for >solutions and found something similar to yours here: > >http://www.astro.washington.edu/owen/TkinterSummary.html#TracingVariables > >The problem is that I have a class and it wants the callback function to be >a global name (I also can't figure out hot to pass parameters to it) > >By being a global name I can't access the var with widget.getvar(), and it >complains if I use root by saying: > >Exception in Tkinter callback >Traceback (most recent call last): > File "C:\Python24\Lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "C:\Workplace\python\piim\Tkclient.py", line 312, in doLangChoices > varValue = root.getvar(name) >AttributeError: Tkclient instance has no attribute 'getvar' > > > > Not sure what Tkclient() is... seems to be not child od Tk(), cause there is no getvar() function... Anyway I am not able to run your script cause you used there both tabs and spaces for indentation. (see the row OPTIONS = ["en","pt","es","it","fr","de"], how much it is intended....) Shoudnt be there varValue = self.startw.getvar(name)? - just guessing - I can not check cause the indentation i scorrupted ;-) geon From rabidpoobear at gmail.com Mon Aug 15 17:27:32 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 15 Aug 2005 10:27:32 -0500 Subject: [Tutor] Would like some help References: Message-ID: <003901c5a1ad$dd1963d0$aa0ca8c0@luke> Howard, I believe what's happening in the second example is that you can combine dictionaries. ... >>>d2 = {'hello':1,'hi':2} >>>print d2.items() [('hi',2),('hello',1)] so in the second example you can just pass it a list of elements (.items()) and it will concatenate (append?) these to the new dictionary. hope that helps. Luke ----- Original Message ----- From: "Howard Kao" To: Sent: Monday, August 15, 2005 6:32 AM Subject: [Tutor] Would like some help > ----Directly Quoted From the Python Cookbook---- > 1.3 Constructing a Dictionary Without Excessive Quoting > Credit: Brent Burley > > 1.3.1 Problem > You'd like to construct a dictionary without having to quote the keys. > > 1.3.2 Solution > Once you get into the swing of Python, you may find yourself > constructing a lot of dictionaries. However, the standard way, also > known as a dictionary display, is just a smidgeon more cluttered than > you might like, due to the need to quote the keys. For example: > > data = { 'red' : 1, 'green' : 2, 'blue' : 3 } > When the keys are identifiers, there's a cleaner way: > > def makedict(**kwargs): > return kwargs > data = makedict(red=1, green=2, blue=3) > You might also choose to forego some simplicity to gain more power. > For example: > > def dodict(*args, **kwds): > d = {} > for k, v in args: d[k] = v > d.update(kwds) > return d > tada = dodict(*data.items( ), yellow=2, green=4) > ----End Quote---- > > Hi guys, > Above is a direct cut & paste from the book (hope I am not violating > any thing...). I've read the Python docs and can understand the first > def example ok, I suppose. However I would like some detailed > explaination about the second example, the dodict one. How exactly > does it work? It just puzzles me why this would be more powerful or > better, even though I can understand and agree that re-writting > programs makes good practice. In fact that's what I am looking for > from reading this book. Just hope someone can walk me through this > simple code. Thanks for the help. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ebtmike at gmail.com Mon Aug 15 17:52:59 2005 From: ebtmike at gmail.com (Michael Murphy) Date: Mon, 15 Aug 2005 11:52:59 -0400 Subject: [Tutor] LiveWires problems Message-ID: <9225819e05081508526cc0108e@mail.gmail.com> Hi all I'm having problems with installing LiveWire for python for Linux (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. Heres the results: running install running build running build_py running install_lib creating /usr/lib/python2.3/site-packages/livewires error: could not create '/usr/lib/python2.3/site-packages/livewires': Permission denied I'm new at this but I'm sure this is an easy fix but I can't figure it out, any help is appreciated. -- Mike Erie Freeze will rise again! From kent37 at tds.net Mon Aug 15 19:00:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Aug 2005 13:00:38 -0400 Subject: [Tutor] Would like some help In-Reply-To: References: Message-ID: <4300CA36.1070608@tds.net> Howard Kao wrote: > ----Directly Quoted From the Python Cookbook---- > Once you get into the swing of Python, you may find yourself > constructing a lot of dictionaries. However, the standard way, also > known as a dictionary display, is just a smidgeon more cluttered than > you might like, due to the need to quote the keys. For example: > > data = { 'red' : 1, 'green' : 2, 'blue' : 3 } > When the keys are identifiers, there's a cleaner way: > > def makedict(**kwargs): > return kwargs > data = makedict(red=1, green=2, blue=3) This recipe is obsolete; since Python 2.3 (at least) you can pass keyword args directly to the dict() constructor: data = dict(red=1, green=2, blue=3) > You might also choose to forego some simplicity to gain more power. > For example: > > def dodict(*args, **kwds): > d = {} > for k, v in args: d[k] = v > d.update(kwds) > return d > tada = dodict(*data.items( ), yellow=2, green=4) This can now be written as tada = dict(data, yellow=2, green=4) Kent From zamb at saudi.net.sa Mon Aug 15 19:12:47 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Mon, 15 Aug 2005 20:12:47 +0300 Subject: [Tutor] LiveWires problems In-Reply-To: <9225819e05081508526cc0108e@mail.gmail.com> References: <9225819e05081508526cc0108e@mail.gmail.com> Message-ID: <1124125967.25706.7.camel@localhost.localdomain> On Mon, 2005-08-15 at 11:52 -0400, Michael Murphy wrote: > Hi all > > I'm having problems with installing LiveWire for python for Linux > (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. > Heres the results: > > running install > running build > running build_py > running install_lib > creating /usr/lib/python2.3/site-packages/livewires > error: could not create '/usr/lib/python2.3/site-packages/livewires': > Permission denied > > I'm new at this but I'm sure this is an easy fix but I can't figure it > out, any help is appreciated. Most likely you need "root" privileges to change anything under "/usr". If you trust the code, try running it again as "root" (also known as "super-user"). Only do that if you're certain that the code is clean (i.e. no viruses, trojans, spyware and/or worms)! (Sorry, I don't know anything about Linspire, or else I would guide you step by step on how to do that!. In general, try "sudo" with your own password, or "su" with root's password.) Ziyad. From falcon3166 at hotmail.com Mon Aug 15 19:40:30 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 15 Aug 2005 11:40:30 -0600 Subject: [Tutor] How can I make this run right? References: <086501c5a172$8187c6f0$bea68651@xp> Message-ID: I put in a 4 and expected 24, and instead got 12. It is supposed to give 4! not 4*3. --------------------------------------------------------------- Early to bed, Early to rise, Makes a man healthy, wealthy, and wise. --Benjamin Franklin ------------------------------------------------------------------- ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; "Tutor mailing list" Sent: Monday, August 15, 2005 2:20 AM Subject: Re: [Tutor] How can I make this run right? >> The following code is supposed to take in a number, and print number!: >> n = int(raw_input("Number: ")) >> x = n-1 >> while 1: >> t = n*x >> while x > 1: >> x -= 1 >> else: >> break >> print t >> >> Why isn't it working, and how can I make it print out the correct output? > > So give is a clue! What is it doing wrong? Is there an error message? > What output did you expect? What did you get? > > Without that information we have to read the code and guess what you > were trying to do. Then try to guess what might be different to what > you expected. > > Alan G. > From rabidpoobear at gmail.com Mon Aug 15 19:59:38 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 15 Aug 2005 12:59:38 -0500 Subject: [Tutor] How can I make this run right? References: <086501c5a172$8187c6f0$bea68651@xp> Message-ID: <001401c5a1c3$22518670$aa0ca8c0@luke> > I put in a 4 and expected 24, and instead got 12. It is supposed to give 4! > not 4*3. [snip rest of message] nathan your problem is easy to see... > >> n = int(raw_input("Number: ")) > >> x = n-1 > >> while 1: > >> t = n*x > >> while x > 1: > >> x -= 1 > >> else: > >> break > >> print t think about it for a *while*... Hint *while* hint hint *change the while* hint hint hint *the inner while* nathan I see that you want to do n!(factorial) but when you explained it you just said you wanted number! which is confusing because I think everyone thought you were just excited. you could always use a recursive function for factorial, IE. def factorial(n): if n > 1: return factorial(n-1) * n else: return n HTH, Luke P.S. Try to fix yours it'll help you. tell me if you get it working correctly. From geon at post.cz Mon Aug 15 20:22:02 2005 From: geon at post.cz (geon) Date: Mon, 15 Aug 2005 20:22:02 +0200 Subject: [Tutor] How can I make this run right? In-Reply-To: References: <086501c5a172$8187c6f0$bea68651@xp> Message-ID: <4300DD4A.4080505@post.cz> Nathan Pinno napsal(a): >I put in a 4 and expected 24, and instead got 12. It is supposed to give 4! >not 4*3. >--------------------------------------------------------------- > > Dear Nathan, Everyone is giving you very good hints but seems to me you keep to resist :-) Looks like you always wait for complete solution, dont you? Here it is. There is one add and two changes. Can you see them? n = int(raw_input("Number: ")) x = n-1 t=n while 1: t = t*x if x > 1: x -= 1 else: break print t Its not the best solution for number!, but it is yours (and a bit of mine :-) ) -- geon From tegmine at gmail.com Mon Aug 15 20:45:28 2005 From: tegmine at gmail.com (Luis N) Date: Mon, 15 Aug 2005 11:45:28 -0700 Subject: [Tutor] web gallery In-Reply-To: <1124105065.3884.5.camel@localhost.localdomain> References: <1124105065.3884.5.camel@localhost.localdomain> Message-ID: <77bfa81a050815114570f23f08@mail.gmail.com> On 8/15/05, paul.hendrick at gmail.com wrote: > Hi All, > > I'd like to write some web gallery software from scratch for my girlfriend. I've looked at the > PIL (python imaging library) and I'm using it to generate thumbnails from given images. > Something else i'd like to get done now though, is building an index of images. > > Are there any libs suited for this? basically I want an text index of images, which > contains the main image name, the thumbnail name, and a description. a new image can > be added to the index either by adding it via ftp, or through an html upload form with the > comment in the form. > > So basically, i'm after advice on indexes. > > thanks for reading, > Paul > You may find this useful: http://freshmeat.net/projects/python-exif/ I think you need to write a script, cgi or otherwise, which will read a particular directory to create your index, including: imagedir = 'path' import os for item in os.listdir(imagedir): #grab some info about the image. Luis. From tegmine at gmail.com Mon Aug 15 20:47:51 2005 From: tegmine at gmail.com (Luis N) Date: Mon, 15 Aug 2005 11:47:51 -0700 Subject: [Tutor] Python hosting again In-Reply-To: References: Message-ID: <77bfa81a050815114768febb01@mail.gmail.com> On 8/11/05, Jorge Louis De Castro wrote: > Hello, > > I'm interested in writing with my own Python implementation of a Jabber IM > server and client. > Anyone knows where I could host my Python Jabber IM server for a reasonable > monlthy fee? It doesn't need to be a top-notch place since my goal is to > test something else, not the scalability of the application. > > chrs > j. I think you will find http://hub.org to be an excellent host. You get a VPS for about $12/month They are the host of the http://postgresql.org project Luis. From tegmine at gmail.com Mon Aug 15 21:04:23 2005 From: tegmine at gmail.com (Luis N) Date: Mon, 15 Aug 2005 12:04:23 -0700 Subject: [Tutor] Replacement for 'Find' Module In-Reply-To: <667ca7b6050815004618b1f754@mail.gmail.com> References: <66926144050815003663d54fa1@mail.gmail.com> <667ca7b6050815004618b1f754@mail.gmail.com> Message-ID: <77bfa81a05081512042b86cb87@mail.gmail.com> On 8/15/05, Simon Gerber wrote: > You could probably do something like this... (Note: This example is > for Linux - but you can adapt it fairly easily to Windows.) > > > # E.g. Find every .inf file on a CD-ROM. > path = '/cdrom' > # 'E:\\' or whatever for Windows.... > inf_list = [] > for root, dirs, files in os.walk(path): > for current_file in files: > if '.inf' in current_file: if current_file.endswith('.inf'): #or current_file[:-4] might be more appropriate, just my 2c I wrote this in a script for limited globbing: if cd: toss = os.path.join(trashcan, os.path.split(i)[1]) pwd = os.getcwd() else: toss = os.path.join(trashcan, i) if toss[-1] == '*': crumple = [] if cd: l = os.listdir(cd) for i in l: crumple.append(os.path.join(cd, i)) else: crumple = os.listdir('.') for i in crumple: if i.startswith(toss[:-1]): junk.append(i) From alan.gauld at freenet.co.uk Mon Aug 15 22:27:51 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 15 Aug 2005 21:27:51 +0100 Subject: [Tutor] How can I make this run right? References: <086501c5a172$8187c6f0$bea68651@xp> Message-ID: <08e401c5a1d7$d3fcae40$bea68651@xp> >I put in a 4 and expected 24, and instead got 12. It is supposed to >give 4! > not 4*3. Thanks Nathan. It would be good to get that kind of detail when you post the initial message. Your function didn't look like the usual factorial function. FWIW here is my version :-) def factorial(n): result = 1 for x in range(2,n+1): result *= x return result By avoiding while loops you avoid all the mess of trying to maintain the counter - one of the most common causes of errors in programming! For a different approach see the recursion topic in my tutor. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From denise.hartley at gmail.com Tue Aug 16 02:49:55 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 15 Aug 2005 17:49:55 -0700 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quick questions Message-ID: <8daabe5605081517494dcd56a1@mail.gmail.com> Hello guys! Is there a way to convert a file from plaintext(Ascii) to unicode? I have found all my notes about moving between hex., int's, chr's, ord's, etc, but all of these things were only riddle exercises to me and I have a hard time keeping them straight. I'm pretty sure I knew the answer to this and now cannot find it anywhere (even googling through my old tutor posts!) Does anyone have a quick answer/pointer? Thanks so much! ~Denise From rabidpoobear at gmail.com Tue Aug 16 02:57:28 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 15 Aug 2005 19:57:28 -0500 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions References: <8daabe5605081517494dcd56a1@mail.gmail.com> Message-ID: <000e01c5a1fd$7a37eb10$aa0ca8c0@luke> um... >>> help(unicode) Help on class unicode in module __builtin__: [snip help stuff] | encode(...) | S.encode([encoding[,errors]]) -> string or unicode | | Encodes S using the codec registered for encoding. encoding defaults | to the default encoding. errors may be given to set a different error | handling scheme. Default is 'strict' meaning that encoding errors raise | a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and | 'xmlcharrefreplace' as well as any other name registered with | codecs.register_error that can handle UnicodeEncodeErrors. [snip rest of help] Denise, I dont know much about Unicode but it seems like f = file(filename, "r") text = f.readlines() text = text.encode() #or maybe just text.encode()? f.close() should encode the filetext to unicode. then you could do a f = file(filename, "w") f.writelines(text) f.close() sorry I don't know more about it but I hope that helps you. -Luke ----- Original Message ----- From: "D. Hartley" To: "Python tutor" Sent: Monday, August 15, 2005 7:49 PM Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions > Hello guys! > > Is there a way to convert a file from plaintext(Ascii) to unicode? I > have found all my notes about moving between hex., int's, chr's, > ord's, etc, but all of these things were only riddle exercises to me > and I have a hard time keeping them straight. I'm pretty sure I knew > the answer to this and now cannot find it anywhere (even googling > through my old tutor posts!) > > Does anyone have a quick answer/pointer? > > Thanks so much! > > ~Denise > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fatearthling at gmail.com Tue Aug 16 03:40:00 2005 From: fatearthling at gmail.com (Howard Kao) Date: Tue, 16 Aug 2005 09:40:00 +0800 Subject: [Tutor] Would like some help Message-ID: Thanks for the help Luke and Kent. From rabidpoobear at gmail.com Tue Aug 16 03:51:02 2005 From: rabidpoobear at gmail.com (luke) Date: Mon, 15 Aug 2005 20:51:02 -0500 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions References: <8daabe5605081517494dcd56a1@mail.gmail.com> <000e01c5a1fd$7a37eb10$aa0ca8c0@luke> <8daabe560508151837660c63d1@mail.gmail.com> Message-ID: <002101c5a204$f6d7bdb0$aa0ca8c0@luke> List: I'm forwarding this private message(hope you don't mind Denise) I personally have no idea what to do, but someone else might be able to help. -Luke ----- Forwarded Message ----- text is a list, so you can't encode it. but you can iterate over each of the elements and encode them. I have tried several variations of that, but keep ending up with all my newlines being little boxes. any ideas? Thanks, Denise On 8/15/05, luke wrote: > um... > >>> help(unicode) > Help on class unicode in module __builtin__: > [snip help stuff] > | encode(...) > | S.encode([encoding[,errors]]) -> string or unicode > | > | Encodes S using the codec registered for encoding. encoding defaults > | to the default encoding. errors may be given to set a different > error > | handling scheme. Default is 'strict' meaning that encoding errors > raise > | a UnicodeEncodeError. Other possible values are 'ignore', 'replace' > and > | 'xmlcharrefreplace' as well as any other name registered with > | codecs.register_error that can handle UnicodeEncodeErrors. > > [snip rest of help] > > Denise, > I dont know much about Unicode but it seems like > f = file(filename, "r") > text = f.readlines() > text = text.encode() > #or maybe just text.encode()? > f.close() > > should encode the filetext to unicode. > then you could do a > f = file(filename, "w") > f.writelines(text) > f.close() > > sorry I don't know more about it but I hope that helps you. > -Luke > ----- Original Message ----- > From: "D. Hartley" > To: "Python tutor" > Sent: Monday, August 15, 2005 7:49 PM > Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very > quickquestions > > > > Hello guys! > > > > Is there a way to convert a file from plaintext(Ascii) to unicode? I > > have found all my notes about moving between hex., int's, chr's, > > ord's, etc, but all of these things were only riddle exercises to me > > and I have a hard time keeping them straight. I'm pretty sure I knew > > the answer to this and now cannot find it anywhere (even googling > > through my old tutor posts!) > > > > Does anyone have a quick answer/pointer? > > > > Thanks so much! > > > > ~Denise > > _______________________________________________ > > 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 bgailer at alum.rpi.edu Tue Aug 16 03:54:55 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 15 Aug 2005 19:54:55 -0600 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quick questions In-Reply-To: <8daabe5605081517494dcd56a1@mail.gmail.com> References: <8daabe5605081517494dcd56a1@mail.gmail.com> Message-ID: <6.1.2.0.0.20050815195242.02ef0b98@mail.mric.net> At 06:49 PM 8/15/2005, D. Hartley wrote: >Hello guys! > >Is there a way to convert a file from plaintext(Ascii) to unicode? I >have found all my notes about moving between hex., int's, chr's, >ord's, etc, but all of these things were only riddle exercises to me >and I have a hard time keeping them straight. I'm pretty sure I knew >the answer to this and now cannot find it anywhere (even googling >through my old tutor posts!) > >Does anyone have a quick answer/pointer? Try the unicode() built-in function. Read the file into a variable, apply the unicode() function, write the result. Bob Gailer 303 442 2625 home 720 938 2625 cell From danf_1979 at yahoo.es Tue Aug 16 04:20:42 2005 From: danf_1979 at yahoo.es (_ Dan _) Date: Tue, 16 Aug 2005 04:20:42 +0200 (CEST) Subject: [Tutor] From file2.py append an item to file1.py combobox In-Reply-To: Message-ID: <20050816022042.46125.qmail@web25210.mail.ukl.yahoo.com> Hi to all: How can I append some data from file1.py to a combobox on file2.py? I know, if you want to append data to a combobox inside the same script, I would be like follows: # file1.py import wx class Myframe(wx.Frame): def __init__(self, *args, **kwds): ... self.mycombobox = wx.Combobox(... ... # and then... self.mycombobox.Append("Item") # would append to the combobox a new item. # file2.py # So here are my problems... # I got: import wx,file1 class Subframe(wx.Frame): def __init__(self, *args, **kwds) ... def Mymethod(self,event): file1.Myframe.mycombobox.Append("Item") # and it doesnt work... # file1.Myframe.self.mycombobox.Append("item") # does not work either.. What can I do? thanks in advance Daniel. ______________________________________________ Renovamos el Correo Yahoo! Nuevos servicios, m?s seguridad http://correo.yahoo.es From kent37 at tds.net Tue Aug 16 04:51:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Aug 2005 22:51:20 -0400 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions In-Reply-To: <002101c5a204$f6d7bdb0$aa0ca8c0@luke> References: <8daabe5605081517494dcd56a1@mail.gmail.com> <000e01c5a1fd$7a37eb10$aa0ca8c0@luke> <8daabe560508151837660c63d1@mail.gmail.com> <002101c5a204$f6d7bdb0$aa0ca8c0@luke> Message-ID: <430154A8.7010708@tds.net> I think Luke's suggestion will work if you use f.read() (to read the whole file as a single string) instead of f.readlines() and f.write() instead of writelines(). Kent luke wrote: > List: > I'm forwarding this private message(hope you don't mind Denise) > I personally have no idea what to do, but > someone else might be able to help. > -Luke > > > ----- Forwarded Message ----- > > text is a list, so you can't encode it. but you can iterate over each > of the elements and encode them. I have tried several variations of > that, but keep ending up with all my newlines being little boxes. any > ideas? > > Thanks, > Denise > > On 8/15/05, luke wrote: >>I dont know much about Unicode but it seems like >>f = file(filename, "r") >>text = f.readlines() >>text = text.encode() >>#or maybe just text.encode()? >>f.close() >> >>should encode the filetext to unicode. >>then you could do a >>f = file(filename, "w") >>f.writelines(text) >>f.close() From python-tutor at richip.dhs.org Tue Aug 16 09:18:20 2005 From: python-tutor at richip.dhs.org (Richi) Date: Tue, 16 Aug 2005 01:18:20 -0600 Subject: [Tutor] IOError with fcntl.ioctl Message-ID: <4301933C.9040005@richip.dhs.org> Hi, I'm trying to get the number of bytes available on an open serial device (on Linux). I try the following commands: >>> import os >>> import fcntl >>> import termios >>> fd = os.open ("/dev/ttyS0", os.O_RDWR) >>> fcntl.ioctl (fd, termios.TIOCINQ) and after the last line I get the following error: Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 14] Bad address I've tried fcntl.ioctl (fd, termios.FIONREAD) (which is supposed to do the same thing, I think), and I still get the previous error. In fact, any ioctl() command I give to that file descriptor gives that result. I'd appreciate any help in getting this to work. -- Richi From tegmine at gmail.com Tue Aug 16 10:55:01 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 16 Aug 2005 01:55:01 -0700 Subject: [Tutor] LiveWires problems In-Reply-To: <1124125967.25706.7.camel@localhost.localdomain> References: <9225819e05081508526cc0108e@mail.gmail.com> <1124125967.25706.7.camel@localhost.localdomain> Message-ID: <77bfa81a050816015558b02d48@mail.gmail.com> On 8/15/05, ZIYAD A. M. AL-BATLY wrote: > On Mon, 2005-08-15 at 11:52 -0400, Michael Murphy wrote: > > Hi all > > > > I'm having problems with installing LiveWire for python for Linux > > (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. > > Heres the results: > > > > running install > > running build > > running build_py > > running install_lib > > creating /usr/lib/python2.3/site-packages/livewires > > error: could not create '/usr/lib/python2.3/site-packages/livewires': > > Permission denied > > > > I'm new at this but I'm sure this is an easy fix but I can't figure it > > out, any help is appreciated. Consider typing: python setup.py install home=$HOME instead of, python setup.py install You will then install into ~/lib/python2.3/livewires if this location is acceptable to livewires. Luis. From duncan at thermal.esa.int Tue Aug 16 11:18:51 2005 From: duncan at thermal.esa.int (Duncan Gibson) Date: Tue, 16 Aug 2005 11:18:51 +0200 Subject: [Tutor] deriving class from file to handle input line numbers? Message-ID: <20050816091851.6FA9E2332@zeeman.thermal.esa.int> I was sure that this must be a frequently asked [homework?] question, but trying to search for 'file open line number' didn't throw up the sort of answers I was looking for, so here goes... I regularly write parsers for simple input files, and I need to give helpful error messages if the input is invalid. The three most helpful pieces on information are file name, line number and line content. Of course I can use a global variable to track how many times f.readline() is called, but I was wondering whether there is a more OO or Python way of encapsulating this within a class derived from file. What I have below is the minimal interface that I could come up with, but it is a file adaptor rather than a derived class, and it doesn't seem quite clean to me, because I have to open the file externally and then pass the file object into the constructor. Is there a better way of doing it, or am I chasing rainbows? Cheers Duncan class LineCountedInputFile(object): """ add input line count to minimal input File interface The file must be opened externally, and then passed into the constructor. All access should occur through the readLine method, and not using normal File methods on the external file variable, otherwise things will get out of sync and strange things could happen, including incorrect line number. """ __slots__ = ( '_inputFile', '_lineNumber') def __init__(self, inputFile): """ create a LineCountedInputFile adaptor object :param inputFile: existing File object already open for reading only :type inputFile: `File` """ assert isinstance(inputFile, file) assert not inputFile.closed and inputFile.mode == 'r' self._inputFile = inputFile self._lineNumber = 0 #---------------------------------------------------------------------- def readLine(self): """ call file.readline(), strip excess whitespace, increment line number :return: next line of text from file minus excess whitespace, or None at end-of-file :rtype: str """ line = self._inputFile.readline() if len(line) == 0: return None self._lineNumber += 1 return line.strip() #---------------------------------------------------------------------- def _get_fileName(self): return self._inputFile.name fileName = property(_get_fileName, None, None, """(read-only)""") #---------------------------------------------------------------------- def _get_lineNumber(self): return self._lineNumber lineNumber = property(_get_lineNumber, None, None, """(read-only)""") From ml.cyresse at gmail.com Tue Aug 16 12:41:58 2005 From: ml.cyresse at gmail.com (mailing list) Date: Tue, 16 Aug 2005 22:41:58 +1200 Subject: [Tutor] Silly loop question Message-ID: Hi all, I should know this, but it seems to elude me at present. I have a loop which is looping through a line of chars by index. So, one of these - for i in range(len(line)): Now, question is, is there a simple way to 'fast forward' index i? At the moment, I'm doing it like this - changeIndex = None al = len(line) for i in range(al): if changeIndex and (i < changeIndex): continue if line[i] == "{": nextRightBracket = line.find("}",i) #other stuff happens changeIndex = nextRightBracket + 1 As I said, pretty dumb question, so somewhat expecting to be told to read Alan's tutorial again. *grin* Regards, Liam Clarke From kent37 at tds.net Tue Aug 16 12:56:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Aug 2005 06:56:47 -0400 Subject: [Tutor] deriving class from file to handle input line numbers? In-Reply-To: <20050816091851.6FA9E2332@zeeman.thermal.esa.int> References: <20050816091851.6FA9E2332@zeeman.thermal.esa.int> Message-ID: <4301C66F.8090504@tds.net> Duncan Gibson wrote: > I was sure that this must be a frequently asked [homework?] question, > but trying to search for 'file open line number' didn't throw up the > sort of answers I was looking for, so here goes... > > I regularly write parsers for simple input files, and I need to give > helpful error messages if the input is invalid. The three most helpful > pieces on information are file name, line number and line content. Of > course I can use a global variable to track how many times f.readline() > is called, but I was wondering whether there is a more OO or Python > way of encapsulating this within a class derived from file. If you just want to keep track of line numbers as you read the file by lines, you could use enumerate(): f = open('myfile.txt') for line_number, line in enumerate(f): ... For any iterable object, enumerate() returns a sequence of (index, value) for each value in the object. Your class has the advantage of maintaining the line number internally and customizing readline() to your needs. More comments inline. Kent > What I have below is the minimal interface that I could come up with, > but it is a file adaptor rather than a derived class, and it doesn't > seem quite clean to me, because I have to open the file externally > and then pass the file object into the constructor. Why? You should be able to open the file in the constuctor and provide close() and __del__() methods to close the file. What problem did you have when deriving from file? > class LineCountedInputFile(object): > """ > add input line count to minimal input File interface > > The file must be opened externally, and then passed into the > constructor. All access should occur through the readLine method, > and not using normal File methods on the external file variable, > otherwise things will get out of sync and strange things could > happen, including incorrect line number. > """ > > __slots__ = ( > '_inputFile', > '_lineNumber') __slots__ is overkill, it is intended as a way to save memory in classes that will have many instances, and discouraged otherwise. > > def __init__(self, inputFile): > """ > create a LineCountedInputFile adaptor object > > :param inputFile: existing File object already open for reading only > :type inputFile: `File` > """ > > assert isinstance(inputFile, file) > assert not inputFile.closed and inputFile.mode == 'r' > > self._inputFile = inputFile > self._lineNumber = 0 > > #---------------------------------------------------------------------- > > def readLine(self): I would call this method readline() to match what file does. > """ > call file.readline(), strip excess whitespace, increment line number > > :return: next line of text from file minus excess whitespace, or > None at end-of-file > :rtype: str > """ > > line = self._inputFile.readline() > if len(line) == 0: > return None > self._lineNumber += 1 > return line.strip() > > #---------------------------------------------------------------------- > > def _get_fileName(self): > return self._inputFile.name > > fileName = property(_get_fileName, None, None, """(read-only)""") Maybe just call this property 'name' to match what file does. > #---------------------------------------------------------------------- > > def _get_lineNumber(self): > return self._lineNumber > > lineNumber = property(_get_lineNumber, None, None, """(read-only)""") The use of properties to make read-only attributes might be overkill also. I would just have a lineNumber attribute but that is more of a judgement call. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From klappnase at freenet.de Tue Aug 16 13:13:34 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 16 Aug 2005 13:13:34 +0200 Subject: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions In-Reply-To: <430154A8.7010708@tds.net> References: <8daabe5605081517494dcd56a1@mail.gmail.com> <000e01c5a1fd$7a37eb10$aa0ca8c0@luke> <8daabe560508151837660c63d1@mail.gmail.com> <002101c5a204$f6d7bdb0$aa0ca8c0@luke> <430154A8.7010708@tds.net> Message-ID: <20050816131334.6def343a.klappnase@freenet.de> On Mon, 15 Aug 2005 22:51:20 -0400 Kent Johnson wrote: > I think Luke's suggestion will work if you use f.read() (to read the whole file as a single string) instead of f.readlines() and f.write() instead of writelines(). > > Kent > And if you want to convert ascii into unicode you need to call * decode() * ( which does pretty much the same as unicode() ) on the string, not encode() . Michael > luke wrote: > > List: > > I'm forwarding this private message(hope you don't mind Denise) > > I personally have no idea what to do, but > > someone else might be able to help. > > -Luke > > > > > > ----- Forwarded Message ----- > > > > text is a list, so you can't encode it. but you can iterate over each > > of the elements and encode them. I have tried several variations of > > that, but keep ending up with all my newlines being little boxes. any > > ideas? > > > > Thanks, > > Denise > > > > On 8/15/05, luke wrote: > >>I dont know much about Unicode but it seems like > >>f = file(filename, "r") > >>text = f.readlines() > >>text = text.encode() > >>#or maybe just text.encode()? > >>f.close() > >> > >>should encode the filetext to unicode. > >>then you could do a > >>f = file(filename, "w") > >>f.writelines(text) > >>f.close() > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Aug 16 13:14:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Aug 2005 07:14:19 -0400 Subject: [Tutor] Silly loop question In-Reply-To: References: Message-ID: <4301CA8B.7090104@tds.net> mailing list wrote: > Hi all, > > I should know this, but it seems to elude me at present. > > I have a loop which is looping through a line of chars by index. > > So, one of these - > > for i in range(len(line)): > > > Now, question is, is there a simple way to 'fast forward' index i? > > At the moment, I'm doing it like this - > > changeIndex = None > al = len(line) > for i in range(al): > > if changeIndex and (i < changeIndex): > continue > > if line[i] == "{": > nextRightBracket = line.find("}",i) > #other stuff happens > changeIndex = nextRightBracket + 1 I would do this with a while loop and an explicit index counter: al = len(line) i = 0 while i < al: if line[i] == "{": nextRightBracket = line.find("}",i) #other stuff happens i = nextRightBracket + 1 else: i += 1 You could also make a custom iterator that you could set but it doesn't seem worth the trouble. If you just had to skip one or two values I would make an explicit iterator and call next() on it, but to advance an arbitrary amount that is awkward. Kent From ebtmike at gmail.com Tue Aug 16 13:25:48 2005 From: ebtmike at gmail.com (Michael Murphy) Date: Tue, 16 Aug 2005 07:25:48 -0400 Subject: [Tutor] LiveWires problems In-Reply-To: <77bfa81a050816015558b02d48@mail.gmail.com> References: <9225819e05081508526cc0108e@mail.gmail.com> <1124125967.25706.7.camel@localhost.localdomain> <77bfa81a050816015558b02d48@mail.gmail.com> Message-ID: <9225819e05081604253485c291@mail.gmail.com> Compiling it in Root worked, thanks. On 8/16/05, Luis N wrote: > On 8/15/05, ZIYAD A. M. AL-BATLY wrote: > > On Mon, 2005-08-15 at 11:52 -0400, Michael Murphy wrote: > > > Hi all > > > > > > I'm having problems with installing LiveWire for python for Linux > > > (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. > > > Heres the results: > > > > > > running install > > > running build > > > running build_py > > > running install_lib > > > creating /usr/lib/python2.3/site-packages/livewires > > > error: could not create '/usr/lib/python2.3/site-packages/livewires': > > > Permission denied > > > > > > I'm new at this but I'm sure this is an easy fix but I can't figure it > > > out, any help is appreciated. > > Consider typing: > > python setup.py install home=$HOME > > instead of, > > python setup.py install > > You will then install into ~/lib/python2.3/livewires if this location > is acceptable to livewires. > > Luis. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Mike Erie Freeze will rise again! From kent37 at tds.net Tue Aug 16 13:43:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Aug 2005 07:43:43 -0400 Subject: [Tutor] Regexp with multiple patterns in Python In-Reply-To: <000101c5a0eb$89060900$6400a8c0@Kristian> References: <000101c5a0eb$89060900$6400a8c0@Kristian> Message-ID: <4301D16F.1080009@tds.net> Kristian Evensen wrote: > What I want to do is to check for two patterns to make sure all > occurrences of pattern1 and pattern2 come in the same order as they do > in the file I parse. It it contains a number of computer-games I would > like the output to look something like this: > > PC, Battlefield, Battlefield2 > > PS2, Battlefield 2: Modern Combat. > > > > The file is constructed somewhat similar to this: > > PC > Battlefield, Battfiled2 > PS2 > Battlefield 2: Modern Combat Are you trying to *check* that the data is in this format, or are you trying to read this format and output a different format? If the data is really this simple you can just iterate over the lines in pairs: f = open('myfile.txt') fi = iter(f) for line in fi: nextline = fi.next() print '%s, %s' % (line.strip(), nextline.strip()) You could add code to the loop to check that the data is in the expected format. > Using the following expression (and re.findall) I get somewhat closer: > > pattern8 = re.compile(r'search.asp\?title=battlefield.*?><.*?>(PCCD|XBOX > 360|XBOX|PLAYSTATION PSP|PLAYSTATION 2) - > TITLE<|game.asp\?id=(\d+).*?><.*?><.*?>(.*?)<') >From this regex it looks like the data is actually in XML. You might want to use an XML parser like ElementTree or BeautifulSoup to parse the file, then extract the data from the resulting tree. If neither of these suggestions helps, please post a sample of your actual data, the actual results you want, and the code you have so far. Kent From duncan at thermal.esa.int Tue Aug 16 14:18:22 2005 From: duncan at thermal.esa.int (Duncan Gibson) Date: Tue, 16 Aug 2005 14:18:22 +0200 Subject: [Tutor] deriving class from file to handle input line numbers? In-Reply-To: <4301C66F.8090504@tds.net> References: <20050816091851.6FA9E2332@zeeman.thermal.esa.int> <4301C66F.8090504@tds.net> Message-ID: <20050816141822.52476632.duncan@thermal.esa.int> Kent Johnson wrote: > If you just want to keep track of line numbers as you read the file by lines, you could use enumerate(): > > f = open('myfile.txt') > for line_number, line in enumerate(f): > ... This is neat, but not all of the parsers work on a 'line by line' basis, so sometimes there are additional calls to f.readline() or equivalent in other places in the code based on what has just been read. > What problem did you have when deriving from file? To be perfectly honest, I didn't try it because even if I had declared class MyFile(file): etc I couldn't see how to have an instance of MyFile returned from the built-in 'open' function. I thought this was the crux of the problem. So what I have done is provide a different interface completely, class MyFile(object): etc I could extend this to take the file name in the constructor, and add a MyFile.open() method, but then I can no longer substitute any MyFile instances in places that expect 'file' instances. Now that I've started to explain all of this to someone else, I'm starting to wonder whether it really matters. Do I really need it to be substitutable for 'file' after all ? I need to sit in a darkened room and think for a while... Cheers Duncan From kent37 at tds.net Tue Aug 16 15:06:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Aug 2005 09:06:10 -0400 Subject: [Tutor] deriving class from file to handle input line numbers? In-Reply-To: <20050816141822.52476632.duncan@thermal.esa.int> References: <20050816091851.6FA9E2332@zeeman.thermal.esa.int> <4301C66F.8090504@tds.net> <20050816141822.52476632.duncan@thermal.esa.int> Message-ID: <4301E4C2.5080708@tds.net> Duncan Gibson wrote: > Kent Johnson wrote: > To be perfectly honest, I didn't try it because even if I had declared > > class MyFile(file): > etc > > I couldn't see how to have an instance of MyFile returned from the > built-in 'open' function. I thought this was the crux of the problem. open() is actually just an alias for file(): >>> open is file True But if you have your own file class then you will call it's constructor rather than open(). Here is a simple example: >>> class MyFile(file): ... def __init__(self, *args, **kwds): ... self.lineNumber = 0 ... super(MyFile, self).__init__(*args, **kwds) ... def readline(self): ... self.lineNumber += 1 ... return super(MyFile, self).readline() ... >>> f=MyFile('build.xml') >>> f.lineNumber 0 >>> f.readline() '\n' >>> f.lineNumber 1 >>> f.readline() '<------ import threading class show_num(threading.Thread): def __init__(self, num): print "__init__: Num = ", num def run(self): print "run" show_num_thread = show_num(742) show_num_thread.start() ---><----- Throws an error >>> __init__: Num = 742 Traceback (most recent call last): File "H:/Docs/PyScripts/test_thread_1.py", line 12, in -toplevel- show_num_thread.start() AssertionError: Thread.__init__() not called >>> Which __init__ method is it referring to? Thanks in advance for your help (and time). U guys are awesome :) -----Original Message----- From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: Thursday, 25 August 2005 12:17 p.m. To: Hans Dushanthakumar Cc: Tutor Subject: Re: [Tutor] Importing modules/classes > class dummy_class: > def __init__(self): > print "__init__" > > def run(self): > print "run" > > > Now, I have another file test_dummy.py, which only has the foll 2 > lines > > import dummy_class > d=dummy_class() Hi Hans, In Python, modules are containers. They can contain possibly more than one thing, so you need to make sure to fully qualify the class: import dummy_class d = dummy_class.dummy_class() Does this make sense? From Hans.Dushanthakumar at navman.com Thu Aug 25 06:28:25 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 25 Aug 2005 16:28:25 +1200 Subject: [Tutor] Differences in running a multithreaded script under IDLE and otherwise Message-ID: <5667508E43F1B740BCFA57FF46E35300016C3892@nav_akl_exch_c.newton.navman.com> Hi, While running the foll script by double-clicking it (under WinXP), it runs as expected. However, when I run it via IDLE, it hangs after a few secs (no runtime errors - just hangs). Why does this happen? Cheers Hans import threading class incr_num(threading.Thread): num = '' def __init__(self, local_num): global num threading.Thread.__init__(self) num = local_num print "__init__: ", num def run(self): global num for k in range (20): print "run: ", num num = num + 1 incr_num_thread = incr_num(501) incr_num_thread.start() print "Wait for thread to finish" incr_num_thread.join() print "Thread finished" raw_input("Press enter") From frank.hoffsummer at gmx.de Thu Aug 25 01:34:54 2005 From: frank.hoffsummer at gmx.de (=?ISO-8859-1?Q?Frank_Hoffs=FCmmer?=) Date: Thu, 25 Aug 2005 01:34:54 +0200 Subject: [Tutor] checking substrings in strings In-Reply-To: <6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> References: <430CDED8.6070304@scottoertel.info> <6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> Message-ID: <68A9241E-0168-4F1F-BEB0-951A4CD93972@gmx.de> Hello, I would like to check if a certain word exists in a given string. since I learned to love lists, I used if myword in mystring: ...didnt work. I have now resorted to if mystring.find(myword) >1: is this really the canonical way to check if myword exists in mystring? it feels somewhat "unpythonic", thats why I'm asking thanks for any insight you might have -frank From julielai823 at yahoo.com.hk Thu Aug 25 03:19:48 2005 From: julielai823 at yahoo.com.hk (Julie Lai) Date: Thu, 25 Aug 2005 09:19:48 +0800 (CST) Subject: [Tutor] Handling binary file Message-ID: <20050825011948.58755.qmail@web31210.mail.mud.yahoo.com> I have opened a file in binary mode. The 9th, 10th and 11th bytes contain the time in seconds. In order to get this value in decimal I did the following: timeinsec = bytes[9] * 65536 + bytes[10] * 256 + bytes{11] Would someone please advise if there is a better way to do this? Thanks, Julie. _______________________________________ ·Q§Y®É¦¬¨ì·s email ³qª¾¡H ¤U¸ü Yahoo! Messenger http://messenger.yahoo.com.hk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050825/bd6b38b1/attachment.htm From alan.gauld at freenet.co.uk Thu Aug 25 08:31:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 25 Aug 2005 07:31:21 +0100 Subject: [Tutor] IndexError and appending to lists [Was: Re: Need Helpon Assignment] References: <430BCE0F.1060300@comcast.net> <006001c5a87f$4da85e80$3bc98751@xp> <430D1043.5040801@comcast.net> Message-ID: <00aa01c5a93e$9c62bbf0$3bc98751@xp> > "for" loop as you suggest, the program won't enter the loop unless > "s" is initialized so that it's in "input". How do I do that? for s in input: means that s takes on each value in input. input is your file. Thus s takes on the value of each line in the input file. You don't need to initialise s before entering the loop as you would with a while loop. Similarly you don't need to test for the end of the file, 'for' does all that too. Take a look at the 'Loops' topic and then the 'Handling Files' topic in my tutorial for more info on this. > Also, near the end of your remarks you say that the code at the > bottom of my program doesn't do anything. It does for me. Lets take a look: >>> print N >>> for i in range(N): >>> T[i] <-------- This does nothing >>> print T[i] The line that simply has the value in it will not do anything. It will not print out the value, you need to call print for that to happen. > put in those print statements to verify that the contents of those > variables are what I expected them to be. That's all that mess is > for. The debug/test print statements are fine, I was only pointing out that one line did nothing, not the entire block. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Aug 25 08:38:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 25 Aug 2005 07:38:38 +0100 Subject: [Tutor] Importing modules/classes References: <5667508E43F1B740BCFA57FF46E353000165878F@nav_akl_exch_c.newton.navman.com> Message-ID: <00ce01c5a93f$a0ad8f90$3bc98751@xp> > Am trying to get my head around classes in python. Looks like you have the classes bit figured out! :-) > import dummy_class > d=dummy_class() But you have a problem with namespaces. the class 'dummy_class' is inside the module 'dummy_class' So when you import the module that allows you to use the name 'dummy_class' to refer to the *contents* of that module. To access the class 'dummy_class' you need to prepend it with the name of the module: d = dummy_class.dummy_class() You can get more on this in the 'Whats in a Name?' topic of my tutor. And more on OOP in the OOP topic - naturally! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 25 09:58:05 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2005 08:58:05 +0100 Subject: [Tutor] Importing modules/classes References: <5667508E43F1B740BCFA57FF46E35300016C3658@nav_akl_exch_c.newton.navman.com> Message-ID: > class show_num(threading.Thread): > > def __init__(self, num): > print "__init__: Num = ", num > > show_num_thread = show_num(742) > show_num_thread.start() > > ---><----- > > Throws an error > >>>> > __init__: Num = 742 > > Traceback (most recent call last): > File "H:/Docs/PyScripts/test_thread_1.py", line 12, > in -toplevel- > show_num_thread.start() > AssertionError: Thread.__init__() not called >>>> > > Which __init__ method is it referring to? You need to call the init method of the inherited class(es) from within your init. It's conventional to call the superclass constructor before doing your own initialisation so it should look like: def __init__(self, num): Thread.__init__(self) print "__init__: Num = ", num There is a new technique for doing this in recent Python version (v2.2 onwards?) using the super keyword, but I've still to get my own head around it... :-) By calling the superclass first that means that your init code can safely call features of the superclass, sure that they are going to work OK. HTH, -- Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 25 10:04:48 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2005 09:04:48 +0100 Subject: [Tutor] Handling binary file References: <20050825011948.58755.qmail@web31210.mail.mud.yahoo.com> Message-ID: > I have opened a file in binary mode. > The 9th, 10th and 11th bytes contain the time in seconds. > In order to get this value in decimal I did the following: > > timeinsec = bytes[9] * 65536 + bytes[10] * 256 + bytes{11] > > Would someone please advise if there is a better way to do > this? You could use: timeinsec = bytes[9:12] which gets you the three bytes as a sequence. You should be able to use the struct module to convert that into a number except that struct expects an integer to be 4 bytes so you probably need to add a zero in front. It also depends on issues like big-endian v little endian (ie right or left hand alignment) etc. If your method works I wouldn't worry too much! Alan G From alan.gauld at btinternet.com Thu Aug 25 10:07:13 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2005 09:07:13 +0100 Subject: [Tutor] Differences in running a multithreaded script under IDLEand otherwise References: <5667508E43F1B740BCFA57FF46E35300016C3892@nav_akl_exch_c.newton.navman.com> Message-ID: > While running the foll script by double-clicking it (under > WinXP), it > runs as expected. However, when I run it via IDLE, it hangs > after a few > secs (no runtime errors - just hangs). Why does this happen? My guess is that IDLE is already runnning threads of its own and may not like it when threads start running more threads... But I don't know., I've never used IDLE for any threading, I'm a vim and console man myself! Alan G. From alan.gauld at freenet.co.uk Thu Aug 25 10:27:34 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 25 Aug 2005 09:27:34 +0100 Subject: [Tutor] checking substrings in strings References: <430CDED8.6070304@scottoertel.info><6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> <68A9241E-0168-4F1F-BEB0-951A4CD93972@gmx.de> Message-ID: <013501c5a94e$d844fbf0$3bc98751@xp> > I would like to check if a certain word exists in a given string. > since I learned to love lists, I used > > if myword in mystring: > > ...didnt work. I have now resorted to > Which version of Python? >>> 'boo' in 'mybigbooboo' True >>> Works for me in Python 2.4... Alan G. (Regular readers will note I now have 2.4 installed! :-) From john at fouhy.net Thu Aug 25 10:28:39 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 25 Aug 2005 20:28:39 +1200 Subject: [Tutor] checking substrings in strings In-Reply-To: <68A9241E-0168-4F1F-BEB0-951A4CD93972@gmx.de> References: <430CDED8.6070304@scottoertel.info> <6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> <68A9241E-0168-4F1F-BEB0-951A4CD93972@gmx.de> Message-ID: <5e58f2e405082501283c55d9a4@mail.gmail.com> On 8/25/05, Frank Hoffs?mmer wrote: > Hello, > I would like to check if a certain word exists in a given string. > since I learned to love lists, I used > > if myword in mystring: > > ...didnt work. What version of python are you using? This was introduced in Python 2.3. ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 'bar' in 'foobarbaz' True -- John. From pierre.barbier at cirad.fr Thu Aug 25 10:42:29 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 25 Aug 2005 10:42:29 +0200 Subject: [Tutor] Source PC MAC address In-Reply-To: <1124953419.7065.20.camel@KMA.accesstel> References: <1124880684.9086.7.camel@KMA.accesstel> <430C8B9E.8020505@cirad.fr> <1124953419.7065.20.camel@KMA.accesstel> Message-ID: <430D8475.4050403@cirad.fr> The problem is: you cannot do that using the socket interface as the OS IP stack will drop all the ethernet informations. However, you can ask the network explicitly for the MAC address handling some IP address: the protocol is called ARP (RFC 826). To do so, the Python package dpkt (http://www.monkey.org/~dugsong/dpkt/) might be interesting for you (although I never used it ...) as it includes a module to handle ARP requests. Pierre PS: do not forget to send your answers to Python Tutor also ... BTW, could it be possible de configure the list so that the "reply-to" field is set to the Python Tutor list instead of the sender ? Johan Geldenhuys a ?crit : > Is there a other way of doing this? Getting the MAC. I am on a ethernet > network. > > Johan > > > > > > ------------------------------------------------------------------------ > > Sujet: > Re: [Tutor] Source PC MAC address > Exp?diteur: > Pierre Barbier de Reuille > Date: > Wed, 24 Aug 2005 17:00:46 +0200 > Destinataire: > Python Tutor > > Destinataire: > Python Tutor > > Return-Path: > > Received: > from earth.accesstel.co.za ([unix socket]) by earth (Cyrus v2.1.9) with > LMTP; Wed, 24 Aug 2005 16:59:09 +0200 > X-Sieve: > CMU Sieve 2.2 > Received: > by earth.accesstel.co.za (Postfix, from userid 65534) id F00D011DD9; > Wed, 24 Aug 2005 16:59:08 +0200 (SAST) > Received: > from localhost.localdomain (localhost [127.0.0.1]) by > earth.accesstel.co.za (Postfix) with ESMTP id 11EF911DD9 for > ; Wed, 24 Aug 2005 16:59:08 +0200 (SAST) > Received: > from smtp-vbr1.xs4all.nl (smtp-vbr1.xs4all.nl [194.109.24.21]) by > gateway.azitech.co.za (8.11.6/8.11.6) with ESMTP id j7OEnmr23311 for > ; Wed, 24 Aug 2005 16:49:49 +0200 > Received: > from bag.python.org (bag.python.org [194.109.207.14]) by > smtp-vbr1.xs4all.nl (8.13.3/8.13.3) with ESMTP id j7OEvApb033830; Wed, > 24 Aug 2005 16:57:10 +0200 (CEST) (envelope-from tutor-bounces at python.org) > Received: > from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with > ESMTP id DA7B61E400F; Wed, 24 Aug 2005 16:57:15 +0200 (CEST) > X-Original-To: > tutor at python.org > Received: > from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with > ESMTP id 5382C1E4003 for ; Wed, 24 Aug 2005 16:57:13 > +0200 (CEST) > Received: > from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP; > 24 Aug 2005 16:57:13 +0200 > Received: > from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by > bag.python.org (Postfix) with ESMTP for ; Wed, 24 Aug > 2005 16:57:13 +0200 (CEST) > Received: > from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by > auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsnoG028104 for > ; Wed, 24 Aug 2005 16:54:49 +0200 > Received: > from [195.221.175.162] (barbier at pcps-162.cirad.fr [195.221.175.162]) by > auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsmMS028090 for > ; Wed, 24 Aug 2005 16:54:48 +0200 > ID du Message: > <430C8B9E.8020505 at cirad.fr> > Agent utilisateur: > Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050817 > Thunderbird/1.0.2 Mnenhy/0.7 > X-Accept-Language: > fr, en > Version de MIME: > 1.0 > R?f?rences: > <1124880684.9086.7.camel at KMA.accesstel> > In-Reply-To: > <1124880684.9086.7.camel at KMA.accesstel> > X-Enigmail-Version: > 0.91.0.0 > X-BeenThere: > tutor at python.org > X-Mailman-Version: > 2.1.6 > Precedence: > list > List-Id: > Discussion for learning programming with Python > List-Unsubscribe: > , > > List-Archive: > > List-Post: > > List-Help: > > List-Subscribe: > , > > Content-Type: > text/plain; charset="iso-8859-15" > Exp?diteur: > tutor-bounces at python.org > Errors-To: > tutor-bounces at python.org > X-Virus-Scanned: > by XS4ALL Virus Scanner > X-Accesstel-MailScanner-Information: > Please contact Accesstel for information > X-Accesstel-MailScanner: > Found to be clean > X-MIME-Autoconverted: > from quoted-printable to 8bit by gateway.azitech.co.za id j7OEnmr23311 > X-Fetched: > by SuSE Linux Openexchange Server from > accesstel^johan at mail.accesstel.co.za for johan at accesstel.co.za via pop > X-Spam-Status: > No, hits=-7.6 required=4.8 > tests=AWL,BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES, > REPLY_WITH_QUOTES,SIGNATURE_LONG_SPARSE, USER_AGENT_MOZILLA_UA > autolearn=ham version=2.55 > X-Spam-Checker-Version: > SpamAssassin 2.55 (1.174.2.19-2003-05-19-exp) > Content-Transfer-Encoding: > 8bit > > > Socket is built up on IP, not on Ethernet: you have no way of finding a > MAC address using sockets simply because it may not exist one ! (if > you're not on an Ethernet network) You need to access lower levels of > network and probably access directly the network packet as your network > card is sending it to your OS ! > > Pierre > > Johan Geldenhuys a ?crit : > >>Hi List, >>I am doing some networking programming and would like to limit access to >>my socket server on the the source devices' MAC address. >>I know the IP from where the connection is coming, but how could I find >>out what the MAC of the source device is? >>Any quick answers / ideas? >>Is there a build-in function in socket that can do this? >> >>Thanks, >> >>Johan >> >> >> >> >> >>------------------------------------------------------------------------ >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From johan at accesstel.co.za Thu Aug 25 12:45:29 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 25 Aug 2005 12:45:29 +0200 Subject: [Tutor] Importing modules/classes In-Reply-To: <5667508E43F1B740BCFA57FF46E35300016C3658@nav_akl_exch_c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300016C3658@nav_akl_exch_c.newton.navman.com> Message-ID: <1124966729.7065.45.camel@KMA.accesstel> import threading self.thread = threading.Thread.__init__(self) self.thread.start() Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050825/c976fca0/attachment.htm -------------- next part -------------- An embedded message was scrubbed... From: "Hans Dushanthakumar" Subject: Re: [Tutor] Importing modules/classes Date: Thu, 25 Aug 2005 14:34:25 +1200 Size: 5196 Url: http://mail.python.org/pipermail/tutor/attachments/20050825/c976fca0/attachment.eml From kent37 at tds.net Thu Aug 25 13:22:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Aug 2005 07:22:36 -0400 Subject: [Tutor] Differences in running a multithreaded script under IDLE and otherwise In-Reply-To: <5667508E43F1B740BCFA57FF46E35300016C3892@nav_akl_exch_c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300016C3892@nav_akl_exch_c.newton.navman.com> Message-ID: <430DA9FC.90104@tds.net> Hans Dushanthakumar wrote: > Hi, > While running the foll script by double-clicking it (under WinXP), it > runs as expected. However, when I run it via IDLE, it hangs after a few > secs (no runtime errors - just hangs). Why does this happen? It works for me in IDLE with Python 2.4.1 on Win2k. What version of Python do you have? Do you get any output at all? Kent > > Cheers > Hans > > import threading > > class incr_num(threading.Thread): > num = '' > > def __init__(self, local_num): > global num > threading.Thread.__init__(self) > num = local_num > print "__init__: ", num > > def run(self): > global num > for k in range (20): > print "run: ", num > num = num + 1 > > incr_num_thread = incr_num(501) > incr_num_thread.start() > > print "Wait for thread to finish" > incr_num_thread.join() > print "Thread finished" > > raw_input("Press enter") > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jobauk at hotmail.com Thu Aug 25 14:56:15 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Thu, 25 Aug 2005 12:56:15 +0000 Subject: [Tutor] (no subject) Message-ID: Hi, I think I may have misinterpreted the syntax of cPickle. I have dumped data onto a file using: output = codecs.open(".\\"+self.filename, "ab") cPickle.dump(self.terms, output) cPickle.dump(self.username, output) cPickle.dump(self.age, output) cPickle.dump(self.gender, output) cPickle.dump(self.totalMsgs, output) cPickle.dump(self.occurrences, output) I thought I could unpickle this using the load feature, something like: inFile = codecs.open(".\\"+self.filename, "r") cPickle.load(self.terms, inFile) cPickle.dump(self.username, inFile) cPickle.dump(self.age, inFile) cPickle.dump(self.gender, inFile) cPickle.dump(self.totalMsgs, inFile) cPickle.dump(self.occurrences, inFile) Which would unpickle the data onto the variables. It does not work like that, unfortunately. When I try reading the whole file I only get the first object read as output. Any ideas how to achieve what this? chrs j. From jobauk at hotmail.com Thu Aug 25 15:05:34 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Thu, 25 Aug 2005 13:05:34 +0000 Subject: [Tutor] cPickle usage In-Reply-To: Message-ID: Hi, [Sorry for the repost, there was a typo previously] I think I may have misinterpreted the syntax of cPickle. I have dumped data onto a file using: output = codecs.open(".\\"+self.filename, "ab") cPickle.dump(self.terms, output) cPickle.dump(self.username, output) cPickle.dump(self.age, output) cPickle.dump(self.gender, output) cPickle.dump(self.totalMsgs, output) cPickle.dump(self.occurrences, output) I thought I could unpickle this using the load feature, something like: inFile = codecs.open(".\\"+self.filename, "r") cPickle.load(self.terms, inFile) cPickle.load(self.username, inFile) cPickle.load(self.age, inFile) cPickle.load(self.gender, inFile) cPickle.load(self.totalMsgs, inFile) cPickle.load(self.occurrences, inFile) Which would unpickle the data onto the variables. It does not work like that, unfortunately. When I try reading the whole file I only get the first object read as output. Any ideas how to achieve what this? chrs j. > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From pierre.barbier at cirad.fr Thu Aug 25 15:20:16 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 25 Aug 2005 15:20:16 +0200 Subject: [Tutor] cPickle usage In-Reply-To: References: Message-ID: <430DC590.20301@cirad.fr> Jorge Louis de Castro a ?crit : > Hi, > > [Sorry for the repost, there was a typo previously] > > I think I may have misinterpreted the syntax of cPickle. I have dumped data > onto a file using: > > [...] > > I thought I could unpickle this using the load feature, something like: > inFile = codecs.open(".\\"+self.filename, "r") > cPickle.load(self.terms, inFile) > cPickle.load(self.username, inFile) > cPickle.load(self.age, inFile) > cPickle.load(self.gender, inFile) > cPickle.load(self.totalMsgs, inFile) > cPickle.load(self.occurrences, inFile) self.terms = cPickle.load(inFile) self.username = cPickle.load(inFile) ... should work better :) > > Which would unpickle the data onto the variables. It does not work like > that, unfortunately. When I try reading the whole file I only get the first > object read as output. > Any ideas how to achieve what this? > > chrs > j. > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Thu Aug 25 15:19:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Aug 2005 09:19:51 -0400 Subject: [Tutor] cPickle usage In-Reply-To: References: Message-ID: <430DC577.3070404@tds.net> Jorge Louis de Castro wrote: > Hi, > > [Sorry for the repost, there was a typo previously] > > I think I may have misinterpreted the syntax of cPickle. I have dumped data > onto a file using: > > output = codecs.open(".\\"+self.filename, "ab") Use plain open(), not codecs.open(), as you are not writing encoded character data. Why are you opening for append? Is the data in the file already? Are you skipping over it on the read? Otherwise use "wb" instead of "ab". > cPickle.dump(self.terms, output) > cPickle.dump(self.username, output) > cPickle.dump(self.age, output) > cPickle.dump(self.gender, output) > cPickle.dump(self.totalMsgs, output) > cPickle.dump(self.occurrences, output) > > I thought I could unpickle this using the load feature, something like: > inFile = codecs.open(".\\"+self.filename, "r") Use open() and mode "rb". > cPickle.load(self.terms, inFile) Shoud be self.username = cPickle.load(inFile) etc. I think you will get a TypeError here... Kent > cPickle.load(self.username, inFile) > cPickle.load(self.age, inFile) > cPickle.load(self.gender, inFile) > cPickle.load(self.totalMsgs, inFile) > cPickle.load(self.occurrences, inFile) > > Which would unpickle the data onto the variables. It does not work like > that, unfortunately. When I try reading the whole file I only get the first > object read as output. > Any ideas how to achieve what this? > > chrs > j. > >> >>_______________________________________________ >>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 tlinux at comcast.net Thu Aug 25 15:47:35 2005 From: tlinux at comcast.net (Tom Strickland) Date: Thu, 25 Aug 2005 08:47:35 -0500 Subject: [Tutor] IndexError and appending to lists [Was: Re: Need Helpon Assignment] In-Reply-To: <00aa01c5a93e$9c62bbf0$3bc98751@xp> References: <430BCE0F.1060300@comcast.net> <006001c5a87f$4da85e80$3bc98751@xp> <430D1043.5040801@comcast.net> <00aa01c5a93e$9c62bbf0$3bc98751@xp> Message-ID: <430DCBF7.8090301@comcast.net> Alan, Now I understand! Thanks again for the explanation! Alan G wrote: >> "for" loop as you suggest, the program won't enter the loop unless >> "s" is initialized so that it's in "input". How do I do that? > > > for s in input: > > means that s takes on each value in input. > input is your file. Thus s takes on the value of each line in > the input file. You don't need to initialise s before entering > the loop as you would with a while loop. Similarly you don't > need to test for the end of the file, 'for' does all that too. > > Take a look at the 'Loops' topic and then the 'Handling Files' topic > in my tutorial for more info on this. > >> Also, near the end of your remarks you say that the code at the >> bottom of my program doesn't do anything. It does for me. > > > Lets take a look: > >>>> print N >>>> for i in range(N): >>>> T[i] <-------- This does nothing >>>> print T[i] >>> > > The line that simply has the value in it will not do anything. > It will not print out the value, you need to call print for that > to happen. > >> put in those print statements to verify that the contents of those >> variables are what I expected them to be. That's all that mess is for. > > > The debug/test print statements are fine, I was only pointing out > that one line did nothing, not the entire block. > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From ewalker at micron.com Thu Aug 25 18:28:39 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 25 Aug 2005 10:28:39 -0600 Subject: [Tutor] Hello In-Reply-To: <20050824215718.10f117bc.usedtire@pbembattletech.com> References: <20050824234917.73909.qmail@web60112.mail.yahoo.com> <20050824215718.10f117bc.usedtire@pbembattletech.com> Message-ID: <200508251028.39837.ewalker@micron.com> On Wednesday 24 August 2005 03:57 pm, Jesse Lands wrote: Yes, I think its well worth it. He's a great guy and you learn lots of python tips and stuff. I need to get something to do now... ... > On Wed, 24 Aug 2005 16:49:17 -0700 (PDT) > > Eric Walker wrote: > > all, > > Hello... I just finished a class given by Mark Lutz > > and I love python. Now I need to find a project to > > hone my skills. I am sure I will be sending lots of > > questions to this list. I used to use perl but now > > Its gone. I am now a Python guy... Hail Guido.... > > How was the class? I am taking a class that Mark Lutz is teaching in > October. Is it worth it? Thanks -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From jobauk at hotmail.com Thu Aug 25 18:43:44 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Thu, 25 Aug 2005 16:43:44 +0000 Subject: [Tutor] (no subject) Message-ID: Hi, What is the best way to split a unicode string in its characters? Specifically, having this unicode chinese string u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48 I want to either split all its characters: [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48] or insert a space between each character: \u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48 Its not as easy as it looks, though. chrs j. From johnp at milwaukielumber.com Thu Aug 25 18:44:47 2005 From: johnp at milwaukielumber.com (John Purser) Date: Thu, 25 Aug 2005 09:44:47 -0700 Subject: [Tutor] Handling binary file In-Reply-To: <20050825011948.58755.qmail@web31210.mail.mud.yahoo.com> Message-ID: <200508251644.j7PGilk9031628@email.morseintranet.com> Julie, I've had to work with some binary files with 3 byte data types. They were generated by an application coded in Business Basic. Like you I grabbed it as bytes and converted. For clarity's sake I used powers of 2 instead of hard coding the numbers. 2^8 makes it pretty obvious why you're multiplying by 256 IMHO. Look out for negative numbers though. May not be applicable to "number of seconds" but as a general rule watch for it. Incidentally when I had to read the same data with VBA I used the same technique to reverse the byte order from Unix to Windows. Worked just fine. John Purser _____ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Julie Lai Sent: Wednesday, August 24, 2005 18:20 To: tutor at python.org Subject: [Tutor] Handling binary file I have opened a file in binary mode. The 9th, 10th and 11th bytes contain the time in seconds. In order to get this value in decimal I did the following: timeinsec = bytes[9] * 65536 + bytes[10] * 256 + bytes{11] Would someone please advise if there is a better way to do this? Thanks, Julie. _______________________________________ ?????? email ??? ?? Yahoo! Messenger http://messenger.yahoo.com.hk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050825/ac0173f5/attachment.htm From carroll at tjc.com Thu Aug 25 18:52:10 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 25 Aug 2005 09:52:10 -0700 (PDT) Subject: [Tutor] Splitting a unicode string into characters (was "(No Subject)") In-Reply-To: Message-ID: Jorge, please include a subject line. On Thu, 25 Aug 2005, Jorge Louis de Castro wrote: > What is the best way to split a unicode string in its characters? > Specifically, having this unicode chinese string > > u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48 I'm assuming you've actually got the close-quote there, i.e.: >>> s=u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48' > I want to either split all its characters: > [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48] >>> l=list(s) >>> l [u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48'] > or insert a space between each character: > \u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48 >>> s_with_spaces = ' '.join(l) >>> s_with_spaces u'\u8c01 \u4eca \u5929 \u7a7f \u4ec0 \u4e48' From kent37 at tds.net Thu Aug 25 18:57:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Aug 2005 12:57:40 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <430DF884.2010703@tds.net> Jorge Louis de Castro wrote: > Hi, > > What is the best way to split a unicode string in its characters? > Specifically, having this unicode chinese string > > u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48 > > I want to either split all its characters: > [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48] >>> s=u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48' >>> list(s) [u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48'] > or insert a space between each character: > \u8C01 \u4ECA \u5929 \u7A7F \u4EC0 \u4E48 >>> ' '.join(list(s)) u'\u8c01 \u4eca \u5929 \u7a7f \u4ec0 \u4e48' Kent From alan.gauld at freenet.co.uk Thu Aug 25 19:20:59 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 25 Aug 2005 18:20:59 +0100 Subject: [Tutor] (no subject) References: Message-ID: <002a01c5a999$5c63ec30$52199c51@xp> I've not used pickle so don;t know if this is relevant but... > output = codecs.open(".\\"+self.filename, "ab") > cPickle.dump(self.terms, output) > inFile = codecs.open(".\\"+self.filename, "r") > cPickle.load(self.terms, inFile) I notice you wrote in binary mode but are reading in text mode. Does binary reading make a difference? Guessing, Alan G. PS. Anyone else notice how some topics seem to come up in bunches. We haven't had any questions involving binary files for months and this last week we've had at least 3! From arvind at arraycomm.com Thu Aug 25 20:02:35 2005 From: arvind at arraycomm.com (Arvind Raghavan) Date: Thu, 25 Aug 2005 11:02:35 -0700 Subject: [Tutor] Running a script not in the current directory Message-ID: <430E07BB.6030802@arraycomm.com> I'm using an XP platform and have both a Windows and Cygwin installation of Python. I store all my Python scripts in one directory, but would like to invoke the script from the command line without specifying the full path to this directory. i.e., Say all my scripts are in: ~/py_scripts/ My current directory is: ~ I want to be able to do this: prompt>python myscript.py and not: prompt>python ~/py_scripts/myscript.py Any way to do this? (I use PYTHONPATH for modules and that works correctly) Arvind From nick at javacat.f2s.com Thu Aug 25 21:28:45 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 25 Aug 2005 20:28:45 +0100 Subject: [Tutor] Should I be thinking of threads for this ? Message-ID: <430E1BED.6020709@javacat.f2s.com> Hello folks, I have the following code taken from the Twisted examples - [code] # filewatcher.py from twisted.application import internet def watch(fp): fp.seek(fp.tell()) for line in fp.readlines(): sys.stdout.write(line) import sys from twisted.internet import reactor s = internet.TimerService(1.0, watch, file(sys.argv[1])) s.startService() reactor.run() s.stopService() [/code] I find this piece of code amazing and I am keen to put it to use. If I run './filewatcher.py myfile' it will print out any changes made to 'myfile', very similar to 'tail -f' . Now if I want to have this program monitor several files at once I could run './filewatcher.py file1 file2 filex' or './filewatcher.py file1 & ./filewatcher file2 & etc' both with minor modifications to the code, but I think that could cause performance problems relating to the OS. So I'm thinking I will need to learn python threads (no bad thing) instead, but Im hoping that someone could tell me if that seems the best way to go ? I will be getting to grips with python threads anyway but I'd appreciate any input on this. Many thanks, Nick . From grouch at gmail.com Thu Aug 25 20:24:38 2005 From: grouch at gmail.com (grouchy) Date: Thu, 25 Aug 2005 13:24:38 -0500 Subject: [Tutor] Beautiful Soup / Unicode problem? Message-ID: Hi, I'm having bang-my-head-against-a-wall moments trying to figure all of this out. A word of warming, this is the first time I've tried using unicode, or Beautiful Soup, so if I'm being stupid, please forgive me. I'm trying to scrape results from google as a test case. with Beautiful Soup. I've seen people recommend it here, so maybe somebody can recognize what I'm doing wrong: >>>from BeautifulSoup import BeautifulSoup >>>file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup") >>>file = file.read().decode("utf-8") >>>soup = BeautifulSoup(file) >>>results = soup('p','g') >>> x = results[1].a.renderContents() >>> type(x) >>> print x Matt Croydon::Postneo 2.0 ? Blog Archive ? Mobile Screen Scraping ... So far so good. But what I really want is just the text, so I try something like: >>> y = results[1].a.fetchText(re.compile('.+')) Traceback (most recent call last): File "", line 1, in ? File "BeautifulSoup.py", line 466, in fetchText return self.fetch(recursive=recursive, text=text, limit=limit) File "BeautifulSoup.py", line 492, in fetch return self._fetch(name, attrs, text, limit, generator) File "BeautifulSoup.py", line 194, in _fetch if self._matches(i, text): File "BeautifulSoup.py", line 252, in _matches chunk = str(chunk) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 26: ordinal not in range(128) Is this a bug? Come to think of it, I'm not even sure how printing x worked, since it printed non-ascii characters. If I convert to a string first: >>> filestr = file.encode("utf-8") >>> soup = BeautifulSoup(filestr) >>> soup('p','g')[1].font.fetchText(re.compile('.+')) ['Mobile Screen Scraping with ', 'BeautifulSoup', ' and Python for Series 60. ', 'BeautifulSoup', ' 2', 'BeautifulSoup', ' 3. I haven\xe2€™t had enough time to work up a proper hack for ', '...', 'www.postneo.com/2005/03/28/', 'mobile-screen-scraping-with-', 'beautifulsoup', '-and-python-for-series-60 - 19k - Aug 24, 2005 - ', ' ', 'Cached', ' - ', 'Similar pages'] The regex works, but things like "I haven\xe2€™t" get a bit mangled :) In filestr, it was represented as haven\xe2\x80\x99t which I guess is the ASCII representation for UTF-8. From Hans.Dushanthakumar at navman.com Thu Aug 25 23:42:49 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Fri, 26 Aug 2005 09:42:49 +1200 Subject: [Tutor] Differences in running a multithreaded script under IDLE and otherwise Message-ID: <5667508E43F1B740BCFA57FF46E35300016C3D35@nav_akl_exch_c.newton.navman.com> Kent, I'm using the same version (2.4.1) under Win XP. The program works as expected (ie prints "run: " a few times, and then just goes dead - no errors. Having said that, I did see one instance where it ran to completion under IDLE. So looks like the behaviour is not consistent. Cheers Hans -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, 25 August 2005 11:23 p.m. Cc: tutor at python.org Subject: Re: [Tutor] Differences in running a multithreaded script under IDLE and otherwise Hans Dushanthakumar wrote: > Hi, > While running the foll script by double-clicking it (under WinXP), > it runs as expected. However, when I run it via IDLE, it hangs after a > few secs (no runtime errors - just hangs). Why does this happen? It works for me in IDLE with Python 2.4.1 on Win2k. What version of Python do you have? Do you get any output at all? Kent > > Cheers > Hans > > import threading > > class incr_num(threading.Thread): > num = '' > > def __init__(self, local_num): > global num > threading.Thread.__init__(self) > num = local_num > print "__init__: ", num > > def run(self): > global num > for k in range (20): > print "run: ", num > num = num + 1 > > incr_num_thread = incr_num(501) > incr_num_thread.start() > > print "Wait for thread to finish" > incr_num_thread.join() > print "Thread finished" > > raw_input("Press enter") > _______________________________________________ > 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 me at scottoertel.info Thu Aug 25 23:55:51 2005 From: me at scottoertel.info (Scott Oertel) Date: Thu, 25 Aug 2005 14:55:51 -0700 Subject: [Tutor] Working with files In-Reply-To: <6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> References: <430CDED8.6070304@scottoertel.info> <6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> Message-ID: <430E3E67.60205@scottoertel.info> Bob Gailer wrote: > At 02:55 PM 8/24/2005, Scott Oertel wrote: > >> How do I use the built in file objects to insert text into a file at a >> certain location? >> >> i.e. >> >> something, 2, chance, weee >> nothing, happened, crap, nice >> >> .... need to search for "something" and insert, "what," before it > > > Here's the algorithm. If you know enough Python you will be able to > code it. So put together a program, give it a try and come back with > questions. > > read the file into a string variable (assuming the file is not humungus) > find the location of "something" in the string > assemble a new string consisting of: > the original string up to the location (index) of "something" > "what" > the rest of the original string > write the new string to the file > > Bob Gailer > 303 442 2625 home > 720 938 2625 cell basically I took the idea and the code example given and wrote this little function, i stuck vars in this html page like #email# and just used it like this, " insertdata('#email#','scott at python.org') works perfect! def insertdata(name, data): file = open('template.html', 'r+') contents = file.read() pos = contents.index(name) file.seek(pos) file.write(data) file.write(contents[pos + len(name):]) file.close() From john at fouhy.net Fri Aug 26 00:09:50 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 26 Aug 2005 10:09:50 +1200 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <5e58f2e4050825150927bb4a58@mail.gmail.com> On 8/26/05, Jorge Louis de Castro wrote: > I think I may have misinterpreted the syntax of cPickle. I have dumped data > onto a file using: > > output = codecs.open(".\\"+self.filename, "ab") > cPickle.dump(self.terms, output) > cPickle.dump(self.username, output) > cPickle.dump(self.age, output) > cPickle.dump(self.gender, output) > cPickle.dump(self.totalMsgs, output) > cPickle.dump(self.occurrences, output) > > I thought I could unpickle this using the load feature, something like: > inFile = codecs.open(".\\"+self.filename, "r") > cPickle.load(self.terms, inFile) > cPickle.dump(self.username, inFile) > cPickle.dump(self.age, inFile) > cPickle.dump(self.gender, inFile) > cPickle.dump(self.totalMsgs, inFile) > cPickle.dump(self.occurrences, inFile) Did you notice you have only one call to load() here? The others are still dump(). >>> import pickle >>> f = file('foo', 'ab') >>> pickle.dump('foo', f) >>> pickle.dump('bar', f) >>> pickle.dump('baz', f) >>> f.close() >>> f = file('foo', 'rb') >>> a = pickle.load(f) >>> b = pickle.load(f) >>> c = pickle.load(f) >>> a,b,c ('foo', 'bar', 'baz') Although, normally when I use pickle, I chuck everything into a tuple, so I can store/retrieve it all with a single dump/load command.. -- John. From Liam.Clarke-Hutchinson at business.govt.nz Thu Aug 25 23:06:07 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 26 Aug 2005 09:06:07 +1200 Subject: [Tutor] Source PC MAC address Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A657@chbnt01.alpha.wd.govt.nz> >PS: do not forget to send your answers to Python Tutor also ... BTW, >could it be possible de configure the list so that the "reply-to" field >is set to the Python Tutor list instead of the sender ? I believe our list administrator has decided that reply-to munging can be considered harmful. http://www.unicom.com/pw/reply-to-harmful.html Johan Geldenhuys a ?crit : > Is there a other way of doing this? Getting the MAC. I am on a ethernet > network. > > Johan > > > > > > ------------------------------------------------------------------------ > > Sujet: > Re: [Tutor] Source PC MAC address > Exp?diteur: > Pierre Barbier de Reuille > Date: > Wed, 24 Aug 2005 17:00:46 +0200 > Destinataire: > Python Tutor > > Destinataire: > Python Tutor > > Return-Path: > > Received: > from earth.accesstel.co.za ([unix socket]) by earth (Cyrus v2.1.9) with > LMTP; Wed, 24 Aug 2005 16:59:09 +0200 > X-Sieve: > CMU Sieve 2.2 > Received: > by earth.accesstel.co.za (Postfix, from userid 65534) id F00D011DD9; > Wed, 24 Aug 2005 16:59:08 +0200 (SAST) > Received: > from localhost.localdomain (localhost [127.0.0.1]) by > earth.accesstel.co.za (Postfix) with ESMTP id 11EF911DD9 for > ; Wed, 24 Aug 2005 16:59:08 +0200 (SAST) > Received: > from smtp-vbr1.xs4all.nl (smtp-vbr1.xs4all.nl [194.109.24.21]) by > gateway.azitech.co.za (8.11.6/8.11.6) with ESMTP id j7OEnmr23311 for > ; Wed, 24 Aug 2005 16:49:49 +0200 > Received: > from bag.python.org (bag.python.org [194.109.207.14]) by > smtp-vbr1.xs4all.nl (8.13.3/8.13.3) with ESMTP id j7OEvApb033830; Wed, > 24 Aug 2005 16:57:10 +0200 (CEST) (envelope-from tutor-bounces at python.org) > Received: > from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with > ESMTP id DA7B61E400F; Wed, 24 Aug 2005 16:57:15 +0200 (CEST) > X-Original-To: > tutor at python.org > Received: > from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with > ESMTP id 5382C1E4003 for ; Wed, 24 Aug 2005 16:57:13 > +0200 (CEST) > Received: > from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP; > 24 Aug 2005 16:57:13 +0200 > Received: > from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by > bag.python.org (Postfix) with ESMTP for ; Wed, 24 Aug > 2005 16:57:13 +0200 (CEST) > Received: > from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by > auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsnoG028104 for > ; Wed, 24 Aug 2005 16:54:49 +0200 > Received: > from [195.221.175.162] (barbier at pcps-162.cirad.fr [195.221.175.162]) by > auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsmMS028090 for > ; Wed, 24 Aug 2005 16:54:48 +0200 > ID du Message: > <430C8B9E.8020505 at cirad.fr> > Agent utilisateur: > Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050817 > Thunderbird/1.0.2 Mnenhy/0.7 > X-Accept-Language: > fr, en > Version de MIME: > 1.0 > R?f?rences: > <1124880684.9086.7.camel at KMA.accesstel> > In-Reply-To: > <1124880684.9086.7.camel at KMA.accesstel> > X-Enigmail-Version: > 0.91.0.0 > X-BeenThere: > tutor at python.org > X-Mailman-Version: > 2.1.6 > Precedence: > list > List-Id: > Discussion for learning programming with Python > List-Unsubscribe: > , > > List-Archive: > > List-Post: > > List-Help: > > List-Subscribe: > , > > Content-Type: > text/plain; charset="iso-8859-15" > Exp?diteur: > tutor-bounces at python.org > Errors-To: > tutor-bounces at python.org > X-Virus-Scanned: > by XS4ALL Virus Scanner > X-Accesstel-MailScanner-Information: > Please contact Accesstel for information > X-Accesstel-MailScanner: > Found to be clean > X-MIME-Autoconverted: > from quoted-printable to 8bit by gateway.azitech.co.za id j7OEnmr23311 > X-Fetched: > by SuSE Linux Openexchange Server from > accesstel^johan at mail.accesstel.co.za for johan at accesstel.co.za via pop > X-Spam-Status: > No, hits=-7.6 required=4.8 > tests=AWL,BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES, > REPLY_WITH_QUOTES,SIGNATURE_LONG_SPARSE, USER_AGENT_MOZILLA_UA > autolearn=ham version=2.55 > X-Spam-Checker-Version: > SpamAssassin 2.55 (1.174.2.19-2003-05-19-exp) > Content-Transfer-Encoding: > 8bit > > > Socket is built up on IP, not on Ethernet: you have no way of finding a > MAC address using sockets simply because it may not exist one ! (if > you're not on an Ethernet network) You need to access lower levels of > network and probably access directly the network packet as your network > card is sending it to your OS ! > > Pierre > > Johan Geldenhuys a ?crit : > >>Hi List, >>I am doing some networking programming and would like to limit access to >>my socket server on the the source devices' MAC address. >>I know the IP from where the connection is coming, but how could I find >>out what the MAC of the source device is? >>Any quick answers / ideas? >>Is there a build-in function in socket that can do this? >> >>Thanks, >> >>Johan >> >> >> >> >> >>------------------------------------------------------------------------ >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From alan.gauld at freenet.co.uk Fri Aug 26 00:17:33 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 25 Aug 2005 23:17:33 +0100 Subject: [Tutor] (no subject) References: Message-ID: <009301c5a9c2$ca9ca420$52199c51@xp> > What is the best way to split a unicode string in its characters? > Specifically, having this unicode chinese string > > u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48 > > I want to either split all its characters: > [\u8C01,\u4ECA,\u5929,\u7A7F,\u4EC0,\u4E48] > >>> s = u'\u8C01\u4ECA\u5929\u7A7F\u4EC0\u4E48' >>> list(s) [u'\u8c01', u'\u4eca', u'\u5929', u'\u7a7f', u'\u4ec0', u'\u4e48'] >>> What seemed to be the problem? Or am I missing something? Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Aug 26 00:41:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Aug 2005 15:41:06 -0700 (PDT) Subject: [Tutor] Beautiful Soup / Unicode problem? In-Reply-To: Message-ID: On Thu, 25 Aug 2005, grouchy wrote: > >>>file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup") > >>>file = file.read().decode("utf-8") > >>>soup = BeautifulSoup(file) > >>>results = soup('p','g') > >>> x = results[1].a.renderContents() > >>> type(x) > > >>> print x > Matt Croydon::Postneo 2.0 » Blog Archive » Mobile Screen Scraping ... Hi Grouchy, So far, so good. You were lucky to be able to print 'x' off-hand like that. When we str() a unicode string, Python will use the default encoding scheme: ###### >>> import sys >>> sys.getdefaultencoding() 'ascii' ###### On my Linux machine, as long as that unicode string didn't include anything that couldn't be encoded as ascii, I'm ok. Of course, the flip side of this is that some unicode strings can't be str()'ed right off the bat: ###### >>> nonasciiMsg = unicode(u'\xbb') >>> nonasciiMsg u'\xbb' >>> str(nonasciiMsg) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 0: ordinal not in range(128) ###### Note here that we can still get a kind of string representation of the nonasciiMsg here; it's when we use str() that bad things happen, and that's because the print statement uses str() as a helper utility. > So far so good. But what I really want is just the text, so I try > something like: > > >>> y = results[1].a.fetchText(re.compile('.+')) > Traceback (most recent call last): > File "", line 1, in ? > File "BeautifulSoup.py", line 466, in fetchText > return self.fetch(recursive=recursive, text=text, limit=limit) > File "BeautifulSoup.py", line 492, in fetch > return self._fetch(name, attrs, text, limit, generator) > File "BeautifulSoup.py", line 194, in _fetch > if self._matches(i, text): > File "BeautifulSoup.py", line 252, in _matches > chunk = str(chunk) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in > position 26: ordinal not in range(128) That's odd! Ok, let's check why BeautifulSoup is str()-ing the chunk... ### in BeautifulSoup.py ####################### #Now we know that chunk is a string if not type(chunk) in types.StringTypes: chunk = str(chunk) if hasattr(howToMatch, 'match'): # It's a regexp object. return howToMatch.search(chunk) ################################################ Ok, that's surprising! Isn't a unicode string's type in types.StringTypes? ###### >>> import types >>> types.StringTypes (, ) ###### Ok. That, too, looks fine. The error message implies that it goes into line 252, where 'chunk' is a unicode string. But from the experiments on my system, running on Python 2.3.5, I don't see how this is doing that. Mysterious. If you have a moment, do you mind doing this on your system? ###### import types print types.StringTypes import sys print sys.version() print type(u'hello') in types.StringTypes ###### and show us what comes up? Good luck to you! From daniel at thewatkins.org.uk Fri Aug 26 02:59:10 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Fri, 26 Aug 2005 01:59:10 +0100 Subject: [Tutor] Remote Directory Reading Message-ID: <1125017950.1831.16.camel@amdbert.oxbridgetechnology.local> I've run into a bit of trouble with my spider script. Thus far, it is able to retrieve all of the data off the website that is contained within standard HTML, downloading jpg, gif and bmp images that are related to the files (this restriction only being set by a lack of further definitions by myself). However, I have run into a problem with one link that simply points to a folder (www.aehof.org.uk/forum) within which is contained a phpBB forum. I've attempted to use 'dircache' but couldn't find a way for it to understand web addresses. However, I may not have hit upon the right combination of syntax, so may be mistaken. I also considered 'os' but it appears to require definition of a particular operating system, which is a direction I'd prefer not to take unless I have to. In addition, the error messages I received from using 'dircache' traced back into 'os' so it is unlikely it would have been suitable for the purpose. The variables at the top of the script will later be cleaned up so they are defined by command line input, they're just there while I sort the actual script itself out. Succinctly, I'm looking for an addition to the following script (ideally under 'default_defs') which will allow me to copy a directly-linked folder and all its contents. I hope I have expressed myself in a useful manner, and any help would be appreciated, although I would prefer no comments on the script in general as I would quite like to develop it myself as a learning project (this being my first proper script). Cheers muchly, Dan spider.py """ import re import urllib import distutils.dir_util site = "http://www.aehof.org.uk" localdir = "/home/daniel/test/" default_defs='[cf]=".*html"|c=".*jpg"|c=".*gif"|c=".*bmp"' if not re.search('/\Z',site): site = site + "/" def get_page_items (source, site = site, defs = default_defs): next = [] text = urllib.urlopen(site+source).read() if re.search(defs,text): for i in re.findall(defs,text): i = i[3:-1] next.append(i) src = [source] + next return src def get_list (source="index.html"): items = [] next = get_page_items (source) for i in next: if i not in items: items.append (i) next.extend (get_page_items (i)) return items def copy_items (): items = get_list() for i in items: distutils.dir_util.create_tree(localdir, items) original = urllib.urlopen(site+i) local = open(localdir+i,'w') body = original.read() local.write(body) local.close() copy_items() """ From kent37 at tds.net Fri Aug 26 13:21:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 07:21:31 -0400 Subject: [Tutor] Beautiful Soup / Unicode problem? In-Reply-To: References: Message-ID: <430EFB3B.7070503@tds.net> grouchy wrote: > Hi, > > I'm having bang-my-head-against-a-wall moments trying to figure all of this out. > >>>>from BeautifulSoup import BeautifulSoup >>> >>>>file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup") >>>>file = file.read().decode("utf-8") >>>>soup = BeautifulSoup(file) >>>>results = soup('p','g') >>>>x = results[1].a.renderContents() >>>>type(x) > > > >>>>print x > > Matt Croydon::Postneo 2.0 ? Blog Archive ? Mobile Screen Scraping ... > > So far so good. But what I really want is just the text, so I try > something like: > > >>>>y = results[1].a.fetchText(re.compile('.+')) > > Traceback (most recent call last): > File "", line 1, in ? > File "BeautifulSoup.py", line 466, in fetchText > return self.fetch(recursive=recursive, text=text, limit=limit) > File "BeautifulSoup.py", line 492, in fetch > return self._fetch(name, attrs, text, limit, generator) > File "BeautifulSoup.py", line 194, in _fetch > if self._matches(i, text): > File "BeautifulSoup.py", line 252, in _matches > chunk = str(chunk) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in > position 26: ordinal not in range(128) > > Is this a bug? Come to think of it, I'm not even sure how printing x > worked, since it printed non-ascii characters. This is the first question in the BeautifulSoup FAQ at http://www.crummy.com/software/BeautifulSoup/FAQ.html Unfortunately the author of BS considers this a problem with your Python installation! So it seems he doesn't have a good understanding of Python and Unicode. (OK, I can forgive him that, I think there are only a handful of people who really do understand it completely.) The first fix given doesn't work. The second fix works but it is not a good idea to change the default encoding for your Python install. There is a hack you can use to change the default encoding just for one program; in your program put reload(sys); sys.setdefaultencoding('utf-8') This seems to fix the problem you are having. Kent From kent37 at tds.net Fri Aug 26 13:33:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Aug 2005 07:33:00 -0400 Subject: [Tutor] Remote Directory Reading In-Reply-To: <1125017950.1831.16.camel@amdbert.oxbridgetechnology.local> References: <1125017950.1831.16.camel@amdbert.oxbridgetechnology.local> Message-ID: <430EFDEC.2080904@tds.net> Daniel Watkins wrote: > I've run into a bit of trouble with my spider script. Thus far, it is > able to retrieve all of the data off the website that is contained > within standard HTML, downloading jpg, gif and bmp images that are > related to the files (this restriction only being set by a lack of > further definitions by myself). However, I have run into a problem with > one link that simply points to a folder (www.aehof.org.uk/forum) within > which is contained a phpBB forum. It seems to me this page is no different from any other - it has a bunch of links that you can follow to get the content. I'm not sure why you want to handle it specially? Except maybe to ignore some of the links, which you will have to write into your program. > I've attempted to use 'dircache' but couldn't find a way for it to > understand web addresses. However, I may not have hit upon the right > combination of syntax, so may be mistaken. I also considered 'os' but it > appears to require definition of a particular operating system, which is > a direction I'd prefer not to take unless I have to. In addition, the > error messages I received from using 'dircache' traced back into 'os' so > it is unlikely it would have been suitable for the purpose. The os module actually hides the differences between operating systems pretty well. It has implementations for many os's but the interface you see is os-independent. The choice of the correct implementation happens under the hood, it is not something you need to be concerned with. Kent From alan.gauld at freenet.co.uk Fri Aug 26 14:02:22 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 26 Aug 2005 13:02:22 +0100 Subject: [Tutor] Working with files References: <430CDED8.6070304@scottoertel.info><6.1.2.0.0.20050824161531.02fba6c8@mail.mric.net> <430E3E67.60205@scottoertel.info> Message-ID: <00e601c5aa36$04d0b5f0$52199c51@xp> > > basically I took the idea and the code example given and wrote this > little function, i stuck vars in this html page like #email# and > just used it like this, " insertdata('#email#','scott at python.org') > > works perfect! ARe you sure? The problem using seek and write is that if the data you are inserting is bigger than your marker you will overwrite the data following the marker. Thus if your marker were in a table like:
#email#Scott's email
scott at python.orgScott's email