From dyoo at hkn.eecs.berkeley.edu Mon May 1 08:11:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 30 Apr 2006 23:11:03 -0700 (PDT) Subject: [Tutor] Splitting strings into blocks In-Reply-To: <200604301635.09227.daniel@thewatkins.org.uk> References: <200604301635.09227.daniel@thewatkins.org.uk> Message-ID: On Sun, 30 Apr 2006, Daniel Watkins wrote: > I'm currently working on a program to parse LaTeX style maths > expressions and provide an answer. For example, I have the expression > "2^\frac{1}{2}". I'm trying to work out a way to split this into it's > most basic blocks of LaTeX (i.e. 2^ and \frac{1}{2}) while maintaining a > record of the depth of the expression (i.e. (2^,0),(\frac{1}{2},1)). Hi Daniel, Forgive me for going off a side tangent here, but do we have to work directly on LaTeX? I don't mean this to be a silly question! What kind of problem are we trying to solve? It sounds like we're trying to evaluate LaTeX equations, so that presents the problem of parsing LaTeX. Diagrammically: LaTeX source ---- parsing --> evaluated expressions We could talk about parsing LaTeX. But could we have equations written in something easier to parse, and generate LaTeX out of that? That is: some easy-to-parse equations | +-- simple parser --> LaTeX writer ---> LaTeX source | +-- simple parser --> evaluator --> evaluated expressions If we have the freedom to do this, we may want to take this route, because it frees us from being so tied to LaTeX. For example, although this will look silly at first, we could do something like: text = """ Hello world. 3 6 equals: Does that look ok? """ This is just an ad-hoc XML document I've cooked up. The idea is that, given something like the above, we can: * write a XML-processing program to turn this into legitimate LaTeX source, or * write a program to evaluate all the math expressions and give us their values. If we take this route, the parsing problem here is already solved for us because there are XML-parsing modules like minidom or ElementTree. http://docs.python.org/lib/module-xml.dom.minidom.html http://effbot.org/zone/element-index.htm For example, here's a quick and dirty one that doesn't do a perfect job, but it's a start. (For this example, I'm using minidom because it handles text nodes as uniformly as other nodes, whereas ElementTree treats them as weird special cases.) ################################################################## import xml.dom.minidom def node_to_latex(node): """node_to_latex: node -> string Converts an arbitrary node to LaTeX source.""" if node.nodeType == node.TEXT_NODE: return text_to_latex(node) elif node.tagName == 'para': return para_to_latex(node) elif node.tagName == 'math': return math_to_latex(node) elif node.tagName == 'evaluated': return evaluated_to_latex(node) def text_to_latex(node): """text_to_latex: node -> string Assuming node is a text node, returns its textual data.""" return node.data def para_to_latex(para_node): """para_to_latex: para -> string Converts a paragraph node to LaTeX source.""" results = [] for sub_node in para_node.childNodes: results.append(node_to_latex(sub_node)) results.append('\n') return ''.join(results) def math_to_latex(math): """math_to_latex: node -> string Converts a math node to latex source.""" results = ['\n\\begin{math}\n'] for sub_math_node in math.childNodes: results.append(math_subnode_to_latex(sub_math_node)) results.append('\n\\end{math}\n') return ''.join(results) def math_subnode_to_latex(sub_node): """math_subnode_to_latex: node -> string Converst a math subnode into LaTeX. At the moment, we handle only fractions and text.""" results = [] if sub_node.nodeType == sub_node.TEXT_NODE: results.append(sub_node.data) elif sub_node.tagName == 'fraction': results.append(fraction_to_latex(sub_node)) return ''.join(results) def fraction_to_latex(node): """fraction_to_latex: fraction -> string Converts fractions to LaTeX.""" results = ['\\frac'] results.append('{') for child_math in ( node.getElementsByTagName('numer')[0].childNodes): results.append(math_subnode_to_latex(child_math)) results.append('}') results.append('{') for child_math in ( node.getElementsByTagName('denom')[0].childNodes): results.append(math_subnode_to_latex(child_math)) results.append('}') return ''.join(results) def evaluated_to_latex(node): """evaluated_to_latex: evaluated -> string Converts evaluated to LaTeX. Doesn't quite work right yet.""" results = [] results.append("EVALUATED-NOT-HANDLED-YET") return ''.join(results) if __name__ == '__main__': text = """ Hello world. 3 6 equals: Does that look ok? """ tree = xml.dom.minidom.parseString(text) print node_to_latex(tree.documentElement) ################################################################## My apologies for the length here, but I needed all those functions. This does a recursive traversal through the structure of the XML tree. It handles text, paragraphs, and very simple math. The XML document is neutral in the ways we can interpret it. Not only can we use it as a source for making LaTeX documents, but we can also extract all the math expressions in there by doing a similar kind of recursive traversal. ##################################################################### def find_math(node): """find_math: node -> (listof node) Returns a list of all the math sub-nodes embedded in the node.""" if node.nodeType == node.TEXT_NODE: return [] elif node.tagName == 'math': return [node] else: results = [] for child in node.childNodes: results.extend(find_math(child)) return results ##################################################################### Evaluating these math nodes should just be a matter of doing similar kinds of recursive traversals on their structure. I'm sorry I went really fast on this, but does this make sense so far? From kent37 at tds.net Mon May 1 14:57:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 May 2006 08:57:27 -0400 Subject: [Tutor] Splitting strings into blocks In-Reply-To: <200604301635.09227.daniel@thewatkins.org.uk> References: <200604301635.09227.daniel@thewatkins.org.uk> Message-ID: <445605B7.2020602@tds.net> Daniel Watkins wrote: > Hi list, > I'm currently working on a program to parse LaTeX style maths expressions and > provide an answer. For example, I have the expression "2^\frac{1}{2}". I'm > trying to work out a way to split this into it's most basic blocks of LaTeX > (i.e. 2^ and \frac{1}{2}) while maintaining a record of the depth of the > expression (i.e. (2^,0),(\frac{1}{2},1)). I will then process this list from > the highest order downwards, feeding the deeper results progressively into > shallower elements until all have been calculated. > LaTeX allows me to legally express the previously stated expression as > "{2^{\\frac{1}{2}}}". This makes it much easier to figure out where the units > of LaTeX are located. The depth of any item can now be expressed as the > number of unpaired opening or closing braces between the element and the > start or end of the expression. > I'm essentially looking for a way to split the string up along the braces, > while recording the number of braces between the split and either end of the > expression. First, I'll echo Danny's question - why do you need to do this? For a general parser of LaTex expressions you will want to use a parsing package. I have found pyparsing to be pretty easy to use but there are many others. Someone may have solved this problem already. To answer your specific question, here is code that uses re.split() to break an expression on the braces, then a simple loop through the results keeps track of nesting level and prints the depth of each token between the braces: import re data = r"{2^{\\frac{1}{2}}}" depth = 0 for token in re.split(r'([{}])', data): if token == '{': depth += 1 elif token == '}': depth -= 1 elif token: print depth, token Kent From kent37 at tds.net Mon May 1 15:46:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 May 2006 09:46:20 -0400 Subject: [Tutor] Splitting strings into blocks In-Reply-To: <445605B7.2020602@tds.net> References: <200604301635.09227.daniel@thewatkins.org.uk> <445605B7.2020602@tds.net> Message-ID: <4456112C.3020806@tds.net> Kent Johnson wrote: > For a general parser of LaTex expressions you will want to use a parsing > package. I have found pyparsing to be pretty easy to use but there are > many others. Someone may have solved this problem already. Googling 'python latex parser' gives some interesting hits including http://pylatex.sourceforge.net/ http://lists.wxwidgets.org/archive/wxPython-docs/msg00235.html Kent From jon at spamcop.net Mon May 1 16:57:45 2006 From: jon at spamcop.net (Jon Whitehouse) Date: Mon, 01 May 2006 10:57:45 -0400 Subject: [Tutor] Pyton and Webpages Message-ID: <20060501105745.l4pah7osg8gos40s@webmail.spamcop.net> Greetings All, I'm a newbie to python and am curious if I can do the following in python. I'm not asking HOW to do this, just if it is possible before I spend the time to learn python and do it myself. I want to write a program to go to a webpage, pull the data, and then place it into an excel spreadsheet and then write it to an html file and allow me to also click on the link to the excel spreadsheet. Is this possible to do with python? -- Jon Whitehouse From bgailer at alum.rpi.edu Mon May 1 17:29:16 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 01 May 2006 08:29:16 -0700 Subject: [Tutor] Pyton and Webpages In-Reply-To: <20060501105745.l4pah7osg8gos40s@webmail.spamcop.net> References: <20060501105745.l4pah7osg8gos40s@webmail.spamcop.net> Message-ID: <4456294C.7060108@alum.rpi.edu> Jon Whitehouse wrote: > Greetings All, > > I'm a newbie to python and am curious if I can do the following in python. I'm > not asking HOW to do this, just if it is possible before I spend the time to > learn python and do it myself. > > I want to write a program to go to a webpage, pull the data, Yes. There is a module for that. Since you want to discover it yourself I won't name it here. Hint: going to a web page requires a url. > and then place it into an excel spreadsheet Yes. There are several ways to do that. > and then write it to an html file Yes. Python provides file i/o. > and allow me to also click on the link to the excel spreadsheet. > Permission granted. You may click. (attempt at humor). Actually I don't know what you mean. From kent37 at tds.net Mon May 1 17:37:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 May 2006 11:37:43 -0400 Subject: [Tutor] Pyton and Webpages In-Reply-To: <20060501105745.l4pah7osg8gos40s@webmail.spamcop.net> References: <20060501105745.l4pah7osg8gos40s@webmail.spamcop.net> Message-ID: <44562B47.5040901@tds.net> Jon Whitehouse wrote: > Greetings All, > > I'm a newbie to python and am curious if I can do the following in python. I'm > not asking HOW to do this, just if it is possible before I spend the time to > learn python and do it myself. > > I want to write a program to go to a webpage, pull the data, and then place it > into an excel spreadsheet and then write it to an html file and allow me to > also click on the link to the excel spreadsheet. > > Is this possible to do with python? Yes. Some of the pieces you might use are urllib2 and BeautifulSoup to get the data from the web page win32com or pyexcelerator to write the Excel file http://docs.python.org/lib/module-urllib2.html http://www.crummy.com/software/BeautifulSoup/index.html http://starship.python.net/crew/mhammond/win32/ http://sourceforge.net/projects/pyexcelerator Kent From traviesomono at yahoo.es Mon May 1 18:56:58 2006 From: traviesomono at yahoo.es (Alfonso) Date: Mon, 01 May 2006 18:56:58 +0200 Subject: [Tutor] copying files and regular expressions Message-ID: <44563DDA.1060606@yahoo.es> I'm totally new to python. I would like to know, how can I copy files using regular expressions (the equivalent in python to unix "cp /home/mycount/*partialname* /home/mycount/directory/"). ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon May 1 21:07:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 1 May 2006 12:07:34 -0700 (PDT) Subject: [Tutor] copying files and regular expressions In-Reply-To: <44563DDA.1060606@yahoo.es> References: <44563DDA.1060606@yahoo.es> Message-ID: On Mon, 1 May 2006, Alfonso wrote: > I'm totally new to python. I would like to know, how can I copy files > using regular expressions (the equivalent in python to unix "cp > /home/mycount/*partialname* /home/mycount/directory/"). Hi Alfonso, Just as a pedantic note: the above pattern you're using isn't quite a regular expression, but something less powerful called a "glob". http://en.wikipedia.org/wiki/Glob Knowing the common names of things matters sometimes just because we communicate through the shared meanings of words. In this situation, it does help because it turns out there's a 'glob' module in Python's Standard Library: http://www.python.org/doc/lib/module-glob.html I'm not sure how familiar you are with using the Standard Library. Have you used modules before? The shell utilities defined in the 'shutil' module should also be helpful to let you copy files from one path to another: http://www.python.org/doc/lib/module-shutil.html Best of wishes to you! From SNelson at midway.com Tue May 2 03:06:11 2006 From: SNelson at midway.com (Nelson, Scott) Date: Mon, 1 May 2006 20:06:11 -0500 Subject: [Tutor] Pyton and Webpages Message-ID: <64F7B8E2954C73499806C1E59A848C1D09849708@CHICAGO-EX1.chicago.midway.com> WRT creating the Excel file... The previously mentioned techniques work great. But, if you want to start off even simpler, just create a .csv (comma separated value) file with python's file i/o (there is even a python module to help you with this if you want). It is just a simple text file that looks something like this: Name, Age, Hair Adam, 23, brown Don, 19, gray Biff, 42, blond Cathy, 35, red Gary, 99, none Excel handles these files just fine. You don't get all the fancy formatting, but this is a good first step. Good luck -Scott -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Monday, May 01, 2006 10:38 AM Cc: Tutor at python.org Subject: Re: [Tutor] Pyton and Webpages Jon Whitehouse wrote: > Greetings All, > > I'm a newbie to python and am curious if I can do the following in python. I'm > not asking HOW to do this, just if it is possible before I spend the time to > learn python and do it myself. > > I want to write a program to go to a webpage, pull the data, and then place it > into an excel spreadsheet and then write it to an html file and allow me to > also click on the link to the excel spreadsheet. > > Is this possible to do with python? Yes. Some of the pieces you might use are urllib2 and BeautifulSoup to get the data from the web page win32com or pyexcelerator to write the Excel file http://docs.python.org/lib/module-urllib2.html http://www.crummy.com/software/BeautifulSoup/index.html http://starship.python.net/crew/mhammond/win32/ http://sourceforge.net/projects/pyexcelerator Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From michel.maho at skynet.be Tue May 2 16:33:28 2006 From: michel.maho at skynet.be (michel maho) Date: Tue, 2 May 2006 16:33:28 +0200 Subject: [Tutor] decimal floating point? Message-ID: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> To all I have the following calculation: "Je Body Mass Index is",gewicht/lengte**2 The result is a (digital?)floating point figure with with 10 decimal numbers. For = example 27.2345678487 Did I mis something? I would like to reduce it to one or two decimal = numbers.(27.2) but round(_,1) does not work. Is there any other way? Thank You Michel Maho Sorry if this is a second mail. Something went wrong Michel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060502/c11185db/attachment.html From andreengels at gmail.com Tue May 2 16:46:57 2006 From: andreengels at gmail.com (Andre Engels) Date: Tue, 2 May 2006 16:46:57 +0200 Subject: [Tutor] decimal floating point? In-Reply-To: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> References: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> Message-ID: <6faf39c90605020746w65485235i8bb4507e37f207df@mail.gmail.com> 2006/5/2, michel maho : > > To all > I have the following calculation: > > "Je Body Mass Index is",gewicht/lengte**2 > > The result is a (digital?)floating point figure with with 10 decimal > numbers. For = > example 27.2345678487 > Did I mis something? I would like to reduce it to one or two decimal = > numbers.(27.2) but round(_,1) does not work. > Is there any other way? > Thank You > Michel Maho > Sorry if this is a second mail. > Something went wrong You can use string formatting here: "Je Body Mass Index is %.1f"%gewicht/lengte**2 The % inside the string says that one should format the thing following the % after the string here. ".2f" specifies how it should be formatted - f says that we will have a floating-point value, shown in decimal (not exponentional form), and the .1 means that there should be 1 digit after the decimal dot. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From andreengels at gmail.com Tue May 2 16:48:01 2006 From: andreengels at gmail.com (Andre Engels) Date: Tue, 2 May 2006 16:48:01 +0200 Subject: [Tutor] decimal floating point? In-Reply-To: <6faf39c90605020746w65485235i8bb4507e37f207df@mail.gmail.com> References: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> <6faf39c90605020746w65485235i8bb4507e37f207df@mail.gmail.com> Message-ID: <6faf39c90605020748m3a1c5bc3jce7205c59257e5d6@mail.gmail.com> > You can use string formatting here: > "Je Body Mass Index is %.1f"%gewicht/lengte**2 Actually, I'm not sure this word work correctly. Better: "Je Body Mass Index is %.1f"%(gewicht/lengte**2) that should definitely owrk -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From yi at yiqiang.net Tue May 2 16:46:19 2006 From: yi at yiqiang.net (Yi Qiang) Date: Tue, 02 May 2006 07:46:19 -0700 Subject: [Tutor] decimal floating point? In-Reply-To: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> References: <001e01c66df5$6147fa40$660aa8c0@LAPTOP> Message-ID: <445770BB.8050401@yiqiang.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 michel maho wrote, On 05/02/2006 07:33 AM: > To all > I have the following calculation: > > "Je Body Mass Index is",gewicht/lengte**2 > > The result is a (digital?)floating point figure with with 10 decimal numbers. For = > example 27.2345678487 > Did I mis something? I would like to reduce it to one or two decimal = > numbers.(27.2) but round(_,1) does not work. What exactly doesn't work? >>> n = 27.2345678487 >>> round(n) 27.0 >>> round(n, 2) 27.23 Yi -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEV3C7tXlIMrUVVksRAgBGAJ963EK8jkngIr53NNuT1e1NvoU97gCffslK W/+Q4+/A2hoq3VXC0pR3J+Y= =3RAJ -----END PGP SIGNATURE----- From john.ertl at fnmoc.navy.mil Tue May 2 20:30:56 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue, 2 May 2006 11:30:56 -0700 Subject: [Tutor] question about run time Message-ID: I have been using python for sometime...and occasionally I noticed significant delay before the code would run but unitl now I have been able to write it off to other things. Now I have a short script that I wrote to check some files and print out a few lines. I have noticed that usually the first time I fire it up in the morning or after a long time of not running it, it takes 10-15 seconds to run and the output to the screen is very slow...maybe 1 second per line. If I run it soon after that it runs and the output is on the screen in less then a second. I would think this has to do with compiling but I am not sure. Any ideas how to speed this up? I am running python 2.4 on a RHE3.0 cluster. Thanks, John Ertl From kent37 at tds.net Tue May 2 21:06:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 May 2006 15:06:14 -0400 Subject: [Tutor] question about run time In-Reply-To: References: Message-ID: <4457ADA6.5010602@tds.net> Ertl, John wrote: > I have been using python for sometime...and occasionally I noticed > significant delay before the code would run but unitl now I have been able > to write it off to other things. Now I have a short script that I wrote to > check some files and print out a few lines. > > I have noticed that usually the first time I fire it up in the morning or > after a long time of not running it, it takes 10-15 seconds to run and the > output to the screen is very slow...maybe 1 second per line. If I run it > soon after that it runs and the output is on the screen in less then a > second. I would think this has to do with compiling but I am not sure. Any > ideas how to speed this up? Compiling is not that slow. Are you files huge? Possibly they are in the disk cache after the first run. Kent From john.ertl at fnmoc.navy.mil Tue May 2 21:18:51 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue, 2 May 2006 12:18:51 -0700 Subject: [Tutor] question about run time Message-ID: Kent, The files are very small (a few hundred lines). Maybe it is a network issue? But then why is it always slow the first time in the morning? I don't know network stuff but that seams a bit strange. Thanks, John Ertl -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Tuesday, May 02, 2006 12:06 PM To: Ertl, John Cc: tutor at python.org Subject: Re: [Tutor] question about run time Ertl, John wrote: > I have been using python for sometime...and occasionally I noticed > significant delay before the code would run but unitl now I have been able > to write it off to other things. Now I have a short script that I wrote to > check some files and print out a few lines. > > I have noticed that usually the first time I fire it up in the morning or > after a long time of not running it, it takes 10-15 seconds to run and the > output to the screen is very slow...maybe 1 second per line. If I run it > soon after that it runs and the output is on the screen in less then a > second. I would think this has to do with compiling but I am not sure. Any > ideas how to speed this up? Compiling is not that slow. Are you files huge? Possibly they are in the disk cache after the first run. Kent From kent37 at tds.net Tue May 2 21:26:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 May 2006 15:26:46 -0400 Subject: [Tutor] question about run time In-Reply-To: References: Message-ID: <4457B276.60300@tds.net> Ertl, John wrote: > Kent, > > The files are very small (a few hundred lines). Maybe it is a network > issue? But then why is it always slow the first time in the morning? I > don't know network stuff but that seams a bit strange. Maybe the network access is slow and the files are cached locally after the first access? I think Windows does this... Some things you might want to try: - Open one of the files in a text editor. Close it and open it again. Is it faster the second time? - Write a simple python program to open one of the files and read it. Is it faster the second time you run it? HTH, I'm guessing here. I have definitely seen scripts that run faster the second time and attribute it to file caching somewhere...though I haven't seen such a significant difference as you. Kent > > Thanks, > > John Ertl > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Tuesday, May 02, 2006 12:06 PM > To: Ertl, John > Cc: tutor at python.org > Subject: Re: [Tutor] question about run time > > Ertl, John wrote: >> I have been using python for sometime...and occasionally I noticed >> significant delay before the code would run but unitl now I have been able >> to write it off to other things. Now I have a short script that I wrote > to >> check some files and print out a few lines. >> >> I have noticed that usually the first time I fire it up in the morning or >> after a long time of not running it, it takes 10-15 seconds to run and the >> output to the screen is very slow...maybe 1 second per line. If I run it >> soon after that it runs and the output is on the screen in less then a >> second. I would think this has to do with compiling but I am not sure. > Any >> ideas how to speed this up? > > Compiling is not that slow. Are you files huge? Possibly they are in the > disk cache after the first run. > > Kent > > > From john.ertl at fnmoc.navy.mil Tue May 2 21:32:34 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue, 2 May 2006 12:32:34 -0700 Subject: [Tutor] question about run time Message-ID: Kent, I will check with the systems guys...and the Perl guys down the hall to see if they have the same problem. Thanks for the help. John Ertl -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Tuesday, May 02, 2006 12:27 PM Cc: tutor at python.org Subject: Re: [Tutor] question about run time Ertl, John wrote: > Kent, > > The files are very small (a few hundred lines). Maybe it is a network > issue? But then why is it always slow the first time in the morning? I > don't know network stuff but that seams a bit strange. Maybe the network access is slow and the files are cached locally after the first access? I think Windows does this... Some things you might want to try: - Open one of the files in a text editor. Close it and open it again. Is it faster the second time? - Write a simple python program to open one of the files and read it. Is it faster the second time you run it? HTH, I'm guessing here. I have definitely seen scripts that run faster the second time and attribute it to file caching somewhere...though I haven't seen such a significant difference as you. Kent > > Thanks, > > John Ertl > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Tuesday, May 02, 2006 12:06 PM > To: Ertl, John > Cc: tutor at python.org > Subject: Re: [Tutor] question about run time > > Ertl, John wrote: >> I have been using python for sometime...and occasionally I noticed >> significant delay before the code would run but unitl now I have been able >> to write it off to other things. Now I have a short script that I wrote > to >> check some files and print out a few lines. >> >> I have noticed that usually the first time I fire it up in the morning or >> after a long time of not running it, it takes 10-15 seconds to run and the >> output to the screen is very slow...maybe 1 second per line. If I run it >> soon after that it runs and the output is on the screen in less then a >> second. I would think this has to do with compiling but I am not sure. > Any >> ideas how to speed this up? > > Compiling is not that slow. Are you files huge? Possibly they are in the > disk cache after the first run. > > Kent > > > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue May 2 22:31:59 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 May 2006 13:31:59 -0700 (PDT) Subject: [Tutor] question about run time In-Reply-To: References: Message-ID: > I have been using python for sometime...and occasionally I noticed > significant delay before the code would run but unitl now I have been > able to write it off to other things. Now I have a short script that I > wrote to check some files and print out a few lines. > > I have noticed that usually the first time I fire it up in the morning > or after a long time of not running it, it takes 10-15 seconds to run > and the output to the screen is very slow...maybe 1 second per line. > If I run it soon after that it runs and the output is on the screen in > less then a second. I would think this has to do with compiling but I > am not sure. Any ideas how to speed this up? > > I am running python 2.4 on a RHE3.0 cluster. ^^^^^^^^^^^^^^ Hi John, One thing to check is to see if the program is spending the majority of its time doing input and output (I/O Bound), or if it's really doing heavy computations (CPU bound). Knowing this might provide clues as to why you're seeing this kind of jerky performance. Also, you may want to check with your cluster folks on the possible effects the cluster's architecture may have on program startup. You're running on a slightly specialized platform, so I wouldn't be surprised if the cluster architecture is contributing something special. Finally, if you want to share that script for people to comment on, that might help. Good luck! From john.ertl at fnmoc.navy.mil Tue May 2 22:44:56 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue, 2 May 2006 13:44:56 -0700 Subject: [Tutor] question about run time Message-ID: Danny, What is the best way to track the time uses in I/O and CPU. Here is the code. It checks some text files for a user name and collects memory and inode usage then adds them together and checks against a set limit...if the limit is reached it calls a mail script to send an email warning. The program is used like a script with variables passed from the command line. (maybe I should just write this in bash?) import sys import time import glob import os.path import subprocess class memoryUsage: def __init__(self,userName,gpfs,emailAddress,memLimit=500000,inodeLimit=20000, searchMonth="None",searchDay="None",searchYear="None"): self.BASEDIR = "/GPFS/Usage" self.gpfs=gpfs.lower() self.emailAddress=emailAddress self.memLimit=memLimit self.inodeLimit=inodeLimit self.userName=userName self.searchMonth=searchMonth self.searchDay=searchDay self.searchYear=searchYear self.memTotal = 0 self.inodeTotal = 0 self.gpfsList = [] date = time.strftime("%b %d %Y") print "date =" ,date date = date.split() if self.searchMonth == "None": self.searchMonth=date[0] if self.searchDay == "None": self.searchDay = date[1] if self.searchYear == "None": self.searchYear = date[2] if emailAddress == "None": print "You must enter an email (-e)" print "ex. memoryCheck.py -n ertlj -g all -e j.e at fnmoc.navy.mil" sys.exit() def getGPFSList(self): ## if self.gpfs is set to all get all availabel otherwise just add the one asked for if self.gpfs == "all": self.gpfsPathList = glob.glob(self.BASEDIR +"/gpfs*") for each in self.gpfsPathList: (base,gpfs) = os.path.split(each) self.gpfsList.append(gpfs) else: self.gpfsList.append(self.gpfs) def makeFilePath(self,gpfs): ## make the full path to the file tha contans the memory and inode usage for each node self.filePath = os.path.join(self.BASEDIR,gpfs,self.searchYear, self.searchMonth,self.searchDay) def extractUserData(self): ## look in each file and search for the name...if found get the memory and inode usage ## and return them print self.filePath fullList = open(self.filePath,"r").readlines() for line in fullList: #print "line", line singleList = line.split() try: if singleList[1] == self.userName: print line return singleList[2],singleList[3] except: pass return 0,0 def add(self,memAmount,inodeAmount): self.memTotal = self.memTotal + int(memAmount) self.inodeTotal = self.inodeTotal + int(inodeAmount) def sendEmail(self,message): if self.emailAddress != "None": messagePath="/home/ertlj/localBin/blank" emailComand = "/u/curr/bin/smail.pl -f %s -t %s -s '%s'" % (messagePath,self.emailAddress,message) p = subprocess.Popen(emailComand, shell=True) self.sts = os.waitpid(p.pid, 0) else: sys.exit("No valid email address given...can not email size warning") if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-n", "--userName", default=os.getenv("LOGNAME","None"), help="The user name to look for") parser.add_option("-g", "--gpfs", default="all", help="Enter the gpfs you want to search or 'all'") parser.add_option("-e", "--email", default="None", help="The email the report if any will be sent to") parser.add_option("-l", "--memLimit", default=5000000, help="The memory size in KB that will triger a report") parser.add_option("-i", "--inodeLimit",default=50000, help="The inode size that will trigger a report") parser.add_option("-d", "--day", default="None", help="The day of the month you want to check") parser.add_option("-m", "--month",default="None" ,help="The month of the year you want to check") parser.add_option("-y", "--year",default="None", help="The year you want to check") (options, args) = parser.parse_args() myUse = memoryUsage(options.userName,options.gpfs,options.email,options.memLimit, options.inodeLimit,options.month,options.day,options.year) myUse.getGPFSList() for each in myUse.gpfsList: myUse.makeFilePath(each) (memAmount,inodeAmount) = myUse.extractUserData() myUse.add(memAmount,inodeAmount) print "Your memory usage is %s KB and your inode usage is %s" % (myUse.memTotal,myUse.inodeTotal) print "Your memory limit is %s KB and your inode limit is %s" % (myUse.memLimit, myUse.inodeLimit) if myUse.memLimit < myUse.memTotal or myUse.inodeLimit < myUse.inodeTotal: print "You have excedded your limit" myUse.sendEmail("%s memory/inode limit reached on gpfs " % myUse.userName) -----Original Message----- From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: Tuesday, May 02, 2006 1:32 PM To: Ertl, John Cc: tutor at python.org Subject: Re: [Tutor] question about run time > I have been using python for sometime...and occasionally I noticed > significant delay before the code would run but unitl now I have been > able to write it off to other things. Now I have a short script that I > wrote to check some files and print out a few lines. > > I have noticed that usually the first time I fire it up in the morning > or after a long time of not running it, it takes 10-15 seconds to run > and the output to the screen is very slow...maybe 1 second per line. > If I run it soon after that it runs and the output is on the screen in > less then a second. I would think this has to do with compiling but I > am not sure. Any ideas how to speed this up? > > I am running python 2.4 on a RHE3.0 cluster. ^^^^^^^^^^^^^^ Hi John, One thing to check is to see if the program is spending the majority of its time doing input and output (I/O Bound), or if it's really doing heavy computations (CPU bound). Knowing this might provide clues as to why you're seeing this kind of jerky performance. Also, you may want to check with your cluster folks on the possible effects the cluster's architecture may have on program startup. You're running on a slightly specialized platform, so I wouldn't be surprised if the cluster architecture is contributing something special. Finally, if you want to share that script for people to comment on, that might help. Good luck! From dyoo at hkn.eecs.berkeley.edu Tue May 2 23:49:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 May 2006 14:49:49 -0700 (PDT) Subject: [Tutor] question about run time In-Reply-To: References: Message-ID: Hi John, You can try something like the profiler, which will say where most of the program's time is being spent. We can find documentation on the Python profiler here: http://www.python.org/doc/lib/profile.html >From a rough, low-level standpoint, there are tools like 'top' on Linux that let you see if a program is idling. Another low-level program --- strace --- allows one to watch for system calls, and can be very useful for understanding the low-level performance of a program. http://www.liacs.nl/~wichert/strace/ I'm using Solaris on one of my systems, and it comes with a marvelous tool called 'dtrace': http://www.sun.com/bigadmin/content/dtrace/ So there are good tools for measuring performance from both a high-level and a low-level perspective, and we often need to jump betweeen these levels to understand program performance. Let's do some code review. > It checks some text files for a user name and collects memory and inode > usage then adds them together and checks against a set limit...if the > limit is reached it calls a mail script to send an email warning. >From a cursory look at your program, I see one place which seems to be the tight inner loop of your program, in extractUserData(). ##################################################### def extractUserData(self): print self.filePath fullList = open(self.filePath,"r").readlines() for line in fullList: #print "line", line singleList = line.split() try: if singleList[1] == self.userName: print line return singleList[2],singleList[3] except: pass return 0,0 ##################################################### This function is called in another loop in your main program, and it itself does lots of looping, so let's spend some time looking at this: I believe this will be worthwhile. One small improvement you might want to make here is to avoid reading in the whole file at once. That is, rather than: lines = open(filename).readlines() for line in lines: ... it's often better to do: myfile = open(filename) for line in myfile: ... This is a relatively minor detail, and a low-level one. But a bigger payoff can occur if we take a higher-level look at what's happening. From a high level, the premise of the program is that there's a set of text files. For any particular user, some auxiliary information (inode and memory usage.) is being stored in these files. This is really crying out to be a database. *grin* I don't know how much freedom you have to change things around, but if you can use a database to centralize all this information, that will be a very good thing. If we really must keep things this way, I'd strongly recommend that we reconsider doing all the file opening/reading/scanning in the inner loop. I suspect that doing all that file opening and linear scanning in the inner loop is what strongly influences the program's performance. This is certainly I/O bound, and we want to get I/O out of tight loops like this. Instead, we can do some preprocessing work up front. If we read all the records at the very beginning and store those records in an in-memory dictionary, then extractUserData() can be a very simple lookup rather than a filesystem-wide hunt. It's the conceptual difference between: ######################################################## ## Pseudocode; in reality, we'd strip line endings too ######################################################## while True: word = raw_input("enter a word") for other in open('/usr/share/dict/words'): if other == word: print "It's in" break ######################################################## vs: ######################################################### all_words = {} for word in open('/usr/share/dict/words'): all_words[word] = True while True: word = raw_input("enter a word") if word in all_words: print "It's in" ######################################################### The former opens and scans the file for each input we get. The latter does a bit of work up front, but it makes up for it if we go through the inner loop more than once. If we were to do a scan for words just once, the former might be preferable since it might not need to read the whole file to give an answer. But if we're going to do the scan for several people, the latter is probably the way to go. Good luck to you! From glingl at aon.at Wed May 3 00:24:18 2006 From: glingl at aon.at (Gregor Lingl) Date: Wed, 03 May 2006 00:24:18 +0200 Subject: [Tutor] simple question about numeric types Message-ID: <4457DC12.9090603@aon.at> Hi! Is there a simpler/fster way to check if a value has int or float type (i.e. is a "real number") than: v= if isinstance(v, int) or isinstance(v, float): (v must not be complex) Regards, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From john at fouhy.net Wed May 3 00:29:28 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 3 May 2006 10:29:28 +1200 Subject: [Tutor] simple question about numeric types In-Reply-To: <4457DC12.9090603@aon.at> References: <4457DC12.9090603@aon.at> Message-ID: <5e58f2e40605021529gc21b024p9417accbdb3bafb@mail.gmail.com> On 03/05/06, Gregor Lingl wrote: > Hi! > > Is there a simpler/fster way to check if a value > has int or float type (i.e. is a "real number") than: > > v= > if isinstance(v, int) or isinstance(v, float): > > > (v must not be complex) Well, for one, you can simplify that line to: if isinstance(v, (int, float)): (also, you might want to check if it's a long as well --- ie: isinstance(v, (int, float, long))) Another possibility, maybe: try: int(v) except ValueError, TypeError: pass -- John. From evans1018 at verizon.net Wed May 3 01:25:43 2006 From: evans1018 at verizon.net (MICHELLE EVANS) Date: Tue, 02 May 2006 19:25:43 -0400 Subject: [Tutor] counting number of inputs Message-ID: <002801c66e3f$bc3012e0$e1966147@michelleevans> I am trying to count the number of times a positive number is entered from the user. But, the program must stop after 5 user inputs or a negative number. Can anyone help. Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060502/f2227ddb/attachment.htm From python at venix.com Wed May 3 01:56:41 2006 From: python at venix.com (Python) Date: Tue, 02 May 2006 19:56:41 -0400 Subject: [Tutor] counting number of inputs In-Reply-To: <002801c66e3f$bc3012e0$e1966147@michelleevans> References: <002801c66e3f$bc3012e0$e1966147@michelleevans> Message-ID: <1146614201.20702.338.camel@www.venix.com> On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > I am trying to count the number of times a positive number is entered > from the user. But, the program must stop after 5 user inputs or a > negative number. > > Can anyone help. Yes, but you need to help yourself also. Do you know how to get input from the user? Do you know how to count things in Python? Do you know how to test a number to see if it is positive or negative? Why don't you post your code for any part of this problem and explain how it is supposed to work and where you are having difficulty. If necessary, review some of the tutorials to get some pointers on writing Python programs. We're happy to help you learn, but do not want to simply write your program for you. > Rick > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Wed May 3 02:08:42 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 2 May 2006 17:08:42 -0700 (PDT) Subject: [Tutor] counting number of inputs In-Reply-To: <002801c66e3f$bc3012e0$e1966147@michelleevans> References: <002801c66e3f$bc3012e0$e1966147@michelleevans> Message-ID: On Tue, 2 May 2006, MICHELLE EVANS wrote: > I am trying to count the number of times a positive number is entered > from the user. But, the program must stop after 5 user inputs or a > negative number. That seems like a really arbitrary and silly thing to do, but ok. So... what question do you have? Have you had a chance to go through a tutorial, like the ones listed in: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers If so, what kinds of programs have you done already? Do any of them have any similaries to the problem you're working on now? From oztriking at hotmail.com Wed May 3 09:57:37 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 03 May 2006 17:57:37 +1000 Subject: [Tutor] Books Message-ID: G'day, I know this is a difficult question to answer because it's probably more a matter of personal taste than anything else. I'm retired so money has to be watched fairly carefully and books are kind of expensive down here in Australia but the Mrs has said I can lash out on a book for my birthday. So I was wondering (bearing in mimd that I'm only 2 or 3 steps above total beginner), what is the one book on python that I shouldn't be without? John _________________________________________________________________ realestate.com.au: the biggest address in property http://ninemsn.realestate.com.au From sanelson at gmail.com Wed May 3 11:49:37 2006 From: sanelson at gmail.com (Steve Nelson) Date: Wed, 3 May 2006 10:49:37 +0100 Subject: [Tutor] Books In-Reply-To: References: Message-ID: On 5/3/06, John Connors wrote: > G'day, > > I know this is a difficult question to answer because it's probably more a > matter of personal taste than anything else. It is also a VFAQ. Check the archives - I'm not aware of any radical new books that would render the most recent incarnation of this subject outdated. S. From igor at c-base.org Wed May 3 14:00:13 2006 From: igor at c-base.org (Igor) Date: Wed, 3 May 2006 14:00:13 +0200 Subject: [Tutor] Bitten by lexical closures Message-ID: <20060503140013.0e0e3b27@valkyr.wg> Hi. And I thought I understood python pretty well. Until I got hit by this: >>> def f(x): ... print x >>> cb = [lambda :f(what) for what in "1234"] >>> for c in cb:c() 4 4 4 4 And even this works >>> what = "foo" >>> for c in cb:c() foo foo foo foo I expected the output to be 1 2 3 4. Now I understand the cookbook recipe for currying: def curry(func, *args, **kwds): def callit(*moreargs, **morekwds): kw = kwds.copy() kw.update(morekwds) return func(*(args+moreargs), **kw) return callit cb = [curry(f,what) for what in "1234"] gives the right functions. Regards, Igor From oasf2004 at yahoo.com Wed May 3 15:10:35 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 3 May 2006 06:10:35 -0700 (PDT) Subject: [Tutor] Books In-Reply-To: Message-ID: <20060503131035.36018.qmail@web60016.mail.yahoo.com> --- John Connors wrote: > G'day, > > I know this is a difficult question to answer > because it's probably more a > matter of personal taste than anything else. > > I'm retired so money has to be watched fairly > carefully and books are kind > of expensive down here in Australia but the Mrs has > said I can lash out on a > book for my birthday. So I was wondering (bearing in > mimd that I'm only 2 or > 3 steps above total beginner), what is the one book > on python that I > shouldn't be without? > > John > > Hi John, I would suggest you: "Beginning Python: From Novice to Professional", by Magnus Lie Hetland Publisher: Apress (September 26, 2005) ISBN: 159059519X In my opinion, this is the best and the most up-to-date Python book for beginner/intermediate available. I am studying Python by myself with this book, and I am enjoying it a lot. I hope this help. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From wescpy at gmail.com Wed May 3 17:07:45 2006 From: wescpy at gmail.com (w chun) Date: Wed, 3 May 2006 08:07:45 -0700 Subject: [Tutor] ANN: 2006 Python training May/Aug/Nov, San Francisco Message-ID: <78b3a9580605030807u7c9ad20cu5c6d0af80414cdeb@mail.gmail.com> *** 50% DISCOUNT to STUDENTS/TEACHERS *** Dear fellow list members, Below is the announcement we've just made this morning about our upcoming advanced Python course, May 17-19, 2006. This advanced course will be offered again in Nov 2006. In Aug 2006, we will have another intensive introduction to Python course. Please forward this msg to anyone whom you think would be interested or would benefit from Python training courses. This includes Plone, Zope, and Mailman groups as well. http://mail.python.org/pipermail/python-list/2006-May/339577.html We apologize in advance if you feel this is a commercial and off-topic message. We limit such correspondence to once every few months. Trying to help Python take over the world.... -Wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From francis.moore at rawflow.com Wed May 3 17:16:45 2006 From: francis.moore at rawflow.com (Frank Moore) Date: Wed, 03 May 2006 16:16:45 +0100 Subject: [Tutor] HTML encoding of character sets... Message-ID: <4458C95D.3040300@rawflow.com> Hi, I need to do some encoding of text that will be used in a web page. The text has been translated into 16 different languages. I've managed the manual translation of some of the more regular languages (French, Spanish, Italian etc...) , by replacing characters like '?' with the numeric entity á etc... This works when you only have a few characters like this in the text and they visually stand out. However, I now have to move on to other languages like Arabic, Russian, Chinese, Hebrew, Japanese, Korean, Hindi and Polish. In these languages, the sheer volume of characters that need to be encoded is huge. For instance, the following text is a title on a web page (in Russian), asking the user to wait for the page to load: ???? ????????, ??????????, ?????????? It obviously looks like garbage unless you have your email reader set to a Russian text encoding. But even if it appears correctly, the sheer number of characters that I will need to numerically encode is massive. Does anyone know how I can automate this process? I want to be able to read a string out of a translation file, pass it to a Python script and get back a list or string of numeric entities that I can then bury in my HTML. I had a play with a snippet of code from the Unicode chapter of 'Dive Into Python' (http://diveintopython.org/xml_processing/unicode.html) but get the following error: text = open('russian.txt', 'r').read() converted_text = text.encode('koi8-r') Traceback (most recent call last): File "", line 1, in ? File "c:\Python24\lib\encodings\koi8_r.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: ordinal not in range(128) Anybody got any ideas? Many thanks, Frank. From evans1018 at verizon.net Wed May 3 17:46:25 2006 From: evans1018 at verizon.net (MICHELLE EVANS) Date: Wed, 03 May 2006 11:46:25 -0400 Subject: [Tutor] Fw: counting number of inputs Message-ID: <003101c66ec8$bd162ee0$e1966147@michelleevans> This is what I have so far. Can anyone help? > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > number5 = int(raw_input("Run number 5 (-1 to end) : ")) > > > # The following will sum the numbers and then print the answer > sum = number1 + number2 + number3 + number4 + number5 > print > print "The total number of parts produced was:", sum,"." > > I need this to ask the user to enter their number per each run. That is why > I have 5 different input numbers. I need this break if a -1 is entered. > Would I use "if-else" to break this if -1 is entered? I need to be able to > count the number of lines entered. I also need to print the run number with the highest and lowest input number. > > Thanks, I'm lost > Rick > ----- Original Message ----- From: MICHELLE EVANS To: tutor at python.org Sent: Tuesday, May 02, 2006 7:25 PM Subject: counting number of inputs I am trying to count the number of times a positive number is entered from the user. But, the program must stop after 5 user inputs or a negative number. Can anyone help. Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060503/a40a20af/attachment.htm From python at venix.com Wed May 3 18:07:46 2006 From: python at venix.com (Python) Date: Wed, 03 May 2006 12:07:46 -0400 Subject: [Tutor] counting number of inputs In-Reply-To: <006501c66e51$ae869620$e1966147@michelleevans> References: <002801c66e3f$bc3012e0$e1966147@michelleevans> <1146614201.20702.338.camel@www.venix.com> <006501c66e51$ae869620$e1966147@michelleevans> Message-ID: <1146672466.20702.394.camel@www.venix.com> (Tip: Best to use reply-to-all when responding to an email on the list) On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > number5 = int(raw_input("Run number 5 (-1 to end) : ")) Good. You collect the string from raw_input and convert it to an integer. This will prompt for 5 inputs, but it is missing any logic to actually break if -1 is entered. With a language like BASIC, you could stick in tests sort of like: if number1 == -1 goto done: BUT Python does not have a goto. So we actually need some "flow control" around the block of code where you collect inputs. while blocks process an indefinite number of times while a test condition is True. for blocks iterate through a sequence until they reach the end. By providing a sequence with the correct count, you can repeat the block the correct number of times. The range (and xrange for big sequences) functions provide a sequence of integers that can be used conveniently with for. The easiest way to fix your code above would be something like: ask_for_number = True while ask_for_number: > > > # The following will sum the numbers and then print the answer > sum = number1 + number2 + number3 + number4 + number5 > print > print "The total number of parts produced was:", sum,"." > > I need this to ask the user to enter their number per each run. That is why > I have 5 different input numbers. I need this break if a -1 is entered. > Would I use "if-else" to break this if -1 is entered? I need to be able to > count the number of lines entered. > > Thanks > Rick > > > ----- Original Message ----- > From: "Python" > To: "MICHELLE EVANS" > Cc: "Tutor Python" > Sent: Tuesday, May 02, 2006 7:56 PM > Subject: Re: [Tutor] counting number of inputs > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > I am trying to count the number of times a positive number is entered > > > from the user. But, the program must stop after 5 user inputs or a > > > negative number. > > > > > > Can anyone help. > > Yes, but you need to help yourself also. > > > > Do you know how to get input from the user? > > Do you know how to count things in Python? > > Do you know how to test a number to see if it is positive or negative? > > > > Why don't you post your code for any part of this problem and explain > > how it is supposed to work and where you are having difficulty. If > > necessary, review some of the tutorials to get some pointers on writing > > Python programs. > > > > We're happy to help you learn, but do not want to simply write your > > program for you. > > > > > Rick > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- > > Lloyd Kvam > > Venix Corp > > > > > -- Lloyd Kvam Venix Corp From python at venix.com Wed May 3 18:18:41 2006 From: python at venix.com (Python) Date: Wed, 03 May 2006 12:18:41 -0400 Subject: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) In-Reply-To: <006501c66e51$ae869620$e1966147@michelleevans> References: <002801c66e3f$bc3012e0$e1966147@michelleevans> <1146614201.20702.338.camel@www.venix.com> <006501c66e51$ae869620$e1966147@michelleevans> Message-ID: <1146673121.20702.403.camel@www.venix.com> (Tip: Best to use reply-to-all when responding to an email on the list) On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > number5 = int(raw_input("Run number 5 (-1 to end) : ")) Good. You collect the string from raw_input and convert it to an integer. This will prompt for 5 inputs, but it is missing any logic to actually break if -1 is entered. With a language like BASIC, you could stick in tests sort of like: if number1 == -1 goto done: BUT Python does not have a goto. So we actually need some "flow control" around the block of code where you collect inputs. while blocks process an indefinite number of times while a test condition is True. for blocks iterate through a sequence until they reach the end. By providing a sequence with the correct count, you can repeat the block the correct number of times. The range (and xrange for big sequences) functions provide a sequence of integers that can be used conveniently with for. The easiest way to fix your code above would be something like: ask_for_number = True while ask_for_number: number1 = .... if number1 == -1: break ... number5 = ... ask_for_number = False HOWEVER, that is not a good approach in the long run. A better approach is to have a single container to hold all of the inputs. For this, Python provides lists. Rather than have 5 separate variables, use a single list variable to hold all of the inputs. Then use a "for block" to ask for the input and put the result into the list. You already know how to convert the input from a string to a number. If you have trouble figuring out lists and for blocks, ask for help. (Sorry about the extra email. I forgot and used ad editor hot-key combo in my email program which sent the email.) > > > # The following will sum the numbers and then print the answer > sum = number1 + number2 + number3 + number4 + number5 > print > print "The total number of parts produced was:", sum,"." > > I need this to ask the user to enter their number per each run. That is why > I have 5 different input numbers. I need this break if a -1 is entered. > Would I use "if-else" to break this if -1 is entered? I need to be able to > count the number of lines entered. > > Thanks > Rick > > > ----- Original Message ----- > From: "Python" > To: "MICHELLE EVANS" > Cc: "Tutor Python" > Sent: Tuesday, May 02, 2006 7:56 PM > Subject: Re: [Tutor] counting number of inputs > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > I am trying to count the number of times a positive number is entered > > > from the user. But, the program must stop after 5 user inputs or a > > > negative number. > > > > > > Can anyone help. > > Yes, but you need to help yourself also. > > > > Do you know how to get input from the user? > > Do you know how to count things in Python? > > Do you know how to test a number to see if it is positive or negative? > > > > Why don't you post your code for any part of this problem and explain > > how it is supposed to work and where you are having difficulty. If > > necessary, review some of the tutorials to get some pointers on writing > > Python programs. > > > > We're happy to help you learn, but do not want to simply write your > > program for you. > > > > > Rick > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- > > Lloyd Kvam > > Venix Corp > > > > > -- Lloyd Kvam Venix Corp From Barry.Carroll at psc.com Wed May 3 18:30:55 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 3 May 2006 09:30:55 -0700 Subject: [Tutor] Books Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C367F@eugsrv400.psc.pscnet.com> Greetings, John, For my money, that book is: Learning Python, 2nd Edition By David Ascher, Mark Lutz Publisher: O'Reilly Pub Date: December 2003 ISBN: 0-596-00281-5 Pages: 620 $25.19 new, 18.47 used (+ shipping) From amazon.com I taught myself Python with this book, and I still use it nearly every day. BTW, there are several excellent tutorials for free online, but you asked about books :^) Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Wed, 03 May 2006 17:57:37 +1000 > From: "John Connors" > Subject: [Tutor] Books > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed > > G'day, > > I know this is a difficult question to answer because it's probably more a > matter of personal taste than anything else. > > I'm retired so money has to be watched fairly carefully and books are kind > of expensive down here in Australia but the Mrs has said I can lash out on > a > book for my birthday. So I was wondering (bearing in mimd that I'm only 2 > or > 3 steps above total beginner), what is the one book on python that I > shouldn't be without? > > John > > _________________________________________________________________ > realestate.com.au: the biggest address in property > http://ninemsn.realestate.com.au > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 27, Issue 4 > ************************************ From flaxeater at gmail.com Wed May 3 18:34:49 2006 From: flaxeater at gmail.com (Chad Crabtree) Date: Wed, 3 May 2006 12:34:49 -0400 Subject: [Tutor] Books In-Reply-To: References: Message-ID: <584940990605030934u4c6e2362j2d2aedf4325822e0@mail.gmail.com> I have learend a great deal of python, and I have never bought a book. All the information one really needs is available freely on the internet. As long as you understand the basic data types you should be able to piece together what you need from the internet. From m_webber_sydney at yahoo.com.au Wed May 3 18:35:04 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Wed, 3 May 2006 17:35:04 +0100 Subject: [Tutor] Halting execution In-Reply-To: <003101c66ec8$bd162ee0$e1966147@michelleevans> Message-ID: <003d01c66ecf$88725e00$0200a8c0@kookaburra> This has got to be trivial, but I can't find the answer ... I want to stop execution of my main script half way through. This is just for debugging - the code in the bottom half of the script generates a whole lot of output that I don't want. Inserting "break" or "return" doesn't work, but something like that is what I had in mind. I'm running under ipython on windows, FWIW. Thanks From john.ertl at fnmoc.navy.mil Wed May 3 19:09:31 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 3 May 2006 10:09:31 -0700 Subject: [Tutor] Halting execution Message-ID: Matthew, Not sure if ipython is different but have you tried sys.exit("stoping now") You could also put in a flag to turn the printing on and off so it wont print it out when you are testing. John -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Matthew Webber Sent: Wednesday, May 03, 2006 9:35 AM To: tutor at python.org Subject: [Tutor] Halting execution This has got to be trivial, but I can't find the answer ... I want to stop execution of my main script half way through. This is just for debugging - the code in the bottom half of the script generates a whole lot of output that I don't want. Inserting "break" or "return" doesn't work, but something like that is what I had in mind. I'm running under ipython on windows, FWIW. Thanks _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From jason.massey at gmail.com Wed May 3 19:10:24 2006 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 3 May 2006 12:10:24 -0500 Subject: [Tutor] Halting execution In-Reply-To: <003d01c66ecf$88725e00$0200a8c0@kookaburra> References: <003101c66ec8$bd162ee0$e1966147@michelleevans> <003d01c66ecf$88725e00$0200a8c0@kookaburra> Message-ID: <7e3eab2c0605031010k2d94117fm98df218dc1b5f421@mail.gmail.com> How about: import sys sys.exit() On 5/3/06, Matthew Webber wrote: > > This has got to be trivial, but I can't find the answer ... I want to stop > execution of my main script half way through. This is just for debugging - > the code in the bottom half of the script generates a whole lot of output > that I don't want. Inserting "break" or "return" doesn't work, but > something > like that is what I had in mind. > > I'm running under ipython on windows, FWIW. > > Thanks > > _______________________________________________ > 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/20060503/0c7018a9/attachment.htm From mwhite3 at ttsd.k12.or.us Wed May 3 19:14:55 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 3 May 2006 10:14:55 -0700 Subject: [Tutor] Halting execution In-Reply-To: <003d01c66ecf$88725e00$0200a8c0@kookaburra> References: <003101c66ec8$bd162ee0$e1966147@michelleevans> <003d01c66ecf$88725e00$0200a8c0@kookaburra> Message-ID: <20060503171455.GA11991@ttsd.k12.or.us> Matthew, sys.exit() is one way to do it. Or you could use a conditional to toggle printing the output. -mtw On Wed, May 03, 2006 at 05:35:04PM +0100, Matthew Webber (m_webber_sydney at yahoo.com.au) wrote: > This has got to be trivial, but I can't find the answer ... I want to stop > execution of my main script half way through. This is just for debugging - > the code in the bottom half of the script generates a whole lot of output > that I don't want. Inserting "break" or "return" doesn't work, but something > like that is what I had in mind. > > I'm running under ipython on windows, FWIW. > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From kent37 at tds.net Wed May 3 19:15:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 May 2006 13:15:43 -0400 Subject: [Tutor] HTML encoding of character sets... In-Reply-To: <4458C95D.3040300@rawflow.com> References: <4458C95D.3040300@rawflow.com> Message-ID: <4458E53F.3020708@tds.net> Hi Frank, A couple of questions / issues here. Not really an answer, but hopefully a start in the right direction. Why do you need to use entity escapes at all? If you have a correct charset declaration you can use whatever encoding you like for the web page - latin-1, koi8-r, shift-jis, etc. If you pick utf-8 for the encoding, you can use it for all your pages rather than using a different encoding for each language. The string you read with open('russian.txt', 'r').read() is already encoded in the encoding used by the file 'russian.txt'. It is critical that you know this encoding. You can convert encoded text to Unicode with text.decode('koi8-r') etc. decode() goes to Unicode, encode() goes away from Unicode. Once you have Unicode text you can encode it to whatever encoding you want. Or you can use the codepoint2name dictionary in the htmlentitydefs module to convert to entities. This recipe shows one way to do it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440563 HTH Kent Frank Moore wrote: > Hi, > > I need to do some encoding of text that will be used in a web page. > The text has been translated into 16 different languages. > I've managed the manual translation of some of the more regular > languages (French, Spanish, Italian etc...) , by > replacing characters like '?' with the numeric entity á etc... > This works when you only have a few characters like this in the text and > they visually stand out. > However, I now have to move on to other languages like Arabic, Russian, > Chinese, Hebrew, Japanese, Korean, Hindi and Polish. > In these languages, the sheer volume of characters that need to be > encoded is huge. > For instance, the following text is a title on a web page (in Russian), > asking the user to wait for the page to load: > > ???? ????????, ??????????, ?????????? > > It obviously looks like garbage unless you have your email reader set to > a Russian text encoding. > But even if it appears correctly, the sheer number of characters that I > will need to numerically encode is massive. > > Does anyone know how I can automate this process? > I want to be able to read a string out of a translation file, pass it to > a Python script and get back a list or string of numeric entities > that I can then bury in my HTML. > > I had a play with a snippet of code from the Unicode chapter of 'Dive > Into Python' (http://diveintopython.org/xml_processing/unicode.html) > but get the following error: > > text = open('russian.txt', 'r').read() > converted_text = text.encode('koi8-r') > Traceback (most recent call last): > File "", line 1, in ? > File "c:\Python24\lib\encodings\koi8_r.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: > ordinal not in range(128) > > Anybody got any ideas? > > Many thanks, > Frank. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From flaxeater at gmail.com Wed May 3 20:24:45 2006 From: flaxeater at gmail.com (Chad Crabtree) Date: Wed, 3 May 2006 14:24:45 -0400 Subject: [Tutor] Bitten by lexical closures In-Reply-To: <20060503140013.0e0e3b27@valkyr.wg> References: <20060503140013.0e0e3b27@valkyr.wg> Message-ID: <584940990605031124r44bad075u26ca86b1a0e7d994@mail.gmail.com> Are you just trying to make a continuation? On 5/3/06, Igor wrote: > Hi. > > And I thought I understood python pretty well. Until I got hit by this: > > >>> def f(x): > ... print x > > >>> cb = [lambda :f(what) for what in "1234"] > >>> for c in cb:c() > 4 > 4 > 4 > 4 > > And even this works > > >>> what = "foo" > >>> for c in cb:c() > foo > foo > foo > foo > > I expected the output to be 1 2 3 4. Now I understand the cookbook > recipe for currying: > def curry(func, *args, **kwds): > def callit(*moreargs, **morekwds): > kw = kwds.copy() > kw.update(morekwds) > return func(*(args+moreargs), **kw) > return callit > > cb = [curry(f,what) for what in "1234"] > > gives the right functions. > > Regards, > Igor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From python at venix.com Wed May 3 20:49:30 2006 From: python at venix.com (Python) Date: Wed, 03 May 2006 14:49:30 -0400 Subject: [Tutor] Bitten by lexical closures In-Reply-To: <20060503140013.0e0e3b27@valkyr.wg> References: <20060503140013.0e0e3b27@valkyr.wg> Message-ID: <1146682170.20702.412.camel@www.venix.com> On Wed, 2006-05-03 at 14:00 +0200, Igor wrote: > Hi. > > And I thought I understood python pretty well. Until I got hit by this: > > >>> def f(x): > ... print x > > >>> cb = [lambda :f(what) for what in "1234"] > >>> for c in cb:c() > 4 > 4 > 4 > 4 >>> cb = [(lambda x=what:f(x)) for what in "1234"] >>> cb[0]() 1 A variable from the enclosing scope is normally only evaluated when used, that is when the closure is called. To capture a "transient" value, you need to explicitly pass it into the closure. I've gotten burned on this more than once. (snipped) > Regards, > Igor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 -- Lloyd Kvam Venix Corp From kent37 at tds.net Wed May 3 21:00:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 May 2006 15:00:02 -0400 Subject: [Tutor] Bitten by lexical closures In-Reply-To: <20060503140013.0e0e3b27@valkyr.wg> References: <20060503140013.0e0e3b27@valkyr.wg> Message-ID: <4458FDB2.5070404@tds.net> Igor wrote: > Hi. > > And I thought I understood python pretty well. Until I got hit by this: > >>>> def f(x): > ... print x > >>>> cb = [lambda :f(what) for what in "1234"] >>>> for c in cb:c() > 4 > 4 > 4 > 4 You haven't actually created a closure because you don't have any nested scopes, you have global scope and the scope of the lambda function. A list comprehension doesn't introduce a new scope. Your list comp changes the value of the global what. Here is a simpler version of what you are doing that is not so mysterious: In [8]: what = 3 In [9]: def f(x): ...: print x ...: ...: In [10]: def anon(): ....: f(what) ....: ....: In [11]: anon() 3 In [12]: what = 4 In [13]: anon() 4 Here it is pretty obvious that anon() is referring to the global what, and no surprise that changing what changes the value printed by anon(). There is actually a gotcha here and maybe the code you show is a simplified version of some real code that trips over it. The problem is that the value in a closure is the value that a variable has when the scope creating the closure is exited, not the value when the closure is created. So even if your list comp is in a function (and thus a true closure) you will see the same result: In [14]: def makefuncs(): ....: return [lambda :f(who) for who in "1234"] ....: In [15]: for func in makefuncs(): func() ....: 4 4 4 4 Each function sees the value that who had when makefuncs exited. There are two ways to work around this. One is to use a default argument to the lambda to bind the value, rather than depending on the closure. This would work for your version as well: In [16]: cb = [lambda what=what:f(what) for what in "1234"] In [17]: for c in cb:c() ....: 1 2 3 4 Another way to do it is to make a factory function that creates a single function, and call that in the list comp. Then each value is bound in a separate closure: In [18]: def makefunc(what): ....: return lambda : f(what) ....: In [19]: cb = [makefunc(what) for what in "1234"] In [20]: for c in cb:c() ....: 1 2 3 4 Kent From dyoo at hkn.eecs.berkeley.edu Wed May 3 21:04:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 3 May 2006 12:04:54 -0700 (PDT) Subject: [Tutor] Bitten by lexical closures In-Reply-To: <20060503140013.0e0e3b27@valkyr.wg> References: <20060503140013.0e0e3b27@valkyr.wg> Message-ID: On Wed, 3 May 2006, Igor wrote: > And I thought I understood python pretty well. Until I got hit by this: > >>>> def f(x): > ... print x > >>>> cb = [lambda :f(what) for what in "1234"] >>>> for c in cb:c() > 4 > 4 > 4 > 4 Hi Igor, I think you're getting caught by something that isn't quite related to closures really, but with the way Python does for loops (or assignment, for that matter.) Take a look at the following example: ###### >>> import sys >>> def sequence_function(seq): ... x = [None] ... results = [] ... for s in seq: ... x[0] = s ... results.append(lambda: sys.stdout.write("hello %s" % x[0])) ... return results ... ###### Try it out; does it behave in an expected way to you? If so, compare it against what you had earlier. The core of the problem is that Python's for loop mutates 's', so that all the newly defined functions refer to the same s. Best of wishes! From hugonz-lists at h-lab.net Wed May 3 21:04:44 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 03 May 2006 13:04:44 -0600 Subject: [Tutor] Halting execution In-Reply-To: References: Message-ID: <4458FECC.2060301@h-lab.net> It would be similar to Perl's die() commmand. But no, in Python the argument is the error status of your script. You'd have to do something like def exitnow(arg): print arg #maybe sys has not been imported import sys sys.exit(1) Hugo Ertl, John wrote: > Matthew, > > Not sure if ipython is different but have you tried sys.exit("stoping now") > From john.ertl at fnmoc.navy.mil Wed May 3 21:19:02 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 3 May 2006 12:19:02 -0700 Subject: [Tutor] Halting execution Message-ID: For this case, just wanting to stop the code for testing, using a short statement as the arg is not only OK it is an example in the doc. exit( [arg]) Exit from Python. ...... In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. I agree I should be a bit more careful about giving examples that are quick fixes as opposed to best practice. John -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Hugo Gonz?lez Monteverde Sent: Wednesday, May 03, 2006 12:05 PM To: tutor at python.org Subject: Re: [Tutor] Halting execution It would be similar to Perl's die() commmand. But no, in Python the argument is the error status of your script. You'd have to do something like def exitnow(arg): print arg #maybe sys has not been imported import sys sys.exit(1) Hugo Ertl, John wrote: > Matthew, > > Not sure if ipython is different but have you tried sys.exit("stoping now") > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From evans1018 at verizon.net Wed May 3 21:33:54 2006 From: evans1018 at verizon.net (MICHELLE EVANS) Date: Wed, 03 May 2006 15:33:54 -0400 Subject: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) References: <002801c66e3f$bc3012e0$e1966147@michelleevans> <1146614201.20702.338.camel@www.venix.com> <006501c66e51$ae869620$e1966147@michelleevans> <1146673121.20702.403.camel@www.venix.com> Message-ID: <006e01c66ee8$8441a340$e1966147@michelleevans> OK, I've tried a different approach to this. How do I get this to stop by using -1? I do not want this to print until either 5 inputs have been entered or -1 has been entered. See below: # Add number of per hour numbers = [] stop = None while stop != "-1": number = int(raw_input("Run number(-1 to end) : ")) numbers.append(number) print for number in numbers: print number ----- Original Message ----- From: "Python" To: "MICHELLE EVANS" Cc: "Tutor Python" Sent: Wednesday, May 03, 2006 12:18 PM Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) > (Tip: Best to use reply-to-all when responding to an email on the list) > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > > number5 = int(raw_input("Run number 5 (-1 to end) : ")) > Good. You collect the string from raw_input and convert it to an > integer. > > This will prompt for 5 inputs, but it is missing any logic to actually > break if -1 is entered. With a language like BASIC, you could stick in > tests sort of like: > if number1 == -1 goto done: > BUT Python does not have a goto. So we actually need some "flow > control" around the block of code where you collect inputs. > > while blocks process an indefinite number of times while a test > condition is True. > > for blocks iterate through a sequence until they reach the end. By > providing a sequence with the correct count, you can repeat the block > the correct number of times. The range (and xrange for big sequences) > functions provide a sequence of integers that can be used conveniently > with for. > > The easiest way to fix your code above would be something like: > ask_for_number = True > while ask_for_number: > number1 = .... > if number1 == -1: break > ... > number5 = ... > ask_for_number = False > > HOWEVER, that is not a good approach in the long run. > > A better approach is to have a single container to hold all of the > inputs. For this, Python provides lists. Rather than have 5 separate > variables, use a single list variable to hold all of the inputs. Then > use a "for block" to ask for the input and put the result into the list. > You already know how to convert the input from a string to a number. > > If you have trouble figuring out lists and for blocks, ask for help. > > (Sorry about the extra email. I forgot and used ad editor hot-key combo > in my email program which sent the email.) > > > > > > > > # The following will sum the numbers and then print the answer > > sum = number1 + number2 + number3 + number4 + number5 > > print > > print "The total number of parts produced was:", sum,"." > > > > I need this to ask the user to enter their number per each run. That is why > > I have 5 different input numbers. I need this break if a -1 is entered. > > Would I use "if-else" to break this if -1 is entered? I need to be able to > > count the number of lines entered. > > > > Thanks > > Rick > > > > > > ----- Original Message ----- > > From: "Python" > > To: "MICHELLE EVANS" > > Cc: "Tutor Python" > > Sent: Tuesday, May 02, 2006 7:56 PM > > Subject: Re: [Tutor] counting number of inputs > > > > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > > I am trying to count the number of times a positive number is entered > > > > from the user. But, the program must stop after 5 user inputs or a > > > > negative number. > > > > > > > > Can anyone help. > > > Yes, but you need to help yourself also. > > > > > > Do you know how to get input from the user? > > > Do you know how to count things in Python? > > > Do you know how to test a number to see if it is positive or negative? > > > > > > Why don't you post your code for any part of this problem and explain > > > how it is supposed to work and where you are having difficulty. If > > > necessary, review some of the tutorials to get some pointers on writing > > > Python programs. > > > > > > We're happy to help you learn, but do not want to simply write your > > > program for you. > > > > > > > Rick > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > -- > > > Lloyd Kvam > > > Venix Corp > > > > > > > > > -- > Lloyd Kvam > Venix Corp > > From hugonz-lists at h-lab.net Wed May 3 21:51:30 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 03 May 2006 13:51:30 -0600 Subject: [Tutor] question about run time In-Reply-To: References: Message-ID: <445909C2.9060006@h-lab.net> I have made scripts that work on many files (sometimes just some tens) and appears that filesystem structure caching in Linux is very efficient. That's why it runs very fast later. I've seen this in Slackware, Debian, and RH, so I guess it's just a linux/FS/disk thing. Try doing 'find' combined with md5sum or something disk-intensive, but unrelated with python to see if it exhibits the same problem. Hugo Ertl, John wrote: > I have been using python for sometime...and occasionally I noticed > significant delay before the code would run but unitl now I have been able > to write it off to other things. Now I have a short script that I wrote to > check some files and print out a few lines. > > I have noticed that usually the first time I fire it up in the morning or > after a long time of not running it, it takes 10-15 seconds to run and the > output to the screen is very slow...maybe 1 second per line. If I run it > soon after that it runs and the output is on the screen in less then a > second. I would think this has to do with compiling but I am not sure. Any > ideas how to speed this up? > > I am running python 2.4 on a RHE3.0 cluster. > > Thanks, > > John Ertl > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Wed May 3 21:55:03 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 03 May 2006 13:55:03 -0600 Subject: [Tutor] How Big Is Too Big? In-Reply-To: References: Message-ID: <44590A97.6020901@h-lab.net> > Just wondering how many lines of code is the maximum to post in the list > to have it critiqued. I realise people are using their own time to help > others in here for no real personal gain and I would hate to impose on > their goodwill. Would about 100 lines of code be considered too much? My 2 cents: Length is really no problem, the problem would be: 1) inconvenience of too long an email. Post a link to a webpage with the code if it is longer than, say, 100 lines. 2) It is much more important for me that the poster seems to be really working on the issue, and willing to learn. Then I'd have a look at code any size :) But this is just my own opinion. Greetings, Hugo From python at venix.com Wed May 3 22:58:22 2006 From: python at venix.com (Python) Date: Wed, 03 May 2006 16:58:22 -0400 Subject: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) In-Reply-To: <006e01c66ee8$8441a340$e1966147@michelleevans> References: <002801c66e3f$bc3012e0$e1966147@michelleevans> <1146614201.20702.338.camel@www.venix.com> <006501c66e51$ae869620$e1966147@michelleevans> <1146673121.20702.403.camel@www.venix.com> <006e01c66ee8$8441a340$e1966147@michelleevans> Message-ID: <1146689902.20702.429.camel@www.venix.com> On Wed, 2006-05-03 at 15:33 -0400, MICHELLE EVANS wrote: > OK, I've tried a different approach to this. > How do I get this to stop by using -1? > I do not want this to print until either 5 inputs have been entered or -1 > has been entered. See below: > use a "for block" rather than a "while block" to have a normal limit of 5 repetitions: for x in range(5): will repeat 5 times with x running from 0 to 4. x is ignored - unless some use for it does turn up. the break statement allows you to terminate a block, so if number == -1: break will end the for block. Now, one of the cute features in Python is the else clause that goes with the for and while blocks. The else block is executed when there is no break. So the skeleton for your program can look something like for x in range(5): # get inputs and break on -1 else: # no break so just process the inputs Good luck. > # Add number of per hour > numbers = [] > stop = None > while stop != "-1": > number = int(raw_input("Run number(-1 to end) : ")) > numbers.append(number) > print > for number in numbers: > print number > > > > > ----- Original Message ----- > From: "Python" > To: "MICHELLE EVANS" > Cc: "Tutor Python" > Sent: Wednesday, May 03, 2006 12:18 PM > Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT > ACCIDENTLY) > > > > (Tip: Best to use reply-to-all when responding to an email on the list) > > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > > > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > > > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > > > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > > > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > > > number5 = int(raw_input("Run number 5 (-1 to end) : ")) > > Good. You collect the string from raw_input and convert it to an > > integer. > > > > This will prompt for 5 inputs, but it is missing any logic to actually > > break if -1 is entered. With a language like BASIC, you could stick in > > tests sort of like: > > if number1 == -1 goto done: > > BUT Python does not have a goto. So we actually need some "flow > > control" around the block of code where you collect inputs. > > > > while blocks process an indefinite number of times while a test > > condition is True. > > > > for blocks iterate through a sequence until they reach the end. By > > providing a sequence with the correct count, you can repeat the block > > the correct number of times. The range (and xrange for big sequences) > > functions provide a sequence of integers that can be used conveniently > > with for. > > > > The easiest way to fix your code above would be something like: > > ask_for_number = True > > while ask_for_number: > > number1 = .... > > if number1 == -1: break > > ... > > number5 = ... > > ask_for_number = False > > > > HOWEVER, that is not a good approach in the long run. > > > > A better approach is to have a single container to hold all of the > > inputs. For this, Python provides lists. Rather than have 5 separate > > variables, use a single list variable to hold all of the inputs. Then > > use a "for block" to ask for the input and put the result into the list. > > You already know how to convert the input from a string to a number. > > > > If you have trouble figuring out lists and for blocks, ask for help. > > > > (Sorry about the extra email. I forgot and used ad editor hot-key combo > > in my email program which sent the email.) > > > > > > > > > > > > > # The following will sum the numbers and then print the answer > > > sum = number1 + number2 + number3 + number4 + number5 > > > print > > > print "The total number of parts produced was:", sum,"." > > > > > > I need this to ask the user to enter their number per each run. That is > why > > > I have 5 different input numbers. I need this break if a -1 is entered. > > > Would I use "if-else" to break this if -1 is entered? I need to be able > to > > > count the number of lines entered. > > > > > > Thanks > > > Rick > > > > > > > > > ----- Original Message ----- > > > From: "Python" > > > To: "MICHELLE EVANS" > > > Cc: "Tutor Python" > > > Sent: Tuesday, May 02, 2006 7:56 PM > > > Subject: Re: [Tutor] counting number of inputs > > > > > > > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > > > I am trying to count the number of times a positive number is > entered > > > > > from the user. But, the program must stop after 5 user inputs or a > > > > > negative number. > > > > > > > > > > Can anyone help. > > > > Yes, but you need to help yourself also. > > > > > > > > Do you know how to get input from the user? > > > > Do you know how to count things in Python? > > > > Do you know how to test a number to see if it is positive or negative? > > > > > > > > Why don't you post your code for any part of this problem and explain > > > > how it is supposed to work and where you are having difficulty. If > > > > necessary, review some of the tutorials to get some pointers on > writing > > > > Python programs. > > > > > > > > We're happy to help you learn, but do not want to simply write your > > > > program for you. > > > > > > > > > Rick > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > > > Lloyd Kvam > > > > Venix Corp > > > > > > > > > > > > > -- > > Lloyd Kvam > > Venix Corp > > > > > -- Lloyd Kvam Venix Corp From stvsmth at gmail.com Wed May 3 23:47:40 2006 From: stvsmth at gmail.com (stv) Date: Wed, 3 May 2006 17:47:40 -0400 Subject: [Tutor] Books In-Reply-To: <20060503131035.36018.qmail@web60016.mail.yahoo.com> References: <20060503131035.36018.qmail@web60016.mail.yahoo.com> Message-ID: <9493d0340605031447u79910552xbbe215ec75d890ce@mail.gmail.com> > "Beginning Python: From Novice to Professional", by > Magnus Lie Hetland > Publisher: Apress (September 26, 2005) > ISBN: 159059519X I would heartily second this recommendation. Different folks have different learning styles, and having a good overview can make weeding out the internet information a lot easier. There's also, on-line, Dive Into Python by Mark Pilgrim, often recommended as a good intro book http://diveintopython.org/index.html From wescpy at gmail.com Thu May 4 00:51:08 2006 From: wescpy at gmail.com (w chun) Date: Wed, 3 May 2006 15:51:08 -0700 Subject: [Tutor] Books In-Reply-To: <9493d0340605031447u79910552xbbe215ec75d890ce@mail.gmail.com> References: <20060503131035.36018.qmail@web60016.mail.yahoo.com> <9493d0340605031447u79910552xbbe215ec75d890ce@mail.gmail.com> Message-ID: <78b3a9580605031551g23690687m9d9a2277e902fd87@mail.gmail.com> > > "Beginning Python: From Novice to Professional", by > > Magnus Lie Hetland > > There's also, on-line, Dive Into Python by Mark Pilgrim, often > recommended as a good intro book both of these are very good books, but the target audience is slightly different, as is for "Core Python" -- 2nd ed is coming out late this summer! dive into python gives a very quick... um, "dive", into python. there are specific tasks and subjects which marks wants you to learn from and just jumps right in as a quick intro to python. magnus' "beginning python" (really the 2nd ed of Practical Python) spends more time on a more broad selection of topics, and goes more in-depth, hence the reason why it's a bigger book. finally, "core python" is the complete and intensive intro. we have had pretty good word of mouth over the past 5 yrs for the 1st ed., and i've finally had the chance to update it all the way to 2.5, 2.6, etc. the book is much longer than the other too, but my goal is to not only "teach Python," something that someone already in this thread has mentioned, can be learned online without a book really, but to dive deep into it and go under Python's covers to learn how objects and memory management work. it is our belief that the in-depth learning helps you understand the interpreter better, and in turn, write *more effective* python coming out of the chute than if you just learned the syntax alone. also, we are proud to feature many easy, intermediate, and challenging exercises at the end of each chapter to hammer the concepts home. the bad news is that you'll have to wait till the end of summer. :-) click on the link below in my sig for reviews, a sample chapter, and more! if you are looking for more of a reference book to pull off the shelf while programming, we suggest the python essential reference by beazley (who also had time recently to come out with a 3rd ed) or the python in a nutshell by martelli (who's furiously trying to come out with another ed). core python is not a reference book like the above two but does have more reference material than the 1st two books mentioned. it's main purpose is teaching *and* learning python well. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From marichar at csusb.edu Thu May 4 01:09:43 2006 From: marichar at csusb.edu (Matt Richardson) Date: Wed, 03 May 2006 16:09:43 -0700 Subject: [Tutor] sockets Message-ID: <44593837.5070605@csusb.edu> Just verifying what I looked up earlier: are strings and binary (through struct.pack) the only data types that can be sent through a socket? This is my first crack at socket programming, so I'll probably have lots of questions to bug you with. thanks, Matt From mahansen at adelphia.net Thu May 4 03:16:18 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 3 May 2006 19:16:18 -0600 Subject: [Tutor] Tutor FAQ Message-ID: <7afb5a737105d51ed4d83506a23afba2@adelphia.net> Well, I posted a few questions to http://pyfaq.infogami.com/tutor-index late last week. Since the next questions and answers are a bit on the long side, I'll send them to this list in multiple messages. Please let me know if you have any corrections or clarifications. Below is a reworked question from last week. --------------------------------------------------------------------- How do I make public and private attributes and methods in my classes? Python followws the philosophy of "we're all adults here" with respect to hiding attributes and methods. i.e. trust the other programmers who will use your classes. You should use plain attributes whenever possible. You might be tempted to use getters and setters, but the only reason to use getters and setters is so you can change the implementation later if you need to. However, Python allows you to do this with properties http://www.python.org/download/releases/2.2.3/descrintro/#property If you really must hide an attribute or method, Python does do name mangling. By putting two underscores before the attribute or method name and not putting two underscores after the name, Python will mangle the name by putting the class name in front of it. For an short example see http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python [Paraphrased from a post to comp.lang.python by Steven Bethard] From mahansen at adelphia.net Thu May 4 03:18:57 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 3 May 2006 19:18:57 -0600 Subject: [Tutor] Tutor FAQ Message-ID: --------------------------------------------------------------------- What's the difference between "import foo" and "from foo import *"? import sys This brings the *name* "sys" into your module. It does not give you access to any of the names inside sys itself (such as exit for example). To access those you need to prefix them with sys, as in sys.exit() from sys import * This does NOT bring the name "sys" into your module, instead it brings all of the names inside sys(like exit for example) into your module. Now you can access those names without a prefix, like this: exit() So why not do that instead of import sys? The reason is that the second form will overwrite and names you have already declared - like exit say. exit = 42 from sys import * # hides my exit variable. OR more likely, the other way round from sys import * exit = 42 # now hides the sys.exit function so I can't use it. Of course some of these are obvious but there can be a lot of names in a module, and some modules have the same name in them, for example: from os import * from urllib import * open(foo) # which open gets called, os.open or urllib.open? Can you see how it gets confusing. Bottom line is it is usually better to accept the extra typing and use import foo or for just a few names from foo import bar,baz [from a post on Python Tutor by Alan Gauld] From mahansen at adelphia.net Thu May 4 03:23:33 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 3 May 2006 19:23:33 -0600 Subject: [Tutor] Tutor FAQ Message-ID: I need some help with this question and answer. It appears that useless Python is gone. uselesspython.com. Is it still around? Does anyone have any ideas on this one? --------------------------------------------------------------------- I'm learning Python. What should I program? If you have a personal itch to scratch, it's probably best to scratch it. You'll probably be more interested and motivated to program if it's something you want to accomplish. However, if you don't have any ideas, you can try the Python Challenge http://www.pythonchallenge.com/ From mahansen at adelphia.net Thu May 4 03:36:38 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 3 May 2006 19:36:38 -0600 Subject: [Tutor] Tutor FAQ Message-ID: --------------------------------------------------------------------- What are some good books on Python? See the Python wiki http://wiki.python.org/moin/PythonBooks or search comp.lang.python or the tutor archives since this is a very frequently asked. If you have no programming experience, try Alan Gauld's book Learn To Program http://www.freenetpages.co.uk/hp/alan.gauld/ If you have some programming experience try Learning Python http://www.oreilly.com/catalog/lpython2/index.html Dive Into Python http://diveintopython.org/ Beginning Python: From Novice to Professional http://www.apress.com/book/bookDisplay.html?bID=10013 Core Python Programming http://starship.python.net/crew/wesc/cpp/ Good Python reference books are The Essential Python Reference http://www.samspublishing.com/title/0672328623 Python in a Nutshell http://www.oreilly.com/catalog/pythonian/index.html Python Cookbook http://www.oreilly.com/catalog/pythoncook2/ A note to Perl programmers who are learning Python. Don't start with Programming Python. It is not the same as Programming Perl. Start with Learning Python, then move on to Programming Python. From mahansen at adelphia.net Thu May 4 03:37:41 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 3 May 2006 19:37:41 -0600 Subject: [Tutor] Tutor FAQ Message-ID: <47689e0b23da0dd49562e58dd870e593@adelphia.net> --------------------------------------------------------------------- What is if __name__ == "__main__" for? The 'if __name__ == "__main__": ..." trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files: ###### mumak:~ dyoo$ cat mymath.py def square(x): return x * x if __name__ == '__main__': print "test: square(42) ==", square(42) mumak:~ dyoo$ cat mygame.py import mymath print "this is mygame." print mymath.square(17) ###### In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this: ###### mumak:~ dyoo$ python mymath.py test: square(42) == 1764 ###### But we can also use mymath.py as a module; let's see what happens when we run mygame.py: ###### mumak:~ dyoo$ python mygame.py this is mygame. 289 ###### Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the 'if __name__ == "__main__": ...' trick is used for. [From a post to Python Tutor by Danny Woo] From kent37 at tds.net Thu May 4 03:46:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 May 2006 21:46:42 -0400 Subject: [Tutor] sockets In-Reply-To: <44593837.5070605@csusb.edu> References: <44593837.5070605@csusb.edu> Message-ID: <44595D02.2000604@tds.net> Matt Richardson wrote: > Just verifying what I looked up earlier: are strings and binary > (through struct.pack) the only data types that can be sent through a > socket? This is my first crack at socket programming, so I'll probably > have lots of questions to bug you with. The socket library gives low-level access to socket connections. At this level, the only type of data is a byte stream which in Python is represented by a string. There are higher-level protocols that support more structured data. You can use the pickle module to convert most data structures to strings which can be sent over a socket. XML-RPC is a remote procedure call standard that supports simple data structures; it is supported in xmlrpclib and SimpleXMLRPCServer. PyRO is another remote object protocol that is Python-specific. What is it you want to do? Kent From kent37 at tds.net Thu May 4 03:55:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 May 2006 21:55:00 -0400 Subject: [Tutor] Tutor FAQ In-Reply-To: References: Message-ID: <44595EF4.5050503@tds.net> Mike Hansen wrote: > --------------------------------------------------------------------- > What's the difference between "import foo" and "from foo import *"? > > import sys > > This brings the *name* "sys" into your module. (Technically, it binds the name "sys" to the object that is the sys module.) > It does not give you access to any of the names inside sys itself (such > as does not give you _direct_ access... > exit for example). To access those you need to prefix them with sys, as > in > > sys.exit() > > from sys import * > > This does NOT bring the name "sys" into your module, instead it brings > all > of the names inside sys(like exit for example) into your module. Now > you can > access those names without a prefix, like this: > > exit() > > So why not do that instead of > > import sys? > > The reason is that the second form will overwrite and names you have > already > declared - like exit say. > exit = 42 > from sys import * # hides my exit variable. > > OR more likely, the other way round > > from sys import * > exit = 42 # now hides the sys.exit function so I can't use it. > > Of course some of these are obvious but there can be a lot of names in a > module, and some modules have the same name in them, for example: > > from os import * > from urllib import * > > open(foo) # which open gets called, os.open or urllib.open? > > Can you see how it gets confusing. confusing? Another disadvantage of "from sys import *" is that it makes it harder to find the definition of a name. If you see "sys.exit()" in the code, you know exactly where exit() is defined. If you see "exit()" in a module that has several "from xx import *" statements, you will have to search each imported module for the definition of exit(). > Bottom line is it is usually better to accept the extra typing and use The bottom line... > > import foo > > or for just a few names > > from foo import bar,baz > > [from a post on Python Tutor by Alan Gauld] > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu May 4 04:01:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 May 2006 22:01:43 -0400 Subject: [Tutor] Tutor FAQ In-Reply-To: References: Message-ID: <44596087.8020701@tds.net> Mike Hansen wrote: > --------------------------------------------------------------------- > What are some good books on Python? > > See the Python wiki http://wiki.python.org/moin/PythonBooks or search > comp.lang.python or the tutor archives since this is a very frequently > asked. > > If you have no programming experience, try Alan Gauld's book > Learn To Program http://www.freenetpages.co.uk/hp/alan.gauld/ Python Programming for the absolute beginner http://premierpressbooks.com/ptr_detail.cfm?isbn=1%2D59863%2D112%2D8 Python Programming: An Introduction to Computer Science http://www.fbeedle.com/99-6.html > > If you have some programming experience try > Learning Python http://www.oreilly.com/catalog/lpython2/index.html > Dive Into Python http://diveintopython.org/ > Beginning Python: From Novice to Professional > http://www.apress.com/book/bookDisplay.html?bID=10013 > Core Python Programming http://starship.python.net/crew/wesc/cpp/ > > Good Python reference books are > The Essential Python Reference > http://www.samspublishing.com/title/0672328623 > Python in a Nutshell http://www.oreilly.com/catalog/pythonian/index.html > Python Cookbook http://www.oreilly.com/catalog/pythoncook2/ > > A note to Perl programmers who are learning Python. Don't start with > Programming Python. It is not the same as Programming Perl. Start with > Learning Python, then move on to Programming Python. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From marc_a_poulin at yahoo.com Thu May 4 06:08:04 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Wed, 3 May 2006 21:08:04 -0700 (PDT) Subject: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) In-Reply-To: <1146689902.20702.429.camel@www.venix.com> Message-ID: <20060504040804.21130.qmail@web34113.mail.mud.yahoo.com> Michelle: Are you familiar with writing functions? Here I've created a function named getInputs. I've also created a few test cases to verify that (a) my understanding of the problem is correct, and (b) my solution is correct. It's important to think about how your program is supposed to behave in different situations. Do you think these 3 tests are enough to prove that the code is correct? ######################### ## start of code ## ######################### def getInputs(): """ Description: Collect numbers entered by the user (up to a maximum of 5 values) and store them in the listOfValues. Stop collecting numbers if the user enters -1 or if 5 numbers have been collected. If the user entered -1, the -1 is NOT returned as part of the list. """ listOfValues = [] ## this list holds the values entered by the user for i in range(5): newValue = int(raw_input('Enter a number [-1 to exit]:')) if newValue == -1: # Return right now with whatever is currently in the list. return listOfValues else: # Add this new value to the list and keep looping. listOfValues.append(newValue) ## If we got this far, it means the user did not enter a -1 so ## the list contains 5 values. return listOfValues """ Here are a few test cases to verify the logic of my code. Test Case 1: INPUTS: first entered value: -1 RESULT: function returns empty list Test Case 2: INPUTS: first entered value: 1 second entered value: 2 third entered value: -1 RESULT: returned list contains [1,2] Test Case 3: INPUTS: first entered value: 1 second entered value: 2 third entered value: 3 fourth entered value: 4 fifth entered value: 5 RESULT: returned list contains [1,2,3,4,5] """ if __name__ == "__main__": print getInputs() ################### ## end of code ## ################### --- Python wrote: > On Wed, 2006-05-03 at 15:33 -0400, MICHELLE EVANS > wrote: > > OK, I've tried a different approach to this. > > How do I get this to stop by using -1? > > I do not want this to print until either 5 inputs > have been entered or -1 > > has been entered. See below: > > > > use a "for block" rather than a "while block" to > have a normal limit of > 5 repetitions: > > for x in range(5): > > will repeat 5 times with x running from 0 to 4. > x is ignored - unless some use for it does turn up. > > the break statement allows you to terminate a block, > so > > if number == -1: break > > will end the for block. > > > Now, one of the cute features in Python is the else > clause that goes > with the for and while blocks. The else block is > executed when there is > no break. So the skeleton for your program can look > something like > > for x in range(5): > # get inputs and break on -1 > else: > # no break so just process the inputs > > Good luck. > > > # Add number of per hour > > numbers = [] > > stop = None > > while stop != "-1": > > number = int(raw_input("Run number(-1 to end) > : ")) > > numbers.append(number) > > print > > for number in numbers: > > print number > > > > > > > > > > ----- Original Message ----- > > From: "Python" > > To: "MICHELLE EVANS" > > Cc: "Tutor Python" > > Sent: Wednesday, May 03, 2006 12:18 PM > > Subject: Re: [Tutor] counting number of inputs > (EARLIER VERSION SENT > > ACCIDENTLY) > > > > > > > (Tip: Best to use reply-to-all when responding > to an email on the list) > > > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE > EVANS wrote: > > > > number1 = int(raw_input("Run number 1 (-1 to > end) : ")) > > > > number2 = int(raw_input("Run number 2 (-1 to > end) : ")) > > > > number3 = int(raw_input("Run number 3 (-1 to > end) : ")) > > > > number4 = int(raw_input("Run number 4 (-1 to > end) : ")) > > > > number5 = int(raw_input("Run number 5 (-1 to > end) : ")) > > > Good. You collect the string from raw_input and > convert it to an > > > integer. > > > > > > This will prompt for 5 inputs, but it is missing > any logic to actually > > > break if -1 is entered. With a language like > BASIC, you could stick in > > > tests sort of like: > > > if number1 == -1 goto done: > > > BUT Python does not have a goto. So we actually > need some "flow > > > control" around the block of code where you > collect inputs. > > > > > > while blocks process an indefinite number of > times while a test > > > condition is True. > > > > > > for blocks iterate through a sequence until they > reach the end. By > > > providing a sequence with the correct count, you > can repeat the block > > > the correct number of times. The range (and > xrange for big sequences) > > > functions provide a sequence of integers that > can be used conveniently > > > with for. > > > > > > The easiest way to fix your code above would be > something like: > > > ask_for_number = True > > > while ask_for_number: > > > number1 = .... > > > if number1 == -1: break > > > ... > > > number5 = ... > > > ask_for_number = False > > > > > > HOWEVER, that is not a good approach in the long > run. > > > > > > A better approach is to have a single container > to hold all of the > > > inputs. For this, Python provides lists. > Rather than have 5 separate > > > variables, use a single list variable to hold > all of the inputs. Then > > > use a "for block" to ask for the input and put > the result into the list. > > > You already know how to convert the input from a > string to a number. > > > > > > If you have trouble figuring out lists and for > blocks, ask for help. > > > > > > (Sorry about the extra email. I forgot and used > ad editor hot-key combo > > > in my email program which sent the email.) > > > > > > > > > > > > > > > > > > # The following will sum the numbers and then > print the answer > > > > sum = number1 + number2 + number3 + number4 + > number5 > > > > print > > > > print "The total number of parts produced > was:", sum,"." > > > > > > > > I need this to ask the user to enter their > number per each run. That is > > why > > > > I have 5 different input numbers. I need this > break if a -1 is entered. > > > > Would I use "if-else" to break this if -1 is > entered? I need to be able > > to > > > > count the number of lines entered. > > > > > > > > Thanks > > > > Rick > > > > > > > > > > > > ----- Original Message ----- > > > > From: "Python" > > > > To: "MICHELLE EVANS" > > > > Cc: "Tutor Python" > > > > Sent: Tuesday, May 02, 2006 7:56 PM > > > > Subject: Re: [Tutor] counting number of inputs > > > > > > > > > > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE > EVANS wrote: > > > > > > I am trying to count the number of times a > positive number is > > entered > > > > > > from the user. But, the program must stop > after 5 user inputs or a > > > > > > negative number. > > > > > > > > > > > > Can anyone help. > > > > > Yes, but you need to help yourself also. > > > > > > > > > > Do you know how to get input from the user? > > > > > Do you know how to count things in Python? > > > > > Do you know how to test a number to see if > it is positive or negative? > > > > > > > > > > Why don't you post your code for any part of > this problem and explain > > > > > how it is supposed to work and where you are > having difficulty. If > > > > > necessary, review some of the tutorials to > get some pointers on > > writing > > > > > Python programs. > > > > > > > > > > We're happy to help you learn, but do not > want to simply write your > > > > > program for you. > > > > > > === message truncated === __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john.corry at ntlworld.com Thu May 4 10:51:49 2006 From: john.corry at ntlworld.com (John CORRY) Date: Thu, 4 May 2006 09:51:49 +0100 Subject: [Tutor] 2 Combo Boxes! What was I thinking? Message-ID: <000001c66f57$fcb695a0$4a3ea8c0@JOHNC> Hi, I have set up a GUI which has amongst other widgets two combo boxes. I am using: PythonCard version: 0.8.1 wxPython version: 2.6.1.0 Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] Platform: win32 Glade 2 I started by setting up comboboxentry2 to accept two settings in its drop down list. (open + closed). This worked fined. Code below: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) My problems started when I went to set up comboboxentry3. I used the following code: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo3 = self.wTree.get_widget("comboboxentry3") combo3.connect("changed", self.callback3, "comboboxentry3") combo3.append_text ("Mon") combo3.append_text ("Tue") combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) I got the following error: Gtkwarning: gtk_combo_box_append_text: assertion GTK_IS_LIST_STORE(Combobox->Priv->Model) Failed Combo3.append_text("Mon") Gtkwarning: gtk_combo_box_append_text: assertion GTK_IS_LIST_STORE(Combobox->Priv->Model) Failed Combo3.append_text("Tue") I then tried the code: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo3 = self.wTree.get_widget("comboboxentry3") combo3.connect("changed", self.callback3, "comboboxentry3") combo3.child.append_text ("Mon") combo3.child.append_text ("Tue") combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) I get the following error message: DeprecationWarning: use GtkEditable.insert_text Combo3.child.append_text("Mon") DeprecationWarning: use GtkEditable.insert_text Combo3.child.append_text("Tue") The combobox3 is populated on the GUI but instead of being a drop down list it appears as a string on one line and looks like this: MonTue I have to confess I am not really sure what I am doing. I just guessed at putting the child command in. It gets me close but not close enough. Can anyone tell me what I am doing wrong or explain what happens when you put two combo boxes on the one GUI? Any help greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060504/d0e6aeb9/attachment.htm From traviesomono at yahoo.es Thu May 4 11:01:08 2006 From: traviesomono at yahoo.es (Alfonso) Date: Thu, 04 May 2006 11:01:08 +0200 Subject: [Tutor] UI developing Message-ID: <4459C2D4.10100@yahoo.es> Hi, I'm starting with python on linux. I would like to make gtk user interfaces. Wich is the best option to do that? gtk-bindings, glade? If I want to port a program with gtk interface to windows, what should I use? Thank you very much for your attention. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From philipasmith at blueyonder.co.uk Thu May 4 11:36:26 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Thu, 4 May 2006 10:36:26 +0100 Subject: [Tutor] Memory Management etc Message-ID: <002f01c66f5e$36ce8170$16792d52@PANDORA> Hi I use Activestate Python (2.4.3) in a Windows 32 bit environment. I have a problem with a large programme that uses a lot of memory (numerous large arrays which are dynamically extended). I keep getting unpredictable crashes (on a machine with 1/2 GB memory) whereas on my laptop (1 GB memory) it seems OK. The portion of the code which crashes varies a bit but curiously is NEVER a part where any memory allocation is happening. There are no debugger messages it just crashes (and reboots the machine more often than not). I have so far tried: Using the gc module: can't seem to locate any circular references and garbage collection works OK. Surrounding all memory allocation code with Try...Except but no MemoryError ever gets reported. Running under various versions of Python (standard distrib from Python Org, Stackless Python etc) This kind of crash is classically a stack/heap collision problem (and/or segmentation fault) but if I monitor memory usage during execution (with Windows Monitor) I usually have 200 or so MB free at the point of crash. I have to say I have noticed (the programme is basically a batch-factoring programme for integers) that no matter how I tune gc I can't get it to reliably free memory in between factoring each integer. Because this is a development programme (and for performance reasons) I use global variables some of which refer to the large arrays. My questions are: 1) Does the mere fact that a function cites a variable as global create a reference which prevents it being collected by gc? 2) I notice that in Unix I would have access to a resource module which might help - is there nothing similar in Python for Windows? 3) Is there any way to allocate a pool of available memory to my programme at the outset from which I can allocate my large arrays? 4) Is there any module / function which would enable me to access the BYTE size of Python objects such as arrays etc or to track memory usage from within Python. 5) Does anyone have ANY suggestions please? I'm keen to solve this because I would like to make my programme generally available - in every other respect its near complete and massively outperforms the only other comparable pure python module (nzmath) which does the same job. Thanks in anticipation. Phil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060504/6ea1cfab/attachment.htm From evans1018 at verizon.net Thu May 4 13:53:40 2006 From: evans1018 at verizon.net (MICHELLE EVANS) Date: Thu, 04 May 2006 07:53:40 -0400 Subject: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) References: <20060504040804.21130.qmail@web34113.mail.mud.yahoo.com> Message-ID: <001801c66f71$6366b1e0$e1966147@michelleevans> This is exactly what I am trying to do. I am so confused with trying to write this. I am not very familiar with any of the functions. I keep reading my book and reading my book, and none of it seems to make sense anymore. I can write extremely simple functions, but when I need to use more than one in a code, I'm lost! Thanks ----- Original Message ----- From: "Marc Poulin" To: Sent: Thursday, May 04, 2006 12:08 AM Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY) > > Michelle: > > Are you familiar with writing functions? > Here I've created a function named getInputs. > > I've also created a few test cases to verify that (a) > my understanding of the problem is correct, and (b) my > solution is correct. > > It's important to think about how your program is > supposed to behave in different situations. Do you > think these 3 tests are enough to prove that the code > is correct? > > ######################### > ## start of code ## > ######################### > def getInputs(): > """ > Description: > Collect numbers entered by the user (up to a > maximum of 5 values) and > store them in the listOfValues. > > Stop collecting numbers if the user enters -1 > or if 5 numbers have been collected. > > If the user entered -1, the -1 is NOT returned > as part of the list. > """ > listOfValues = [] ## this list holds the values > entered by the user > > for i in range(5): > newValue = int(raw_input('Enter a number [-1 > to exit]:')) > if newValue == -1: > # Return right now with whatever is > currently in the list. > return listOfValues > else: > # Add this new value to the list and keep > looping. > listOfValues.append(newValue) > > ## If we got this far, it means the user did not > enter a -1 so > ## the list contains 5 values. > return listOfValues > > """ > Here are a few test cases to verify the logic of my > code. > > Test Case 1: > INPUTS: > first entered value: -1 > RESULT: > function returns empty list > > Test Case 2: > INPUTS: > first entered value: 1 > second entered value: 2 > third entered value: -1 > RESULT: > returned list contains [1,2] > > Test Case 3: > INPUTS: > first entered value: 1 > second entered value: 2 > third entered value: 3 > fourth entered value: 4 > fifth entered value: 5 > RESULT: > returned list contains [1,2,3,4,5] > """ > if __name__ == "__main__": > print getInputs() > > ################### > ## end of code ## > ################### > > > --- Python wrote: > > > On Wed, 2006-05-03 at 15:33 -0400, MICHELLE EVANS > > wrote: > > > OK, I've tried a different approach to this. > > > How do I get this to stop by using -1? > > > I do not want this to print until either 5 inputs > > have been entered or -1 > > > has been entered. See below: > > > > > > > use a "for block" rather than a "while block" to > > have a normal limit of > > 5 repetitions: > > > > for x in range(5): > > > > will repeat 5 times with x running from 0 to 4. > > x is ignored - unless some use for it does turn up. > > > > the break statement allows you to terminate a block, > > so > > > > if number == -1: break > > > > will end the for block. > > > > > > Now, one of the cute features in Python is the else > > clause that goes > > with the for and while blocks. The else block is > > executed when there is > > no break. So the skeleton for your program can look > > something like > > > > for x in range(5): > > # get inputs and break on -1 > > else: > > # no break so just process the inputs > > > > Good luck. > > > > > # Add number of per hour > > > numbers = [] > > > stop = None > > > while stop != "-1": > > > number = int(raw_input("Run number(-1 to end) > > : ")) > > > numbers.append(number) > > > print > > > for number in numbers: > > > print number > > > > > > > > > > > > > > > ----- Original Message ----- > > > From: "Python" > > > To: "MICHELLE EVANS" > > > Cc: "Tutor Python" > > > Sent: Wednesday, May 03, 2006 12:18 PM > > > Subject: Re: [Tutor] counting number of inputs > > (EARLIER VERSION SENT > > > ACCIDENTLY) > > > > > > > > > > (Tip: Best to use reply-to-all when responding > > to an email on the list) > > > > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE > > EVANS wrote: > > > > > number1 = int(raw_input("Run number 1 (-1 to > > end) : ")) > > > > > number2 = int(raw_input("Run number 2 (-1 to > > end) : ")) > > > > > number3 = int(raw_input("Run number 3 (-1 to > > end) : ")) > > > > > number4 = int(raw_input("Run number 4 (-1 to > > end) : ")) > > > > > number5 = int(raw_input("Run number 5 (-1 to > > end) : ")) > > > > Good. You collect the string from raw_input and > > convert it to an > > > > integer. > > > > > > > > This will prompt for 5 inputs, but it is missing > > any logic to actually > > > > break if -1 is entered. With a language like > > BASIC, you could stick in > > > > tests sort of like: > > > > if number1 == -1 goto done: > > > > BUT Python does not have a goto. So we actually > > need some "flow > > > > control" around the block of code where you > > collect inputs. > > > > > > > > while blocks process an indefinite number of > > times while a test > > > > condition is True. > > > > > > > > for blocks iterate through a sequence until they > > reach the end. By > > > > providing a sequence with the correct count, you > > can repeat the block > > > > the correct number of times. The range (and > > xrange for big sequences) > > > > functions provide a sequence of integers that > > can be used conveniently > > > > with for. > > > > > > > > The easiest way to fix your code above would be > > something like: > > > > ask_for_number = True > > > > while ask_for_number: > > > > number1 = .... > > > > if number1 == -1: break > > > > ... > > > > number5 = ... > > > > ask_for_number = False > > > > > > > > HOWEVER, that is not a good approach in the long > > run. > > > > > > > > A better approach is to have a single container > > to hold all of the > > > > inputs. For this, Python provides lists. > > Rather than have 5 separate > > > > variables, use a single list variable to hold > > all of the inputs. Then > > > > use a "for block" to ask for the input and put > > the result into the list. > > > > You already know how to convert the input from a > > string to a number. > > > > > > > > If you have trouble figuring out lists and for > > blocks, ask for help. > > > > > > > > (Sorry about the extra email. I forgot and used > > ad editor hot-key combo > > > > in my email program which sent the email.) > > > > > > > > > > > > > > > > > > > > > > > # The following will sum the numbers and then > > print the answer > > > > > sum = number1 + number2 + number3 + number4 + > > number5 > > > > > print > > > > > print "The total number of parts produced > > was:", sum,"." > > > > > > > > > > I need this to ask the user to enter their > > number per each run. That is > > > why > > > > > I have 5 different input numbers. I need this > > break if a -1 is entered. > > > > > Would I use "if-else" to break this if -1 is > > entered? I need to be able > > > to > > > > > count the number of lines entered. > > > > > > > > > > Thanks > > > > > Rick > > > > > > > > > > > > > > > ----- Original Message ----- > > > > > From: "Python" > > > > > To: "MICHELLE EVANS" > > > > > Cc: "Tutor Python" > > > > > Sent: Tuesday, May 02, 2006 7:56 PM > > > > > Subject: Re: [Tutor] counting number of inputs > > > > > > > > > > > > > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE > > EVANS wrote: > > > > > > > I am trying to count the number of times a > > positive number is > > > entered > > > > > > > from the user. But, the program must stop > > after 5 user inputs or a > > > > > > > negative number. > > > > > > > > > > > > > > Can anyone help. > > > > > > Yes, but you need to help yourself also. > > > > > > > > > > > > Do you know how to get input from the user? > > > > > > Do you know how to count things in Python? > > > > > > Do you know how to test a number to see if > > it is positive or negative? > > > > > > > > > > > > Why don't you post your code for any part of > > this problem and explain > > > > > > how it is supposed to work and where you are > > having difficulty. If > > > > > > necessary, review some of the tutorials to > > get some pointers on > > > writing > > > > > > Python programs. > > > > > > > > > > > > We're happy to help you learn, but do not > > want to simply write your > > > > > > program for you. > > > > > > > > > === message truncated === > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu May 4 14:33:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 May 2006 08:33:46 -0400 Subject: [Tutor] Memory Management etc In-Reply-To: <002f01c66f5e$36ce8170$16792d52@PANDORA> References: <002f01c66f5e$36ce8170$16792d52@PANDORA> Message-ID: <4459F4AA.9000405@tds.net> Philip Smith wrote: > Hi > > I use Activestate Python (2.4.3) in a Windows 32 bit environment. > > I have a problem with a large programme that uses a lot of memory > (numerous large arrays which are dynamically extended). I keep getting > unpredictable crashes (on a machine with 1/2 GB memory) whereas on my > laptop (1 GB memory) it seems OK. I'm way out of my expertise here but I'll give it a try... Is your program pure Python or are you using C extensions (other than the ones in the standard library)? If it is pure Python I think this would be considered a Python bug and would interest the Python developers. > The portion of the code which crashes varies a bit but curiously is > NEVER a part where any memory allocation is happening. Can you post any code? If you can make a short test program that shows the problem that will dramatically increase your chances of getting useful help. > I have to say I have noticed (the programme is basically a > batch-factoring programme for integers) that no matter how I tune gc I > can't get it to reliably free memory in between factoring each integer. I don't think Python will ever release memory back to the OS. This has changed in Python 2.5, you might be interested in trying the alpha release: http://docs.python.org/dev/whatsnew/section-other.html http://www.python.org/download/releases/2.5/ > > Because this is a development programme (and for performance reasons) I > use global variables some of which refer to the large arrays. > > My questions are: > > 1) Does the mere fact that a function cites a variable as global > create a reference which prevents it being collected by gc? You mean a 'global' statement without actually using the named variable? I don't know if this creates a reference, but if so, the reference should go out of scope when the function exits. > 5) Does anyone have ANY suggestions please? These links might be interesting: http://tinyurl.com/pszzh http://evanjones.ca/python-memory.html http://pysizer.8325.org/ Asking on comp.lang.python will give you access to many more people familiar with Python internals than you will find on this list. > > I'm keen to solve this because I would like to make my programme > generally available - in every other respect its near complete and > massively outperforms the only other comparable pure python module > (nzmath) which does the same job. > > Thanks in anticipation. > > Phil > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From marichar at csusb.edu Thu May 4 18:23:38 2006 From: marichar at csusb.edu (Matt Richardson) Date: Thu, 04 May 2006 09:23:38 -0700 Subject: [Tutor] sockets In-Reply-To: <44595D02.2000604@tds.net> References: <44593837.5070605@csusb.edu> <44595D02.2000604@tds.net> Message-ID: <445A2A8A.40308@csusb.edu> I need to send some data, 2 strings and a list, to a remote computer. After thinking about it some last night, it wouldn't be hard to just send it all as a string and then parse it on the receiving end. I'm writing a program for work (and for a class project, so no answers!) that will provide some info on the network location of a laptop. The client will gather IP address, MAC address, and a traceroute dump (the list mentioned above), then send this off to a super simple server that receives the data and puts it in a database. We've had a few laptops 'disappear' either through theft or people taking them home to do 'work from home' or whatever. Makes annual inventory a huge pain. Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 From kent37 at tds.net Thu May 4 18:41:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 May 2006 12:41:29 -0400 Subject: [Tutor] sockets In-Reply-To: <445A2A8A.40308@csusb.edu> References: <44593837.5070605@csusb.edu> <44595D02.2000604@tds.net> <445A2A8A.40308@csusb.edu> Message-ID: <445A2EB9.3010604@tds.net> Matt Richardson wrote: > I need to send some data, 2 strings and a list, to a remote computer. > After thinking about it some last night, it wouldn't be hard to just > send it all as a string and then parse it on the receiving end. > > I'm writing a program for work (and for a class project, so no answers!) > that will provide some info on the network location of a laptop. The > client will gather IP address, MAC address, and a traceroute dump (the > list mentioned above), then send this off to a super simple server that > receives the data and puts it in a database. We've had a few laptops > 'disappear' either through theft or people taking them home to do 'work > from home' or whatever. Makes annual inventory a huge pain. This would be very easy to do with XML-RPC. On the server side, writ a function that takes three parameters - the IP address, MAC address, and traceroute dump - and saves them to a database. Use SimpleXMLRPCServer to expose the function. On the client side, gather the data and use xmlrpclib to call the remote function. Easy. Since this function will presumably be exposed on the public internet you need to worry about security; you should use some kind of authorization. A really simple solution would be to add username and password arguments to the function you expose. You could do all this with the socket library but XML-RPC takes care of all the details of connections, etc as well as marshalling and unmarshalling the data. Kent From davholla2002 at yahoo.co.uk Thu May 4 18:50:20 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 4 May 2006 17:50:20 +0100 (BST) Subject: [Tutor] Python challenge Message-ID: <20060504165020.15946.qmail@web25915.mail.ukl.yahoo.com> I looked at this and got stuck on the first one :- http://www.pythonchallenge.com/pc/def/0.html It says try changing the url. I assumed that it either meant 2*38 or 2 to the power of 38 but I can't see how to put either of those in the url. What have I missed ? Thanks in advance. David Holland --------------------------------- Yahoo! Photos ? NEW, now offering a quality print service from just 7p a photo. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060504/ec6d3dca/attachment.html From jason.massey at gmail.com Thu May 4 18:56:02 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 4 May 2006 11:56:02 -0500 Subject: [Tutor] Python challenge In-Reply-To: <20060504165020.15946.qmail@web25915.mail.ukl.yahoo.com> References: <20060504165020.15946.qmail@web25915.mail.ukl.yahoo.com> Message-ID: <7e3eab2c0605040956o389cf610l8cebfea6cf1acf13@mail.gmail.com> David, What answer did you get? One of the things to rember on the challenge is to take your answer and put ".html" (no qutoes) on the end of it in the url. So for the first problem the url would be: http://www.pythonchallenge.com/pc/def/.html On 5/4/06, David Holland wrote: > > I looked at this and got stuck on the first one :- > http://www.pythonchallenge.com/pc/def/0.html > It says try changing the url. > I assumed that it either meant 2*38 or 2 to the power of 38 but I can't > see how to put either of those in the url. > > What have I missed ? > > Thanks in advance. > > David Holland > > ------------------------------ > *Yahoo! Photos*? > NEW, now offering a quality print servicefrom just 7p a photo. > > > _______________________________________________ > 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/20060504/9ab893b8/attachment-0001.htm From glingl at aon.at Thu May 4 19:15:13 2006 From: glingl at aon.at (Gregor Lingl) Date: Thu, 04 May 2006 19:15:13 +0200 Subject: [Tutor] Argument check Message-ID: <445A36A1.7070804@aon.at> Hi all, I've a class with a lot of methods, for which I'd like to check argument types. To show you, what I mean, I've written a prototype I'm not really content with. It goes like this (a bit revised in order to have short codelines (*mail* ;-)): class BadArgError(Exception): def __init__(self, fname, var, typ, val): self.fname = fname self.var = var self.typ = typ self.val = val def __str__(self): return """ %s: argument %s must be %s! %s of %s given.""" % ( self.fname, self.var, self.typ, repr(self.val), type(self.val)) def checkargs(fun,locs,*typelist): varnames=fun.im_func.func_code.co_varnames[1:] fn = fun.__name__ for var, typ in zip(varnames, typelist): ok = isinstance(locs[var],typ) if not ok: raise BadArgError(fn, var, typ, locs[var]) ## classe for testing: class Z(object): pass class A(object): def f(self,x,y): checkargs(self.f, locals(), int, str) def g(self,a,b,c): checkargs(self.g, locals(), (int,float), Z, tuple) BadArgError works like this (interactive session): >>> bae = BadArgError("myfun", "myvar", str, 3) >>> raise bae Traceback (most recent call last): File "", line 1, in -toplevel- raise bae BadArgError: myfun: argument myvar must be ! 3 of given. You see, I want to the error-message to display the name of the function, which got the bad argument, the name of the parameter and it's expected type as well as the wrong argument. Examples for it's use: >>> z=Z() >>> a=A() >>> a.f(1,"a") #ok >>> a.f(1,2) Traceback (most recent call last): File "", line 1, in -toplevel- ... raise BadArgError(fn, var, typ, locs[var]) BadArgError: f: argument y must be ! 2 of given. >>> a.g(.5, z, ()) #ok >>> a.g(.5, a, ()) Traceback (most recent call last): File "", line 1, in -toplevel- ... raise BadArgError(fn, var, typ, locs[var]) BadArgError: g: argument b must be ! <__main__.A object at 0x00C92F70> of given. (One could easily tidy up this output - that's *not* the problem) I feel it to be cumbersome and ugly, to have to pass the function (method) and the locals() dictionary to every call of checkargs. I'd very much prefer a usage of checkargs similar to: class A(object): def f(self,x,y): checkargs(int, str) def g(self,a,b,c): checkargs((int,float), Z, tuple) but then chackargs had to get information about its caller (name, locals) from elsewhere (the callstack?). I don't know if this is possible at all, not to say how to accomplish it. Do you have some hints? Where could I find code-examples which solve similar problems? Would you recommend a different approach? Regards, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From dyoo at hkn.eecs.berkeley.edu Thu May 4 19:31:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 4 May 2006 10:31:41 -0700 (PDT) Subject: [Tutor] Memory Management etc In-Reply-To: <002f01c66f5e$36ce8170$16792d52@PANDORA> References: <002f01c66f5e$36ce8170$16792d52@PANDORA> Message-ID: > I have a problem with a large programme that uses a lot of memory > (numerous large arrays which are dynamically extended). I keep getting > unpredictable crashes (on a machine with 1/2 GB memory) whereas on my > laptop (1 GB memory) it seems OK. Hi Philip, Can you be more specific about what you mean by "crash"? Does the whole operating system freeze, or do you get an error message from Python, or ...? The reason I ask is because what you see may not necessarily have to do with Python --- there may be lower-level issues such as physical hardware, for example. So more information on symptoms will be very helpful. > There are no debugger messages it just crashes (and reboots the machine > more often than not). Ok, if I understand what you're saying: are you saying that the machine physically reboots without user prompting? If so, that's almost certainly NOT Python then. System reboot means that even your operating system is having difficulty keeping the machine usable. The most likely explanation in this circumstance is that the physical hardware is defective. I'd recommend running diagnostics like a RAM checker. But try running your program on another machine as another data point to support the possibility that perhaps the hardware, and not the software is the issue. > I have to say I have noticed (the programme is basically a > batch-factoring programme for integers) that no matter how I tune gc I > can't get it to reliably free memory in between factoring each integer. How are you measuring this? Note that Python does not necessarily give allocated memory back to the operating system: it keeps a memory pool that it reuses for performance reasons. Is the amount of memory you're using at least bounded? > Because this is a development programme (and for performance reasons) I > use global variables some of which refer to the large arrays. Global variables don't necessarily make programs fast. I would strongly discourage this kind of ad-hoc performance optimization. Don't guess: let the machine tell you where the program is slow. If you really want to make your program fast, use a profiler. Also note that parameter passing from one function to another is a constant-time operation: no object values are being copied. So the cost assumptions you're making about passing large arrays around functions may not be correct. > 1) Does the mere fact that a function cites a variable as global create > a reference which prevents it being collected by gc? This isn't a contributing factor. But global variable values at the toplevel don't die: that's the point about global variables, because they always have at least one reference to them and they're always accessible to the outside. > 3) Is there any way to allocate a pool of available memory to my > programme at the outset from which I can allocate my large arrays? Practially everything in Python is done at runtime, not compile time. At program startup, I suppose you can preallocate some arrays and keep a pool of them for your usage. But are you finding this to be a significant factor in your program, though? Again, before you go ahead with optimization, I'd strongly recommend using a profiler to do a principled analysis of the hotspots of your program. Have you looked at the Python Profiler yet? > I'm keen to solve this because I would like to make my programme > generally available - in every other respect its near complete and > massively outperforms the only other comparable pure python module > (nzmath) which does the same job. If you would like a code review, and if the program is short enough, I'm sure people here would be happy to give some pointers. Good luck to you! From kent37 at tds.net Thu May 4 19:40:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 May 2006 13:40:24 -0400 Subject: [Tutor] Argument check In-Reply-To: <445A36A1.7070804@aon.at> References: <445A36A1.7070804@aon.at> Message-ID: <445A3C88.8040604@tds.net> Gregor Lingl wrote: > Hi all, > > I've a class with a lot of methods, for which I'd like to check argument types. You're not the first person to want to do this. You might be interested in these: http://www.artima.com/weblogs/viewpost.jsp?thread=155123 http://www.python.org/dev/peps/pep-0246/ including the references in both cases. > but then chackargs had to get information about its caller (name, locals) from > elsewhere (the callstack?). I don't know if this is possible at all, not to say > how to accomplish it. See this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent From ewald.ertl at hartter.com Thu May 4 19:47:05 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 04 May 2006 19:47:05 +0200 Subject: [Tutor] Argument check In-Reply-To: <445A36A1.7070804@aon.at> References: <445A36A1.7070804@aon.at> Message-ID: <445A3E19.9080904@hartter.com> Hi Gregor, Maybe the module traceback could help you here. It has same functions to extract the actual stack of the program. HTH Ewald Gregor Lingl wrote: > Hi all, > > I've a class with a lot of methods, for which I'd like to check argument types. > To show you, what I mean, I've written a prototype I'm not really content with. > It goes like this (a bit revised in order to have short codelines (*mail* ;-)): > > class BadArgError(Exception): > def __init__(self, fname, var, typ, val): > self.fname = fname > self.var = var > self.typ = typ > self.val = val > def __str__(self): > return """ > %s: argument %s must be %s! > %s of %s given.""" % ( self.fname, self.var, > self.typ, repr(self.val), type(self.val)) > > def checkargs(fun,locs,*typelist): > varnames=fun.im_func.func_code.co_varnames[1:] > fn = fun.__name__ > for var, typ in zip(varnames, typelist): > ok = isinstance(locs[var],typ) > if not ok: > raise BadArgError(fn, var, typ, locs[var]) > > ## classe for testing: > > class Z(object): > pass > > class A(object): > def f(self,x,y): > checkargs(self.f, locals(), int, str) > def g(self,a,b,c): > checkargs(self.g, locals(), (int,float), Z, tuple) > > > BadArgError works like this (interactive session): > > >>> bae = BadArgError("myfun", "myvar", str, 3) > >>> raise bae > > Traceback (most recent call last): > File "", line 1, in -toplevel- > raise bae > BadArgError: > myfun: argument myvar must be ! > 3 of given. > > You see, I want to the error-message to display the name of the function, which > got the bad argument, the name of the parameter and it's expected type as well > as the wrong argument. > > Examples for it's use: > > >>> z=Z() > >>> a=A() > >>> a.f(1,"a") #ok > >>> a.f(1,2) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > ... > raise BadArgError(fn, var, typ, locs[var]) > BadArgError: > f: argument y must be ! > 2 of given. > >>> a.g(.5, z, ()) #ok > >>> a.g(.5, a, ()) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > ... > raise BadArgError(fn, var, typ, locs[var]) > BadArgError: > g: argument b must be ! > <__main__.A object at 0x00C92F70> of given. > > (One could easily tidy up this output - that's *not* the problem) > > I feel it to be cumbersome and ugly, to have to pass the function (method) and > the locals() dictionary to every call of checkargs. > > I'd very much prefer a usage of checkargs similar to: > > class A(object): > def f(self,x,y): > checkargs(int, str) > def g(self,a,b,c): > checkargs((int,float), Z, tuple) > > but then chackargs had to get information about its caller (name, locals) from > elsewhere (the callstack?). I don't know if this is possible at all, not to say > how to accomplish it. > > Do you have some hints? > Where could I find code-examples which solve similar problems? > Would you recommend a different approach? > > Regards, > > Gregor > > > > > -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From marichar at csusb.edu Thu May 4 22:46:07 2006 From: marichar at csusb.edu (Matt Richardson) Date: Thu, 04 May 2006 13:46:07 -0700 Subject: [Tutor] sockets In-Reply-To: <445A2EB9.3010604@tds.net> References: <44593837.5070605@csusb.edu> <44595D02.2000604@tds.net> <445A2A8A.40308@csusb.edu> <445A2EB9.3010604@tds.net> Message-ID: <445A680F.1090509@csusb.edu> Kent Johnson wrote: > > This would be very easy to do with XML-RPC. On the server side, writ a > function that takes three parameters - the IP address, MAC address, and > traceroute dump - and saves them to a database. Use SimpleXMLRPCServer > to expose the function. On the client side, gather the data and use > xmlrpclib to call the remote function. Easy. Since this function will > presumably be exposed on the public internet you need to worry about > security; you should use some kind of authorization. A really simple > solution would be to add username and password arguments to the function > you expose. I thought that might be overkill after quickly glancing at it in 'Foundations of Python Network Programming', but I think you might have just convinced me that it is actually the easier route. My original thought was that it could be just a simple string, sent via UDP, that would happen after networking was established but before log in. I had done something simpler before using a bash script and sendmail, but I really don't want my inbox plugged up with a bunch of 'phone home' messages :) Matt From alan.gauld at freenet.co.uk Fri May 5 00:48:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 4 May 2006 23:48:00 +0100 Subject: [Tutor] Memory Management etc References: <002f01c66f5e$36ce8170$16792d52@PANDORA> Message-ID: <009e01c66fcc$cc085ef0$0c01a8c0@XPpro> > I use Activestate Python (2.4.3) in a Windows 32 bit environment. > > I have a problem with a large programme that uses a lot of memory > (numerous large arrays which are dynamically extended). > I keep getting unpredictable crashes (on a machine with 1/2 GB > memory) > whereas on my laptop (1 GB memory) it seems OK. How are you running it? Double clicjk in explorer? >From within the IDE? or using C:\> python foo.py If the latter try using the -i option (and if you use a lot of docstrings -OO) Otherwise without seeing the code its hard to say, but it doesn't sound like memory probnlems to me - that should just make it run slowly in virtual memory. HTH, Alan G. From jjabson at yahoo.com Fri May 5 00:48:35 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Thu, 4 May 2006 15:48:35 -0700 (PDT) Subject: [Tutor] HELP: using popen2/popen3 Message-ID: <20060504224836.83073.qmail@web53709.mail.yahoo.com> Hello, I'm trying to start a shell script from my python script using os.spawnlp. But I'm not getting msgs from stderr. I thought that I could use popen2/popen3 to replace os.spawnlp but I'm having problems with syntax and how to do this. Can someone point me in the right direction? Here's my original script (w/o using popen2/popen3): import os import sys #################### #### Definition #### #################### def set_up(): print "=== Starting Setup ===" os.chdir('/home/qauser/jerome') os.spawnlp(os.P_WAIT, '/home/qauser/jerome/qaSetup.sh') print "=== Setup Complete ===" #################### ###### Main ###### #################### set_up() I was trying to replace the os.spawnlp with: sout, sin, serr = os.open('/home/qauser/jerome/qaSetup.sh') sout.readlines() serr.readlines() sout.close() serr.close() sin.close() Many thanks, Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From hugonz-lists at h-lab.net Fri May 5 05:20:07 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 04 May 2006 21:20:07 -0600 Subject: [Tutor] sockets In-Reply-To: <445A2A8A.40308@csusb.edu> References: <44593837.5070605@csusb.edu> <44595D02.2000604@tds.net> <445A2A8A.40308@csusb.edu> Message-ID: <445AC467.7070206@h-lab.net> Matt Richardson wrote: > I need to send some data, 2 strings and a list, to a remote computer. > After thinking about it some last night, it wouldn't be hard to just > send it all as a string and then parse it on the receiving end. Well if the excercise itself is not parsing a string, you can just use pickle to serialize your objects. Look up the documentation for the pickle module. You can transform many objects into byte streams and then send them over the network. Hugo From philipasmith at blueyonder.co.uk Fri May 5 08:21:33 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Fri, 5 May 2006 07:21:33 +0100 Subject: [Tutor] Memory Management etc References: <002f01c66f5e$36ce8170$16792d52@PANDORA> <009e01c66fcc$cc085ef0$0c01a8c0@XPpro> Message-ID: <002501c6700c$28008900$16792d52@PANDORA> Hi Thanks for response. Tried this both in IDE and DOS window including under pdb. No docstrings used at present. -i option won't help either as the machine generally reboots - python reports no problems at all. The reason I think it is memory is that the amount of memory available to the programme is the only variable - I'm using two identical hardware/software environments apart from this. Neither machine ever crashes on anything else. The only extraordinary thing about the programme (apart from performance) is the huge amount of dynamic data it uses. Thanks anyway Phil ----- Original Message ----- From: "Alan Gauld" To: "Philip Smith" ; Sent: Thursday, May 04, 2006 11:48 PM Subject: Re: [Tutor] Memory Management etc >> I use Activestate Python (2.4.3) in a Windows 32 bit environment. >> >> I have a problem with a large programme that uses a lot of memory >> (numerous large arrays which are dynamically extended). >> I keep getting unpredictable crashes (on a machine with 1/2 GB memory) >> whereas on my laptop (1 GB memory) it seems OK. > > How are you running it? > Double clicjk in explorer? > From within the IDE? > or using > > C:\> python foo.py > > If the latter try using the -i option (and if you use a lot of > docstrings -OO) > > Otherwise without seeing the code its hard to say, but it doesn't > sound like memory probnlems to me - that should just make it > run slowly in virtual memory. > > HTH, > > Alan G. > > > From janos.juhasz at VELUX.com Fri May 5 08:23:00 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 5 May 2006 08:23:00 +0200 Subject: [Tutor] sockets In-Reply-To: Message-ID: Hi Matt, the traceroute can be done from the client side or eigther from the server side. The two ones should give the same result with reverse order. In this case you can do the tracerouting from the server side when the client ask it. I am just thinking about a simple finger deamon, that can do the job for you. You can ask the deamon, with a simple finger request. Finger.exe is part of th MS system so c:\>finger %username%@myserver.com seems to be enough in the login process. This is the simplest fingerdeamon: import SocketServer, os, string class FingerHandler(SocketServer.StreamRequestHandler): def handle(self): username = self.rfile.readline(512) username = string.strip(username) # Just do your job here # Do the traceroute, and save the result if __name__ == '__main__': server = SocketServer.TCPServer( ('', 79), FingerHandler) server.serve_forever() Matt wrote --- Date: Thu, 04 May 2006 09:23:38 -0700 From: Matt Richardson Subject: Re: [Tutor] sockets To: Tutor at python.org Message-ID: <445A2A8A.40308 at csusb.edu> Content-Type: text/plain; charset=ISO-8859-1; format=flowed I need to send some data, 2 strings and a list, to a remote computer. After thinking about it some last night, it wouldn't be hard to just send it all as a string and then parse it on the receiving end. I'm writing a program for work (and for a class project, so no answers!) that will provide some info on the network location of a laptop. The client will gather IP address, MAC address, and a traceroute dump (the list mentioned above), then send this off to a super simple server that receives the data and puts it in a database. We've had a few laptops 'disappear' either through theft or people taking them home to do 'work from home' or whatever. Makes annual inventory a huge pain. Matt Yours sincerely, ______________________________ Janos Juhasz From philipasmith at blueyonder.co.uk Fri May 5 08:30:02 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Fri, 5 May 2006 07:30:02 +0100 Subject: [Tutor] Memory Management etc References: <002f01c66f5e$36ce8170$16792d52@PANDORA> Message-ID: <002b01c6700d$57721d60$16792d52@PANDORA> Hi Thanks for response. I'm pretty sure for one reason and another that hardware is not at fault. I use the windows monitor to track memory usage. I must say I hadn't realised that Python doesn't release memory back to the OS - someone else advised me to try the alpha 2.5 version which cures this problem - I have but regretably the same problem keeps occurring. The programme is about 600 lines and I'd be loth to let anyone have it in its current form until I understand this problem. Interestingly I have programmed this in 3 different ways - as a class, as a modular programme and (currently) as a single file application (using global variables instead of parameter passing purely because in some cases I was passing and returning up to 20 parameters which seemed clumsy). I have profiled the programme to death and there is no doubt that using globals is faster (this is a time-critical application). However I may translate the current version back into modular or class form and see if the problem vanishes. Regards Phil ----- Original Message ----- From: "Danny Yoo" To: "Philip Smith" Cc: Sent: Thursday, May 04, 2006 6:31 PM Subject: Re: [Tutor] Memory Management etc >> I have a problem with a large programme that uses a lot of memory >> (numerous large arrays which are dynamically extended). I keep getting >> unpredictable crashes (on a machine with 1/2 GB memory) whereas on my >> laptop (1 GB memory) it seems OK. > > Hi Philip, > > Can you be more specific about what you mean by "crash"? Does the whole > operating system freeze, or do you get an error message from Python, or > ...? > > The reason I ask is because what you see may not necessarily have to do > with Python --- there may be lower-level issues such as physical hardware, > for example. So more information on symptoms will be very helpful. > > >> There are no debugger messages it just crashes (and reboots the machine >> more often than not). > > Ok, if I understand what you're saying: are you saying that the machine > physically reboots without user prompting? If so, that's almost certainly > NOT Python then. System reboot means that even your operating system is > having difficulty keeping the machine usable. The most likely explanation > in this circumstance is that the physical hardware is defective. > > I'd recommend running diagnostics like a RAM checker. But try running > your program on another machine as another data point to support the > possibility that perhaps the hardware, and not the software is the issue. > > >> I have to say I have noticed (the programme is basically a >> batch-factoring programme for integers) that no matter how I tune gc I >> can't get it to reliably free memory in between factoring each integer. > > How are you measuring this? > > Note that Python does not necessarily give allocated memory back to the > operating system: it keeps a memory pool that it reuses for performance > reasons. > > Is the amount of memory you're using at least bounded? > > >> Because this is a development programme (and for performance reasons) I >> use global variables some of which refer to the large arrays. > > Global variables don't necessarily make programs fast. I would strongly > discourage this kind of ad-hoc performance optimization. Don't guess: let > the machine tell you where the program is slow. If you really want to make > your program fast, use a profiler. > > Also note that parameter passing from one function to another is a > constant-time operation: no object values are being copied. So the cost > assumptions you're making about passing large arrays around functions may > not be correct. > > > >> 1) Does the mere fact that a function cites a variable as global create >> a reference which prevents it being collected by gc? > > This isn't a contributing factor. But global variable values at the > toplevel don't die: that's the point about global variables, because they > always have at least one reference to them and they're always accessible > to the outside. > > >> 3) Is there any way to allocate a pool of available memory to my >> programme at the outset from which I can allocate my large arrays? > > Practially everything in Python is done at runtime, not compile time. At > program startup, I suppose you can preallocate some arrays and keep a pool > of them for your usage. > > But are you finding this to be a significant factor in your program, > though? Again, before you go ahead with optimization, I'd strongly > recommend using a profiler to do a principled analysis of the hotspots of > your program. Have you looked at the Python Profiler yet? > > > >> I'm keen to solve this because I would like to make my programme >> generally available - in every other respect its near complete and >> massively outperforms the only other comparable pure python module >> (nzmath) which does the same job. > > If you would like a code review, and if the program is short enough, I'm > sure people here would be happy to give some pointers. > > Good luck to you! > From philipasmith at blueyonder.co.uk Fri May 5 08:34:46 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Fri, 5 May 2006 07:34:46 +0100 Subject: [Tutor] Tutor Digest, Vol 27, Issue 12 References: Message-ID: <003901c6700e$0073f410$16792d52@PANDORA> Hi Thanks for response. The programme is pure python (the point is to develop a programme which is as fast as it can be in python without any tricks and then to translate to C). I've tried 2.5 alpha - thanks for the suggestion. It does indeed seem to appropriately return memory to OS but my problem remains. Thanks for the links which have been very useful and for the other tips. Will post to comp.lang.python if I can't sort this out. Phil ----- Original Message ----- From: To: Sent: Thursday, May 04, 2006 5:56 PM Subject: Tutor Digest, Vol 27, Issue 12 > 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: counting number of inputs (EARLIER VERSION SENT > ACCIDENTLY) (MICHELLE EVANS) > 2. Re: Memory Management etc (Kent Johnson) > 3. Re: sockets (Matt Richardson) > 4. Re: sockets (Kent Johnson) > 5. Python challenge (David Holland) > 6. Re: Python challenge (Jason Massey) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 04 May 2006 07:53:40 -0400 > From: "MICHELLE EVANS" > Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT > ACCIDENTLY) > To: "Marc Poulin" , > Message-ID: <001801c66f71$6366b1e0$e1966147 at michelleevans> > Content-Type: text/plain; charset=iso-8859-1 > > This is exactly what I am trying to do. I am so confused with trying to > write this. I am not very familiar with any of the functions. I keep > reading my book and reading my book, and none of it seems to make sense > anymore. I can write extremely simple functions, but when I need to use > more than one in a code, I'm lost! > > Thanks > > ----- Original Message ----- > From: "Marc Poulin" > To: > Sent: Thursday, May 04, 2006 12:08 AM > Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT > ACCIDENTLY) > > >> >> Michelle: >> >> Are you familiar with writing functions? >> Here I've created a function named getInputs. >> >> I've also created a few test cases to verify that (a) >> my understanding of the problem is correct, and (b) my >> solution is correct. >> >> It's important to think about how your program is >> supposed to behave in different situations. Do you >> think these 3 tests are enough to prove that the code >> is correct? >> >> ######################### >> ## start of code ## >> ######################### >> def getInputs(): >> """ >> Description: >> Collect numbers entered by the user (up to a >> maximum of 5 values) and >> store them in the listOfValues. >> >> Stop collecting numbers if the user enters -1 >> or if 5 numbers have been collected. >> >> If the user entered -1, the -1 is NOT returned >> as part of the list. >> """ >> listOfValues = [] ## this list holds the values >> entered by the user >> >> for i in range(5): >> newValue = int(raw_input('Enter a number [-1 >> to exit]:')) >> if newValue == -1: >> # Return right now with whatever is >> currently in the list. >> return listOfValues >> else: >> # Add this new value to the list and keep >> looping. >> listOfValues.append(newValue) >> >> ## If we got this far, it means the user did not >> enter a -1 so >> ## the list contains 5 values. >> return listOfValues >> >> """ >> Here are a few test cases to verify the logic of my >> code. >> >> Test Case 1: >> INPUTS: >> first entered value: -1 >> RESULT: >> function returns empty list >> >> Test Case 2: >> INPUTS: >> first entered value: 1 >> second entered value: 2 >> third entered value: -1 >> RESULT: >> returned list contains [1,2] >> >> Test Case 3: >> INPUTS: >> first entered value: 1 >> second entered value: 2 >> third entered value: 3 >> fourth entered value: 4 >> fifth entered value: 5 >> RESULT: >> returned list contains [1,2,3,4,5] >> """ >> if __name__ == "__main__": >> print getInputs() >> >> ################### >> ## end of code ## >> ################### >> >> >> --- Python wrote: >> >> > On Wed, 2006-05-03 at 15:33 -0400, MICHELLE EVANS >> > wrote: >> > > OK, I've tried a different approach to this. >> > > How do I get this to stop by using -1? >> > > I do not want this to print until either 5 inputs >> > have been entered or -1 >> > > has been entered. See below: >> > > >> > >> > use a "for block" rather than a "while block" to >> > have a normal limit of >> > 5 repetitions: >> > >> > for x in range(5): >> > >> > will repeat 5 times with x running from 0 to 4. >> > x is ignored - unless some use for it does turn up. >> > >> > the break statement allows you to terminate a block, >> > so >> > >> > if number == -1: break >> > >> > will end the for block. >> > >> > >> > Now, one of the cute features in Python is the else >> > clause that goes >> > with the for and while blocks. The else block is >> > executed when there is >> > no break. So the skeleton for your program can look >> > something like >> > >> > for x in range(5): >> > # get inputs and break on -1 >> > else: >> > # no break so just process the inputs >> > >> > Good luck. >> > >> > > # Add number of per hour >> > > numbers = [] >> > > stop = None >> > > while stop != "-1": >> > > number = int(raw_input("Run number(-1 to end) >> > : ")) >> > > numbers.append(number) >> > > print >> > > for number in numbers: >> > > print number >> > > >> > > >> > > >> > > >> > > ----- Original Message ----- >> > > From: "Python" >> > > To: "MICHELLE EVANS" >> > > Cc: "Tutor Python" >> > > Sent: Wednesday, May 03, 2006 12:18 PM >> > > Subject: Re: [Tutor] counting number of inputs >> > (EARLIER VERSION SENT >> > > ACCIDENTLY) >> > > >> > > >> > > > (Tip: Best to use reply-to-all when responding >> > to an email on the list) >> > > > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE >> > EVANS wrote: >> > > > > number1 = int(raw_input("Run number 1 (-1 to >> > end) : ")) >> > > > > number2 = int(raw_input("Run number 2 (-1 to >> > end) : ")) >> > > > > number3 = int(raw_input("Run number 3 (-1 to >> > end) : ")) >> > > > > number4 = int(raw_input("Run number 4 (-1 to >> > end) : ")) >> > > > > number5 = int(raw_input("Run number 5 (-1 to >> > end) : ")) >> > > > Good. You collect the string from raw_input and >> > convert it to an >> > > > integer. >> > > > >> > > > This will prompt for 5 inputs, but it is missing >> > any logic to actually >> > > > break if -1 is entered. With a language like >> > BASIC, you could stick in >> > > > tests sort of like: >> > > > if number1 == -1 goto done: >> > > > BUT Python does not have a goto. So we actually >> > need some "flow >> > > > control" around the block of code where you >> > collect inputs. >> > > > >> > > > while blocks process an indefinite number of >> > times while a test >> > > > condition is True. >> > > > >> > > > for blocks iterate through a sequence until they >> > reach the end. By >> > > > providing a sequence with the correct count, you >> > can repeat the block >> > > > the correct number of times. The range (and >> > xrange for big sequences) >> > > > functions provide a sequence of integers that >> > can be used conveniently >> > > > with for. >> > > > >> > > > The easiest way to fix your code above would be >> > something like: >> > > > ask_for_number = True >> > > > while ask_for_number: >> > > > number1 = .... >> > > > if number1 == -1: break >> > > > ... >> > > > number5 = ... >> > > > ask_for_number = False >> > > > >> > > > HOWEVER, that is not a good approach in the long >> > run. >> > > > >> > > > A better approach is to have a single container >> > to hold all of the >> > > > inputs. For this, Python provides lists. >> > Rather than have 5 separate >> > > > variables, use a single list variable to hold >> > all of the inputs. Then >> > > > use a "for block" to ask for the input and put >> > the result into the list. >> > > > You already know how to convert the input from a >> > string to a number. >> > > > >> > > > If you have trouble figuring out lists and for >> > blocks, ask for help. >> > > > >> > > > (Sorry about the extra email. I forgot and used >> > ad editor hot-key combo >> > > > in my email program which sent the email.) >> > > > >> > > > >> > > > > >> > > > > >> > > > > # The following will sum the numbers and then >> > print the answer >> > > > > sum = number1 + number2 + number3 + number4 + >> > number5 >> > > > > print >> > > > > print "The total number of parts produced >> > was:", sum,"." >> > > > > >> > > > > I need this to ask the user to enter their >> > number per each run. That is >> > > why >> > > > > I have 5 different input numbers. I need this >> > break if a -1 is entered. >> > > > > Would I use "if-else" to break this if -1 is >> > entered? I need to be able >> > > to >> > > > > count the number of lines entered. >> > > > > >> > > > > Thanks >> > > > > Rick >> > > > > >> > > > > >> > > > > ----- Original Message ----- >> > > > > From: "Python" >> > > > > To: "MICHELLE EVANS" >> > > > > Cc: "Tutor Python" >> > > > > Sent: Tuesday, May 02, 2006 7:56 PM >> > > > > Subject: Re: [Tutor] counting number of inputs >> > > > > >> > > > > >> > > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE >> > EVANS wrote: >> > > > > > > I am trying to count the number of times a >> > positive number is >> > > entered >> > > > > > > from the user. But, the program must stop >> > after 5 user inputs or a >> > > > > > > negative number. >> > > > > > > >> > > > > > > Can anyone help. >> > > > > > Yes, but you need to help yourself also. >> > > > > > >> > > > > > Do you know how to get input from the user? >> > > > > > Do you know how to count things in Python? >> > > > > > Do you know how to test a number to see if >> > it is positive or negative? >> > > > > > >> > > > > > Why don't you post your code for any part of >> > this problem and explain >> > > > > > how it is supposed to work and where you are >> > having difficulty. If >> > > > > > necessary, review some of the tutorials to >> > get some pointers on >> > > writing >> > > > > > Python programs. >> > > > > > >> > > > > > We're happy to help you learn, but do not >> > want to simply write your >> > > > > > program for you. >> > > > > > >> > >> === message truncated === >> >> >> __________________________________________________ >> 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 >> > > > > ------------------------------ > > Message: 2 > Date: Thu, 04 May 2006 08:33:46 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Memory Management etc > Cc: tutor at python.org > Message-ID: <4459F4AA.9000405 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Philip Smith wrote: >> Hi >> >> I use Activestate Python (2.4.3) in a Windows 32 bit environment. >> >> I have a problem with a large programme that uses a lot of memory >> (numerous large arrays which are dynamically extended). I keep getting >> unpredictable crashes (on a machine with 1/2 GB memory) whereas on my >> laptop (1 GB memory) it seems OK. > > I'm way out of my expertise here but I'll give it a try... > > Is your program pure Python or are you using C extensions (other than > the ones in the standard library)? If it is pure Python I think this > would be considered a Python bug and would interest the Python developers. > >> The portion of the code which crashes varies a bit but curiously is >> NEVER a part where any memory allocation is happening. > > Can you post any code? If you can make a short test program that shows > the problem that will dramatically increase your chances of getting > useful help. > >> I have to say I have noticed (the programme is basically a >> batch-factoring programme for integers) that no matter how I tune gc I >> can't get it to reliably free memory in between factoring each integer. > > I don't think Python will ever release memory back to the OS. This has > changed in Python 2.5, you might be interested in trying the alpha > release: > http://docs.python.org/dev/whatsnew/section-other.html > http://www.python.org/download/releases/2.5/ > >> >> Because this is a development programme (and for performance reasons) I >> use global variables some of which refer to the large arrays. >> >> My questions are: >> >> 1) Does the mere fact that a function cites a variable as global >> create a reference which prevents it being collected by gc? > > You mean a 'global' statement without actually using the named variable? > I don't know if this creates a reference, but if so, the reference > should go out of scope when the function exits. > >> 5) Does anyone have ANY suggestions please? > > These links might be interesting: > http://tinyurl.com/pszzh > http://evanjones.ca/python-memory.html > http://pysizer.8325.org/ > > Asking on comp.lang.python will give you access to many more people > familiar with Python internals than you will find on this list. >> >> I'm keen to solve this because I would like to make my programme >> generally available - in every other respect its near complete and >> massively outperforms the only other comparable pure python module >> (nzmath) which does the same job. >> >> Thanks in anticipation. >> >> Phil >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > > > ------------------------------ > > Message: 3 > Date: Thu, 04 May 2006 09:23:38 -0700 > From: Matt Richardson > Subject: Re: [Tutor] sockets > To: Tutor at python.org > Message-ID: <445A2A8A.40308 at csusb.edu> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > I need to send some data, 2 strings and a list, to a remote computer. > After thinking about it some last night, it wouldn't be hard to just > send it all as a string and then parse it on the receiving end. > > I'm writing a program for work (and for a class project, so no answers!) > that will provide some info on the network location of a laptop. The > client will gather IP address, MAC address, and a traceroute dump (the > list mentioned above), then send this off to a super simple server that > receives the data and puts it in a database. We've had a few laptops > 'disappear' either through theft or people taking them home to do 'work > from home' or whatever. Makes annual inventory a huge pain. > > Matt > > -- > Matt Richardson > IT Consultant > College of Arts and Letters > CSU San Bernardino > (909)537-7598 > > > > ------------------------------ > > Message: 4 > Date: Thu, 04 May 2006 12:41:29 -0400 > From: Kent Johnson > Subject: Re: [Tutor] sockets > Cc: Tutor at python.org > Message-ID: <445A2EB9.3010604 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Matt Richardson wrote: >> I need to send some data, 2 strings and a list, to a remote computer. >> After thinking about it some last night, it wouldn't be hard to just >> send it all as a string and then parse it on the receiving end. >> >> I'm writing a program for work (and for a class project, so no answers!) >> that will provide some info on the network location of a laptop. The >> client will gather IP address, MAC address, and a traceroute dump (the >> list mentioned above), then send this off to a super simple server that >> receives the data and puts it in a database. We've had a few laptops >> 'disappear' either through theft or people taking them home to do 'work >> from home' or whatever. Makes annual inventory a huge pain. > > This would be very easy to do with XML-RPC. On the server side, writ a > function that takes three parameters - the IP address, MAC address, and > traceroute dump - and saves them to a database. Use SimpleXMLRPCServer > to expose the function. On the client side, gather the data and use > xmlrpclib to call the remote function. Easy. Since this function will > presumably be exposed on the public internet you need to worry about > security; you should use some kind of authorization. A really simple > solution would be to add username and password arguments to the function > you expose. > > You could do all this with the socket library but XML-RPC takes care of > all the details of connections, etc as well as marshalling and > unmarshalling the data. > > Kent > > > > ------------------------------ > > Message: 5 > Date: Thu, 4 May 2006 17:50:20 +0100 (BST) > From: David Holland > Subject: [Tutor] Python challenge > To: tutor python > Message-ID: <20060504165020.15946.qmail at web25915.mail.ukl.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > I looked at this and got stuck on the first one :- > http://www.pythonchallenge.com/pc/def/0.html > It says try changing the url. > I assumed that it either meant 2*38 or 2 to the power of 38 but I can't > see how to put either of those in the url. > > What have I missed ? > > Thanks in advance. > > David Holland > > > --------------------------------- > Yahoo! Photos ? NEW, now offering a quality print service from just 7p a > photo. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060504/ec6d3dca/attachment-0001.html > > ------------------------------ > > Message: 6 > Date: Thu, 4 May 2006 11:56:02 -0500 > From: "Jason Massey" > Subject: Re: [Tutor] Python challenge > To: "David Holland" > Cc: tutor python > Message-ID: > <7e3eab2c0605040956o389cf610l8cebfea6cf1acf13 at mail.gmail.com> > Content-Type: text/plain; charset="windows-1252" > > David, > > What answer did you get? One of the things to rember on the challenge is > to > take your answer and put ".html" (no qutoes) on the end of it in the url. > > So for the first problem the url would be: > > http://www.pythonchallenge.com/pc/def/.html > > On 5/4/06, David Holland wrote: >> >> I looked at this and got stuck on the first one :- >> http://www.pythonchallenge.com/pc/def/0.html >> It says try changing the url. >> I assumed that it either meant 2*38 or 2 to the power of 38 but I can't >> see how to put either of those in the url. >> >> What have I missed ? >> >> Thanks in advance. >> >> David Holland >> >> ------------------------------ >> *Yahoo! >> Photos*? >> NEW, now offering a quality print >> servicefrom >> just 7p a photo. >> >> >> _______________________________________________ >> 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/20060504/9ab893b8/attachment.htm > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 27, Issue 12 > ************************************* > From alan.gauld at freenet.co.uk Fri May 5 09:18:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 5 May 2006 08:18:01 +0100 Subject: [Tutor] Memory Management etc References: <002f01c66f5e$36ce8170$16792d52@PANDORA><009e01c66fcc$cc085ef0$0c01a8c0@XPpro> <002501c6700c$28008900$16792d52@PANDORA> Message-ID: <00d901c67014$0b2f1690$0c01a8c0@XPpro> > The reason I think it is memory is that the amount of memory > available to the programme is the only variable - I'm using two > identical hardware/software environments apart from this. I assume from this that you have explicitly turned off virtual memory on both machines? > crashes on anything else. The only extraordinary thing about the > programme (apart from performance) is the huge amount of dynamic > data it uses. Have you checked Dr Watson debugging? That should capture the memory image at the time of the crash. Although if you have turned off virtual memory that might not work! You should be able to see the dr watson logfuile after rebooting the pc. Alan G From alan.gauld at freenet.co.uk Fri May 5 09:24:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 5 May 2006 08:24:29 +0100 Subject: [Tutor] Memory Management etc References: <002f01c66f5e$36ce8170$16792d52@PANDORA> <002b01c6700d$57721d60$16792d52@PANDORA> Message-ID: <00e601c67014$f25436e0$0c01a8c0@XPpro> > realised that Python doesn't release memory back to the OS - someone > else That's not at all unusual. In fact in most Unices no program ever releases memory to the OS - one reason you should be very careful when writing daemon processes! One advantage of this approach is that it speeds up memory allocation when the memory needs to be reused by the application since its already there waiting to be used. It also acts as a resilience feature by ensuring that running programs don;t get all their memory stolen by some new startup app that grabs all thats available. The reasoning being that its better to have a program crash early than late... Alan G From samrobertsmith at gmail.com Fri May 5 12:30:10 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 5 May 2006 03:30:10 -0700 Subject: [Tutor] why different Message-ID: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> I run a code, which import Numeric module. When I run the code from PythonWin, it is OK. But when I run it from the command line, it reported "Importerror: No Module named Numeric." Why the systems perform differently? Linda -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060505/e9e9d6c9/attachment.html From ml.cyresse at gmail.com Fri May 5 14:01:03 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 6 May 2006 00:01:03 +1200 Subject: [Tutor] Memory Management etc In-Reply-To: <00e601c67014$f25436e0$0c01a8c0@XPpro> References: <002f01c66f5e$36ce8170$16792d52@PANDORA> <002b01c6700d$57721d60$16792d52@PANDORA> <00e601c67014$f25436e0$0c01a8c0@XPpro> Message-ID: There's a specific Python gotcha involving memory allocation and pymalloc, that'll manifest with large amounts of integers. http://evanjones.ca/python-memory.html And, according to that article, it's as Kent said, fixed in 2.5 :) Regards, Liam Clarke On 5/5/06, Alan Gauld wrote: > > realised that Python doesn't release memory back to the OS - someone > > else > > That's not at all unusual. In fact in most Unices no program ever > releases > memory to the OS - one reason you should be very careful when writing > daemon processes! One advantage of this approach is that it speeds up > memory allocation when the memory needs to be reused by the > application > since its already there waiting to be used. It also acts as a > resilience > feature by ensuring that running programs don;t get all their memory > stolen by some new startup app that grabs all thats available. The > reasoning being that its better to have a program crash early than > late... > > Alan G > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Fri May 5 14:01:37 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 6 May 2006 00:01:37 +1200 Subject: [Tutor] Memory Management etc In-Reply-To: References: <002f01c66f5e$36ce8170$16792d52@PANDORA> <002b01c6700d$57721d60$16792d52@PANDORA> <00e601c67014$f25436e0$0c01a8c0@XPpro> Message-ID: Oh dear, I see Kent already posted that linked. Haha. On 5/6/06, Liam Clarke wrote: > There's a specific Python gotcha involving memory allocation and > pymalloc, that'll manifest with large amounts of integers. > > http://evanjones.ca/python-memory.html > > And, according to that article, it's as Kent said, fixed in 2.5 :) > > Regards, > > Liam Clarke > > On 5/5/06, Alan Gauld wrote: > > > realised that Python doesn't release memory back to the OS - someone > > > else > > > > That's not at all unusual. In fact in most Unices no program ever > > releases > > memory to the OS - one reason you should be very careful when writing > > daemon processes! One advantage of this approach is that it speeds up > > memory allocation when the memory needs to be reused by the > > application > > since its already there waiting to be used. It also acts as a > > resilience > > feature by ensuring that running programs don;t get all their memory > > stolen by some new startup app that grabs all thats available. The > > reasoning being that its better to have a program crash early than > > late... > > > > Alan G > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Fri May 5 14:10:38 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 6 May 2006 00:10:38 +1200 Subject: [Tutor] why different In-Reply-To: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> References: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> Message-ID: Hi, Can you please copy and paste the code here? Also, can you please click on Start, select Run, and type cmd.exe, and in the new window that opens type the following command: C:\>echo %PATH% and then right click, select Mark, select the text that was outputted and press enter to copu it and paste it here also? Lastly, what directory are you running your code from? Regards, Liam Clarke On 5/5/06, linda.s wrote: > I run a code, which import Numeric module. When I run the code from > PythonWin, it is OK. > But when I run it from the command line, it reported "Importerror: No > Module named Numeric." > Why the systems perform differently? > Linda > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From clajo04 at mac.com Fri May 5 17:27:54 2006 From: clajo04 at mac.com (John Clark) Date: Fri, 05 May 2006 11:27:54 -0400 Subject: [Tutor] Nested list comprehensions Message-ID: <1107400.1146842874915.JavaMail.clajo04@mac.com> Hello Tutors, I am having trouble wrapping my mind around nested list comprehensions and am hoping that someone can either verify my thinking or provide insight as to what I am doing wrong. I have a list of objects C1 and each object in the list has a method m() that will return a list of sub-objects. I would like to create a list that contains all sub-objects of all members of the C1 collection. If I weren't trying to use list comprehensions, I would code this as: result = [] for eachObject in C1: for eachSubObject in eachObject.m(): result.append(eachSubObject) I have looked at the examples in the books several times, but none of the examples on nested list comprehensions show situations where there is a dependency between the outer loop and the inner loop that are being compressed. However, what I think I have come up with is: result = [eachSubObject for eachObject in C1 for eachSubObject in eachObject.m()] I am already expecting the "just use the first syntax if that does what you want" answers - but in this case, I am trying to understand nested list comprehensions, so I would appreciate an explanation of the list comprehension syntax. If this _is_ the correct syntax, this reads very awkwardly to me, and my initial reaction to this is that it should be expressed as: result = [eachSubObject for eachSubObject in eachObject.m() for eachObject in C1] However, in my testing, this doesn't appear to work. If somone has a way of reading the nested list comprehension syntax that makes sense, I would appreciate it if you would share it. Thanks, -John From kent37 at tds.net Fri May 5 17:53:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 05 May 2006 11:53:39 -0400 Subject: [Tutor] Nested list comprehensions In-Reply-To: <1107400.1146842874915.JavaMail.clajo04@mac.com> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> Message-ID: <445B7503.60003@tds.net> John Clark wrote: > Hello Tutors, > > I am having trouble wrapping my mind around nested list > comprehensions and am hoping that someone can either verify my > thinking or provide insight as to what I am doing wrong. > > If I weren't trying to use list comprehensions, I would > code this as: > > result = [] > for eachObject in C1: > for eachSubObject in eachObject.m(): > result.append(eachSubObject) > > what I think I have come up with is: > > result = [eachSubObject for eachObject in C1 for eachSubObject in eachObject.m()] This is the correct equivalent. > If this _is_ the correct syntax, this reads very awkwardly to me, and > my initial reaction to this is that it should be expressed as: > > result = [eachSubObject for eachSubObject in eachObject.m() for eachObject in C1] FWIW I think it is awkward too. > However, in my testing, this doesn't appear to work. If somone has a > way of reading the nested list comprehension syntax that makes sense, > I would appreciate it if you would share it. I don't know if it makes sense, but the way I think of it is that list comps don't change the order of the 'for x in y' part of the loop, they just move the expression of what to add to the list to the beginning of the code. Kent From doug.shawhan at gmail.com Fri May 5 21:21:52 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 5 May 2006 14:21:52 -0500 Subject: [Tutor] python cgi and html streams Message-ID: <5e1ceb8a0605051221h2b63d85n347bfe625c07acc5@mail.gmail.com> I've been a-googling for examples or information on recieving and parsing html streams in a cgi script. I need to send a request like: '' http://www.foo.com/cgi-bin/responder.cgi?foo=hi&bar=there&bat=buddy&identifier=myname " to a remote server which will then stream a response to my script, similar to what I have grown to expect from cgi.FieldStorage when processing user input. I was hoping for something magical like: gulp = cgi.StreamIO(" http://www.foo.com/cgi-bin/responder.cgi?foo=hi&bar=there&bat=buddy").read() ... but for some reason not one of the python creators foresaw that I might one day need them to do all the thinking, typing and other hard parts for me! So I decided to play around for a while and see what I could happen on my own. I first went to the interpreter: >>> dir(cgi) ['FieldStorage', 'FormContent', 'FormContentDict', 'InterpFormContentDict', 'MiniFieldStorage', 'StringIO', 'SvFormContentDict', 'UserDict', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__version__', 'dolog', 'escape', 'initlog', 'log', 'logfile', 'logfp', 'maxlen', 'mimetools', 'nolog', 'os', 'parse', 'parse_header', 'parse_multipart', 'parse_qs', 'parse_qsl', 'print_arguments', 'print_directory', 'print_environ', 'print_environ_usage', 'print_exception', 'print_form', 'rfc822', 'sys', 'test', 'urllib', 'valid_boundary'] Oho! StringIO seems like it is my baby: dir(cgi.StringIO) ['__doc__', '__init__', '__iter__', '__module__', 'close', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', 'readlines', 'seek', 'tell', 'truncate', 'write', 'writelines'] Right on! GetValue! Read and Write! That looks like the ticket and it appears to work the same way as the usual StringIO module. Now my connundrum: I can't find any examples. I'm guessing what needs to happen is this: meScript --> sends request with an identifier to the remote server. RemoteServer --> sends data back to my meOtherScript (or a routine in meScript) which either pickles the data or stores it in a handy database. while my the first instance of meScript which has now passed the identifier to itself loops around reading from the database until either the identifier (and other data) to show up or the script times out, generating a heartfelt apology. Am I on the right track here? I suspect there is some sort of super easy way to accomplish this, but I am probably missing it. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060505/78d8bfd9/attachment.html From samrobertsmith at gmail.com Fri May 5 22:40:45 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 5 May 2006 13:40:45 -0700 Subject: [Tutor] why different In-Reply-To: References: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> Message-ID: <1d987df30605051340p22045c78v47bffca030dd504b@mail.gmail.com> I have two drives. The python24 is installed in c: and the code is in d: drive (d:\data). so what I did is: d:\data> c:\python24\python test.py On 5/5/06, Liam Clarke wrote: > > Hi, > > Can you please copy and paste the code here? Also, can you please > click on Start, select Run, and type cmd.exe, and in the new window > that opens type the following command: > > C:\>echo %PATH% > > and then right click, select Mark, select the text that was outputted > and press enter to copu it and paste it here also? > > Lastly, what directory are you running your code from? > > Regards, > > Liam Clarke > > On 5/5/06, linda.s wrote: > > I run a code, which import Numeric module. When I run the code from > > PythonWin, it is OK. > > But when I run it from the command line, it reported "Importerror: No > > Module named Numeric." > > Why the systems perform differently? > > Linda > > > > > > _______________________________________________ > > 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/20060505/dada34ce/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri May 5 23:41:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 5 May 2006 14:41:36 -0700 (PDT) Subject: [Tutor] why different In-Reply-To: <1d987df30605051340p22045c78v47bffca030dd504b@mail.gmail.com> References: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> <1d987df30605051340p22045c78v47bffca030dd504b@mail.gmail.com> Message-ID: On Fri, 5 May 2006, linda.s wrote: > I have two drives. The python24 is installed in c: and the code is in d: > drive (d:\data). > so what I did is: > d:\data> c:\python24\python test.py Hi Linda, Can you copy and paste the code to test.py? I suspect that the code does not contain a necessary import statement, but without seeing the code, we can't really say what's going on. Also, just off-hand: do you have several versions of Python on your system? I see you have Python 2.4. Do you know if you have another version of Python installed? The reason we ask is because of the following scenario: one possibility is that the Numeric module is installed for another version of Python --- the one you're running with PythonWin --- and that would also explain the symptoms. But this is only a possibility; let's learn a little more about the situation. From dyoo at hkn.eecs.berkeley.edu Fri May 5 23:49:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 5 May 2006 14:49:34 -0700 (PDT) Subject: [Tutor] python cgi and html streams In-Reply-To: <5e1ceb8a0605051221h2b63d85n347bfe625c07acc5@mail.gmail.com> References: <5e1ceb8a0605051221h2b63d85n347bfe625c07acc5@mail.gmail.com> Message-ID: > I was hoping for something magical like: > > gulp = cgi.StreamIO(" > http://www.foo.com/cgi-bin/responder.cgi?foo=hi&bar=there&bat=buddy").read() > > ... but for some reason not one of the python creators foresaw that I might > one day need them to do all the thinking, typing and other hard parts for > me! Hi Doug, Try the 'urllib' client library. http://www.python.org/doc/lib/module-urllib.html The CGI server library is meant for servers, say, for the person who would be implmenting responder.cgi. If you need to do more complicated interactions as a client, then something like Mechanize might also do the trick: http://wwwsearch.sourceforge.net/mechanize/ but I'd recommend looking into urllib first to see if it's sufficient for your problem. > Oho! StringIO seems like it is my baby: > > dir(cgi.StringIO) > ['__doc__', '__init__', '__iter__', '__module__', 'close', 'flush', > 'getvalue', 'isatty', 'next', 'read', 'readline', 'readlines', 'seek', > 'tell', 'truncate', 'write', 'writelines'] Gotta cut you off there. This isn't what you want: it just turns out that the implementation of 'cgi' uses the StringIO Standard Library: http://www.python.org/doc/lib/module-StringIO.html but that's an internal detail of 'cgi' that you shouldn't need to worry about. > Am I on the right track here? I suspect there is some sort of super easy > way to accomplish this, but I am probably missing it. You are on the wrong track. *wink* No, you were sorta in the right direction, and your instincts are good. But next time, try looking at the documentation too --- it's good to practice using the reference docs. The documentation's at: http://www.python.org/doc/lib/ The Python Cookbook is also a good place to find out which libraries are relevant to the thing you're doing: http://aspn.activestate.com/ASPN/Python/Cookbook/ Best of wishes! From mcarlsen at sbcglobal.net Fri May 5 23:42:07 2006 From: mcarlsen at sbcglobal.net (Mitchel Carlsen) Date: Fri, 5 May 2006 14:42:07 -0700 (PDT) Subject: [Tutor] Calling one python module from another Message-ID: <20060505214207.86881.qmail@web82410.mail.mud.yahoo.com> Is there an easy way to call on python module (called.py) from another (calling.py)? I have been able to do this using 'rc = os.system("called.py")' . Is this the suggested method? Thanks, Mitch -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060505/0644de07/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri May 5 23:58:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 5 May 2006 14:58:01 -0700 (PDT) Subject: [Tutor] Calling one python module from another In-Reply-To: <20060505214207.86881.qmail@web82410.mail.mud.yahoo.com> References: <20060505214207.86881.qmail@web82410.mail.mud.yahoo.com> Message-ID: On Fri, 5 May 2006, Mitchel Carlsen wrote: > Is there an easy way to call on python module (called.py) from another > (calling.py)? I have been able to do this using 'rc = > os.system("called.py")' . Is this the suggested method? Hi Mitch, If you are looking for modules, you may want to take a look at a tutorial on them. Here's a link for Alan's tutorial: http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm There's also a section on them from the official Python tutorial: http://www.python.org/doc/tut/node8.html Read those sections first, and you should be able to solve the problem you have. If you have questions, please feel free to ask. 'os.system()' is not ideal for interacting with another Python module, since the data channel between separate processes is a bit impovershed and uni-directional. However, one could use os.system() to talk to other shell commands besides Python. From Malcolm.S.Britton at frb.gov Sat May 6 00:42:20 2006 From: Malcolm.S.Britton at frb.gov (Malcolm.S.Britton at frb.gov) Date: Fri, 5 May 2006 18:42:20 -0400 Subject: [Tutor] Malcolm S Britton is out of the office. Message-ID: I will be out of the office starting 05/05/2006 and will not return until 05/09/2006. I will respond to your message when I return. From alan.gauld at freenet.co.uk Sat May 6 01:55:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 6 May 2006 00:55:41 +0100 Subject: [Tutor] Nested list comprehensions References: <1107400.1146842874915.JavaMail.clajo04@mac.com> Message-ID: <013b01c6709f$6af15670$0c01a8c0@XPpro> > I am having trouble wrapping my mind around > nested list comprehensions I do too, and usually when that happens I take it as a sign that I'm being too clever for my own good. I unwrap things back to the point where my brain doesn't hurt anymore... I think I've only seen two or three nested comprehensions that I could easily read. Mostly they should be avoided IMHO! > I have a list of objects C1 and each object in the list has > a method m() that will return a list of sub-objects. > I would like to create a list that contains all > sub-objects of all members of the C1 collection. > If I weren't trying to use list comprehensions, I would code this > as: > > result = [] > for eachObject in C1: > for eachSubObject in eachObject.m(): > result.append(eachSubObject) Which makes perfect sense and is definitely the way I'd go. However... > result = [eachSubObject for eachObject in C1 for eachSubObject in > eachObject.m()] Yep, that looks right to me. > I am already expecting the "just use the first syntax if that does > what you want" > answers - but in this case, I am trying to understand nested list > comprehensions, > so I would appreciate an explanation of the list comprehension > syntax. Since you want to understand the syntax... [ for item1 in sequence1 for item2 in sequence2... for itemN in sequenceN ] So your LC becomes: [eachSubObject for eachObject in C1 for eachSubObject in eachObject.m() ] > If this _is_ the correct syntax, this reads very awkwardly to me, Does the layout above look any better? I find breaking nested LCs doen into that structure makes them easier to figure out. > and my initial reaction to this is that it should be expressed as: > > result = [eachSubObject for eachSubObject in eachObject.m() for > eachObject in C1] My take on that is that it doesn't work from a scoping point of view. You have to fetch eachObject before you can send m() to it. Doing it the way you have it here would involve calling eachObject.m() before eachObject had been fetched from C1 > However, in my testing, this doesn't appear to work. > If somone has a way of reading the nested list comprehension > syntax that makes sense, I would appreciate it if you would share > it. I dunno if my ramblings help, but its how I read nested LOCs when I'm forced into that situation. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From samrobertsmith at gmail.com Sat May 6 07:45:42 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 5 May 2006 22:45:42 -0700 Subject: [Tutor] why different In-Reply-To: References: <1d987df30605050330w71de3341yf6b3ba43f5f76cee@mail.gmail.com> <1d987df30605051340p22045c78v47bffca030dd504b@mail.gmail.com> Message-ID: <1d987df30605052245m5d415ff3y37a9c2761b9bf0ca@mail.gmail.com> You are right. When I switch to python23 folder, it works. On 5/5/06, Danny Yoo wrote: > > > > On Fri, 5 May 2006, linda.s wrote: > > > I have two drives. The python24 is installed in c: and the code is in d: > > drive (d:\data). > > so what I did is: > > d:\data> c:\python24\python test.py > > Hi Linda, > > Can you copy and paste the code to test.py? I suspect that the code does > not contain a necessary import statement, but without seeing the code, we > can't really say what's going on. > > > Also, just off-hand: do you have several versions of Python on your > system? I see you have Python 2.4. Do you know if you have another > version of Python installed? > > The reason we ask is because of the following scenario: one possibility is > that the Numeric module is installed for another version of Python --- the > one you're running with PythonWin --- and that would also explain the > symptoms. But this is only a possibility; let's learn a little more about > the situation. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060505/6701b562/attachment.htm From john.corry at ntlworld.com Sat May 6 13:23:02 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 6 May 2006 12:23:02 +0100 Subject: [Tutor] 2 Combo Boxes! What was I thinking? Message-ID: <000501c670ff$747146f0$4a3ea8c0@JOHNC> Hi, I have set up a GUI which has amongst other widgets two combo boxes. I am using: PythonCard version: 0.8.1 wxPython version: 2.6.1.0 Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] Platform: win32 Glade 2 I started by setting up comboboxentry2 to accept two settings in its drop down list. (open + closed). This worked fine. Code below: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) My problems started when I went to set up comboboxentry3. I used the following code: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo3 = self.wTree.get_widget("comboboxentry3") combo3.connect("changed", self.callback3, "comboboxentry3") combo3.append_text ("Mon") combo3.append_text ("Tue") combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) I got the following error: Gtkwarning: gtk_combo_box_append_text: assertion GTK_IS_LIST_STORE(Combobox->Priv->Model) Failed Combo3.append_text("Mon") Gtkwarning: gtk_combo_box_append_text: assertion GTK_IS_LIST_STORE(Combobox->Priv->Model) Failed Combo3.append_text("Tue") I then tried the code: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo3 = self.wTree.get_widget("comboboxentry3") combo3.connect("changed", self.callback3, "comboboxentry3") combo3.child.append_text ("Mon") combo3.child.append_text ("Tue") combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) I get the following error message: DeprecationWarning: use GtkEditable.insert_text Combo3.child.append_text("Mon") DeprecationWarning: use GtkEditable.insert_text Combo3.child.append_text("Tue") The combobox3 is populated on the GUI but instead of being a drop down list it appears as a string on one line and looks like this: MonTue I have to confess I am not really sure what I am doing. I just guessed at putting the child command in. It gets me close but not close enough. Can anyone tell me what I am doing wrong or explain what happens when you put two combo boxes on the one GUI? Any help greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060506/db0b07de/attachment.html From traviesomono at yahoo.es Sat May 6 14:13:17 2006 From: traviesomono at yahoo.es (Alfonso) Date: Sat, 06 May 2006 14:13:17 +0200 Subject: [Tutor] printing the links of a page (regular expressions) Message-ID: <445C92DD.6010302@yahoo.es> I'm writing a script to retrieve and print some links of a page. These links begin wiht "/dog/", so I use a regular expresion to try to find them. The problem is that the script only retrieves a link per line in the page. I mean, if the line hat several links, the script only reports the first. I can't find where is the mistake. Does anyone hat a idea, what I have false made? Thank you very much for your help. import re from urllib import urlopen fileObj = urlopen("http://name_of_the_page") links = [] regex = re.compile ( "((/dog/)[^ \"\'<>;:,]+)",re.I) for a in fileObj.readlines(): result = regex.search(a) if result: print result.group() ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From kent37 at tds.net Sat May 6 14:19:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 May 2006 08:19:36 -0400 Subject: [Tutor] 2 Combo Boxes! What was I thinking? In-Reply-To: <000501c670ff$747146f0$4a3ea8c0@JOHNC> References: <000501c670ff$747146f0$4a3ea8c0@JOHNC> Message-ID: <445C9458.3000801@tds.net> John CORRY wrote: > I have set up a GUI which has amongst other widgets two combo boxes. I > am using: > > PythonCard version: 0.8.1 > wxPython version: 2.6.1.0 > Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit > (Intel)] > > Platform: win32 > > Glade 2 From your code it looks like you are using pyGTK and Glade, not PythonCard and wxPython. I don't have the answer to your question but it might help to get the question right :-) Kent > > > > I started by setting up comboboxentry2 to accept two settings in its > drop down list. (open + closed). This worked fine. Code below: > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > dic={"on_window1_destroy" : self.quit, } > > self.wTree.signal_autoconnect (dic) > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > > > > > combo1.append_text("Open") > > combo1.append_text("Closed") > > combo1.set_active(0) > > combo1.connect("changed", self.callback2, combo1) > > > > My problems started when I went to set up comboboxentry3. I used the > following code: > > > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > dic={"on_window1_destroy" : self.quit, } > > self.wTree.signal_autoconnect (dic) > > > > > > combo3 = self.wTree.get_widget("comboboxentry3") > > combo3.connect("changed", self.callback3, "comboboxentry3") > > > > combo3.append_text ("Mon") > > combo3.append_text ("Tue") > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > combo1.append_text("Open") > > combo1.append_text("Closed") > > combo1.set_active(0) > > combo1.connect("changed", self.callback2, combo1) > > > > > > I got the following error: > > > > Gtkwarning: gtk_combo_box_append_text: assertion > GTK_IS_LIST_STORE(Combobox->Priv->Model) > > Failed > > Combo3.append_text(?Mon?) > > Gtkwarning: gtk_combo_box_append_text: assertion > GTK_IS_LIST_STORE(Combobox->Priv->Model) > > Failed > > Combo3.append_text(?Tue?) > > > > I then tried the code: > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > dic={"on_window1_destroy" : self.quit, } > > self.wTree.signal_autoconnect (dic) > > > > > > combo3 = self.wTree.get_widget("comboboxentry3") > > combo3.connect("changed", self.callback3, "comboboxentry3") > > > > combo3.child.append_text ("Mon") > > combo3.child.append_text ("Tue") > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > combo1.append_text("Open") > > combo1.append_text("Closed") > > combo1.set_active(0) > > combo1.connect("changed", self.callback2, combo1) > > > > I get the following error message: > > > > DeprecationWarning: use GtkEditable.insert_text > > Combo3.child.append_text(?Mon?) > > DeprecationWarning: use GtkEditable.insert_text > > Combo3.child.append_text(?Tue?) > > > > The combobox3 is populated on the GUI but instead of being a drop down > list it appears as a string on one line and looks like this: > > MonTue > > > > I have to confess I am not really sure what I am doing. I just guessed > at putting the child command in. It gets me close but not close > enough. Can anyone tell me what I am doing wrong or explain what > happens when you put two combo boxes on the one GUI? > > > > Any help greatly appreciated. > > > > Thanks, > > > > John. > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat May 6 14:25:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 May 2006 08:25:17 -0400 Subject: [Tutor] printing the links of a page (regular expressions) In-Reply-To: <445C92DD.6010302@yahoo.es> References: <445C92DD.6010302@yahoo.es> Message-ID: <445C95AD.3080504@tds.net> Alfonso wrote: > I'm writing a script to retrieve and print some links of a page. These > links begin wiht "/dog/", so I use a regular expresion to try to find > them. The problem is that the script only retrieves a link per line in > the page. I mean, if the line hat several links, the script only reports > the first. I can't find where is the mistake. Does anyone hat a idea, > what I have false made? You are reading the data by line using readlines(). You only search each line once. regex.findall() or regex.finditer() would be a better choice than regex.search(). You might also be interested in sgmllib-based solutions to this problem, which will generally be more robust than regex-based searching. For example, see http://diveintopython.org/html_processing/extracting_data.html http://www.w3journal.com/6/s3.vanrossum.html#MARKER-9-26 Kent > > Thank you very much for your help. > > > import re > from urllib import urlopen > > fileObj = urlopen("http://name_of_the_page") > links = [] > regex = re.compile ( "((/dog/)[^ \"\'<>;:,]+)",re.I) > > for a in fileObj.readlines(): > result = regex.search(a) > if result: > print result.group() > > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From davholla2002 at yahoo.co.uk Sat May 6 14:41:53 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat, 6 May 2006 13:41:53 +0100 (BST) Subject: [Tutor] Python challenge In-Reply-To: <7e3eab2c0605040956o389cf610l8cebfea6cf1acf13@mail.gmail.com> Message-ID: <20060506124153.77823.qmail@web25914.mail.ukl.yahoo.com> Jason, Thanks that helped me work it out. David Jason Massey wrote: David, What answer did you get? One of the things to rember on the challenge is to take your answer and put ".html" (no qutoes) on the end of it in the url. So for the first problem the url would be: http://www.pythonchallenge.com/pc/def/.html On 5/4/06, David Holland < davholla2002 at yahoo.co.uk> wrote: I looked at this and got stuck on the first one :- http://www.pythonchallenge.com/pc/def/0.html It says try changing the url. I assumed that it either meant 2*38 or 2 to the power of 38 but I can't see how to put either of those in the url. What have I missed ? Thanks in advance. David Holland --------------------------------- Yahoo! Photos ? NEW, now offering a quality print service from just 7p a photo. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060506/e0b8ca98/attachment.htm From ml.cyresse at gmail.com Sat May 6 16:20:51 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 7 May 2006 02:20:51 +1200 Subject: [Tutor] 2 Combo Boxes! What was I thinking? In-Reply-To: <445C9458.3000801@tds.net> References: <000501c670ff$747146f0$4a3ea8c0@JOHNC> <445C9458.3000801@tds.net> Message-ID: Hi John, I'm going to take a wild stab... (but as Kent said, wxPython or pyGTK?) Combo3.child.append_text("Mon") Okay, so, the DeprecationWarning you need to pay attention to, but that aside, according to the pyGTK docs: http://www.pygtk.org/pygtk2reference/class-gtkcomboboxentry.html#function-gtk--combo-box-entry-new-text What you want to try is comboboxthing = gtk.combo_box_new_text() combobox.append_text("Option 1") combobox.append_text("Option 2") Regards, Liam Clarke On 5/7/06, Kent Johnson wrote: > John CORRY wrote: > > I have set up a GUI which has amongst other widgets two combo boxes. I > > am using: > > > > PythonCard version: 0.8.1 > > wxPython version: 2.6.1.0 > > Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit > > (Intel)] > > > > Platform: win32 > > > > Glade 2 > > From your code it looks like you are using pyGTK and Glade, not > PythonCard and wxPython. I don't have the answer to your question but it > might help to get the question right :-) > > Kent > > > > > > > > > I started by setting up comboboxentry2 to accept two settings in its > > drop down list. (open + closed). This worked fine. Code below: > > > > > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > > > dic={"on_window1_destroy" : self.quit, } > > > > self.wTree.signal_autoconnect (dic) > > > > > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > > > > > > > > > > > combo1.append_text("Open") > > > > combo1.append_text("Closed") > > > > combo1.set_active(0) > > > > combo1.connect("changed", self.callback2, combo1) > > > > > > > > My problems started when I went to set up comboboxentry3. I used the > > following code: > > > > > > > > > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > > > dic={"on_window1_destroy" : self.quit, } > > > > self.wTree.signal_autoconnect (dic) > > > > > > > > > > > > combo3 = self.wTree.get_widget("comboboxentry3") > > > > combo3.connect("changed", self.callback3, "comboboxentry3") > > > > > > > > combo3.append_text ("Mon") > > > > combo3.append_text ("Tue") > > > > > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > > > combo1.append_text("Open") > > > > combo1.append_text("Closed") > > > > combo1.set_active(0) > > > > combo1.connect("changed", self.callback2, combo1) > > > > > > > > > > > > I got the following error: > > > > > > > > Gtkwarning: gtk_combo_box_append_text: assertion > > GTK_IS_LIST_STORE(Combobox->Priv->Model) > > > > Failed > > > > Combo3.append_text("Mon") > > > > Gtkwarning: gtk_combo_box_append_text: assertion > > GTK_IS_LIST_STORE(Combobox->Priv->Model) > > > > Failed > > > > Combo3.append_text("Tue") > > > > > > > > I then tried the code: > > > > > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > > > dic={"on_window1_destroy" : self.quit, } > > > > self.wTree.signal_autoconnect (dic) > > > > > > > > > > > > combo3 = self.wTree.get_widget("comboboxentry3") > > > > combo3.connect("changed", self.callback3, "comboboxentry3") > > > > > > > > combo3.child.append_text ("Mon") > > > > combo3.child.append_text ("Tue") > > > > > > > > combo1 = self.wTree.get_widget("comboboxentry2") > > > > combo1.append_text("Open") > > > > combo1.append_text("Closed") > > > > combo1.set_active(0) > > > > combo1.connect("changed", self.callback2, combo1) > > > > > > > > I get the following error message: > > > > > > > > DeprecationWarning: use GtkEditable.insert_text > > > > Combo3.child.append_text("Mon") > > > > DeprecationWarning: use GtkEditable.insert_text > > > > Combo3.child.append_text("Tue") > > > > > > > > The combobox3 is populated on the GUI but instead of being a drop down > > list it appears as a string on one line and looks like this: > > > > MonTue > > > > > > > > I have to confess I am not really sure what I am doing. I just guessed > > at putting the child command in. It gets me close but not close > > enough. Can anyone tell me what I am doing wrong or explain what > > happens when you put two combo boxes on the one GUI? > > > > > > > > Any help greatly appreciated. > > > > > > > > Thanks, > > > > > > > > John. > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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 traviesomono at yahoo.es Sat May 6 17:03:01 2006 From: traviesomono at yahoo.es (Alfonso) Date: Sat, 06 May 2006 17:03:01 +0200 Subject: [Tutor] printing the links of a page (regular expressions) In-Reply-To: <445C95AD.3080504@tds.net> References: <445C92DD.6010302@yahoo.es> <445C95AD.3080504@tds.net> Message-ID: <445CBAA5.5090307@yahoo.es> Kent Johnson wrote: > Alfonso wrote: > >> I'm writing a script to retrieve and print some links of a page. These >> links begin wiht "/dog/", so I use a regular expresion to try to find >> them. The problem is that the script only retrieves a link per line in >> the page. I mean, if the line hat several links, the script only reports >> the first. I can't find where is the mistake. Does anyone hat a idea, >> what I have false made? >> > > You are reading the data by line using readlines(). You only search each > line once. regex.findall() or regex.finditer() would be a better choice > than regex.search(). > > You might also be interested in sgmllib-based solutions to this problem, > which will generally be more robust than regex-based searching. For > example, see > http://diveintopython.org/html_processing/extracting_data.html > http://www.w3journal.com/6/s3.vanrossum.html#MARKER-9-26 > > Kent > > >> Thank you very much for your help. >> >> >> import re >> from urllib import urlopen >> >> fileObj = urlopen("http://name_of_the_page") >> links = [] >> regex = re.compile ( "((/dog/)[^ \"\'<>;:,]+)",re.I) >> >> for a in fileObj.readlines(): >> result = regex.search(a) >> if result: >> print result.group() >> >> >> >> >> ______________________________________________ >> LLama Gratis a cualquier PC del Mundo. >> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. >> http://es.voice.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 > > Thank you very much, Kent, it works with findall(). I will also have a look at the links about sgmllib. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From john.corry at ntlworld.com Sat May 6 15:28:44 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 6 May 2006 14:28:44 +0100 Subject: [Tutor] Stumbled onto the answer! Message-ID: <000001c67111$00b480d0$4a3ea8c0@JOHNC> Hi, I have managed to "fix" my two combo box problem. I have used the following code:- self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) combo1 = self.wTree.get_widget("comboboxentry2") combo1.append_text("Open") combo1.append_text("Closed") combo1.set_active(0) combo1.connect("changed", self.callback2, combo1) combo2 = self.wTree.get_widget("comboboxentry1") combo2.connect("changed", self.callback3, "comboboxentry1") store = gtk.ListStore(gobject.TYPE_STRING) store.append (["Mon"]) store.append (["Tue"]) store.append (["Wed"]) store.append (["Thu"]) store.append (["Fri"]) store.append (["Sat"]) store.append (["Sun"]) combo2.set_model(store) combo2.set_text_column(0) combo2.set_active(0) It works but I am not sure why. Regards, A Very Happy John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060506/c454be7a/attachment-0001.htm From doug.shawhan at gmail.com Sat May 6 19:04:36 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Sat, 6 May 2006 12:04:36 -0500 Subject: [Tutor] python cgi and html streams In-Reply-To: References: <5e1ceb8a0605051221h2b63d85n347bfe625c07acc5@mail.gmail.com> Message-ID: <5e1ceb8a0605061004n3991d520y198e106ac8a4e858@mail.gmail.com> On 5/5/06, Danny Yoo wrote: > > > > I was hoping for something magical like: > > > > gulp = cgi.StreamIO(" > > http://www.foo.com/cgi-bin/responder.cgi?foo=hi&bar=there&bat=buddy > ").read() > > > > ... but for some reason not one of the python creators foresaw that I > might > > one day need them to do all the thinking, typing and other hard parts > for > > me! > > > Hi Doug, > > Try the 'urllib' client library. Headway! The information I was trying to recive is meant to be returned to another cgi script in a parameter string. urllib.urlopen.geturl() gets my information back to me: The following is run on mywebsite.com #!/usr/bin/env python import urllib parameters = urllib.urlencode ({"id":"hippiedavey","origin":"goatville","dest":"cowtown"}) info = urllib.urlopen("http://www.hillbillyheaven.org/expectorate.asp?%s "%parameters).geturl() print info " http://mywebsite.com/Database/test.py?quoteno=999&originzip=47567&destzip=47598&id=hippiedavey&netcharges=$251.73&days=2 " I can, of course, use string methods to convert the returned request to whatever I want, but I still don't belive this was the original intent of the provider. :-) As it is now, I belive I'll have to create a script that will retrieve the info string, then call another copy of itself to extract the parameters from the info string! Not the worst fate, but it does seem to double up my calls to the webserver. On the other hand, I'll probably figure something else out! :-) Thanks! http://www.python.org/doc/lib/module-urllib.html > > The CGI server library is meant for servers, say, for the person who > would be implmenting responder.cgi. > > If you need to do more complicated interactions as a client, then > something like Mechanize might also do the trick: > > http://wwwsearch.sourceforge.net/mechanize/ > > but I'd recommend looking into urllib first to see if it's sufficient for > your problem. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060506/efbbdd58/attachment.html From traviesomono at yahoo.es Sat May 6 19:54:45 2006 From: traviesomono at yahoo.es (Alfonso) Date: Sat, 06 May 2006 19:54:45 +0200 Subject: [Tutor] web intefaces? Message-ID: <445CE2E5.5060008@yahoo.es> I would like to experiment with web interfaces and python. After some googling, I'm quite confused, does somebody know of a good link about this topic / what do you think that is the best software option to design web user intefaces with python? I mean web interfaces for common programms (so it's not important to me to have a very robust web server), the web server should run in the machine of the user of the programm.And it should be easy installed, as bundle, when I distribute the programm. Thank very much for your help. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From doug.shawhan at gmail.com Sun May 7 00:23:16 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Sat, 6 May 2006 17:23:16 -0500 Subject: [Tutor] Drifting Values in urllib. Message-ID: <5e1ceb8a0605061523r58be9ee4pd9deb8a0202b4b0a@mail.gmail.com> I am having difficulty inderstanding urllib's handling of values passed to it. I assign values from cgi.FieldStorage() thusly: if form.has_key("id"): id = form["id"].value if form.has_key("origin"): origin = form["origin"].value if form.has_key("dest"): dest = form["dest"].value ----- and so on. I then attempt to pass the values to urllib.urlencode(): parameters = urllib.urlencode ({"id":"%s","origin":"%s","dest":"%s","class1":"85","weight1":"185","custdata":"%s","respickup":"","resdel":"%s","insidechrg":"","furnchrg":"","cod":""})%(id,origin,dest,custdata,resdel) which rewards me with an error from the remote server. I then print the parameters value to see what is going on: origin= 8002886787&insidechrg=&respickup=&dest= 47720&resdel= 47567&custdata= Goat Kamal&cod=&weight1=185&furnchrg=&id=X&class1=85 Hmmm.. not at all what I put in! :-) I checked just to make sure my assignments were correct in the first place: print '''"id":"%s","origin":"%s","dest":"%s","class1":"85","weight1":"185","custdata":"%s","respickup":"","resdel":"%s","insidechrg":"","furnchrg":"","cod":""'''%(id,origin,dest,custdata,resdel) which reaps: "id":"8002886787","origin":"47720","dest":"47567","class1":"85","weight1":"185","custdata":"GoatKamal","respickup":"","resdel":"X","insidechrg":"","furnchrg":"","cod":"" Am I missing something fundamental here? I am not used to dictionaries swirling around like this. :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060506/9ae12298/attachment.html From alan.gauld at btinternet.com Sun May 7 01:12:34 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 May 2006 00:12:34 +0100 Subject: [Tutor] web intefaces? References: <445CE2E5.5060008@yahoo.es> Message-ID: > what do you think that is the best software option to design > web user intefaces with python? That's a very broad question! A web UI is just HTML, normally expressed using tables and forms. So you can use any HTML editor to design the UI. And it is generally held to be a good idea to separate the code from the UI as much as possible so typically the UI resides in a separate file from the code and the code simply reads it and displays it.(classic CGI style) or the code is imported into the HTML by some mechanism (ASP style) > the web server should run in the machine of the user > of the program. But why you would want to do this rather than build a GUI is somewhat mysterious. By doing so you limit the functionality of your GUI to all the horrors of HTML and incur a significant performance penalty as well as soaking up a lot of your users machine resources (memory, CPU and IO!) You might also introduce security holes, cause conflicts with their own local web server, and run foul of firewall software. Even if you can guarantee a foolproof installation and a big powerful PC you still have to cope with the potential myriad of browsers. What do you do if the default browser is lynx say? The benefits are few and if you design your code and UI to be cleanly separated then they are even fewer. Web applications are very useful for allowing a wide body of users on many platforms to remotely access your applicatiojn, but they are rarely a good way to go on an individual PC - IMHO of course!. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun May 7 01:16:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 May 2006 00:16:07 +0100 Subject: [Tutor] Drifting Values in urllib. References: <5e1ceb8a0605061523r58be9ee4pd9deb8a0202b4b0a@mail.gmail.com> Message-ID: > Am I missing something fundamental here? I am not used to > dictionaries > swirling around like this. :-) Caveat: I didn't read this through thoroughly but... Dictionaries are not in any specific order, you cannot rely on the order remaining constant. If you are relying on the order you may well get bitten, you need to extract the data in the order you need it HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Sun May 7 03:02:10 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 6 May 2006 18:02:10 -0700 (PDT) Subject: [Tutor] Drifting Values in urllib. In-Reply-To: References: <5e1ceb8a0605061523r58be9ee4pd9deb8a0202b4b0a@mail.gmail.com> Message-ID: On Sun, 7 May 2006, Alan Gauld wrote: >> Am I missing something fundamental here? I am not used to dictionaries >> swirling around like this. :-) > > Caveat: I didn't read this through thoroughly but... > > Dictionaries are not in any specific order, you cannot rely on the order > remaining constant. If you are relying on the order you may well get > bitten, you need to extract the data in the order you need it The appropriate data structure in this case might then be a list of key-value pairs. For example, rather than: { 'a' : 'alpha', 'b' : 'beta', 'e' : 'eta' } we can encode the same key-to-value pairing with a list of 2-tuples: [('a', 'alpha'), ('b', 'beta'), ('c', 'eta')] which contains the same information content, but optimized for sequential ordering rather than random-access lookup. This list will maintain the sequence of the items, and we'll still be able to do key-value lookups if we write a simple lookup() function. From dyoo at hkn.eecs.berkeley.edu Sun May 7 03:24:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 6 May 2006 18:24:14 -0700 (PDT) Subject: [Tutor] Drifting Values in urllib. In-Reply-To: <5e1ceb8a0605061523r58be9ee4pd9deb8a0202b4b0a@mail.gmail.com> References: <5e1ceb8a0605061523r58be9ee4pd9deb8a0202b4b0a@mail.gmail.com> Message-ID: > parameters = urllib.urlencode > ({"id":"%s","origin":"%s","dest":"%s","class1":"85", "weight1":"185","custdata":"%s","respickup":"","resdel":"%s", "insidechrg":"","furnchrg":"","cod":""})%(id,origin,dest,custdata,resdel) Hi Doug, On closer look, I think there's a misunderstanding here. According to the documentation on urllib.urlencode(): urlencode(query[, doseq]) Convert a mapping object or a sequence of two-element tuples to a ``url-encoded'' string, suitable to pass to urlopen() above as the optional data argument. For example: #################################### >>> urllib.urlencode({'Hot' : '1', ... 'Cross' : '2', ... 'Buns' : '3'}) 'Hot=1&Buns=3&Cross=2' #################################### Here, we're passing a string of key/value pairs. Alternatively, we can pass: #################################### >>> urllib.urlencode([('Hot', 1), ... ('Cross', '2'), ... ('Buns', '3')]) 'Hot=1&Cross=2&Buns=3' #################################### I'm not quite sure I see where the string interpolation comes in. Wait... ok, now I understand what you're trying to do, looking back on what you tried: ########################################################################## parameters = (urllib.urlencode({"id":"%s","origin":"%s","dest":"%s", ...}) % (id,origin,dest, ...)) ########################################################################## You're using urlencode to build a template string, which is then passed into urlencode. Don't do this. *grin* You're missing the whole point behind urlencode(): it's meant to protect both key and values so that their string content is clean. Concretely: we know that parameter values aren't allowed to have things like ampersands, or else those ampersands will be misinterpreted. We use urlencode() to encode those values properly. Rather than: ################################################## >>> urllib.urlencode({'fish': '%s'}) % 'surf&turf' 'fish= surf&turf' ################################################## which gives the wrong result, it is more correct to do: ########################################### >>> urllib.urlencode({'fish': 'surf&turf'}) 'fish=surf%26turf' ########################################### So, again: when we're building those URL strings, doing the interpolation outside of the urlencode produces incorrectly protected URL strings. Go the direct route, and pass values to urlencode() too. From dyoo at hkn.eecs.berkeley.edu Sun May 7 08:15:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 6 May 2006 23:15:49 -0700 (PDT) Subject: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying Message-ID: Hi everyone, One of the major complaints that people have made about the "One Day of IDLE Toying" tutorial I've written is that the screenshots are badly outdated. http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ I was curious if anyone wanted to volunteer to provide fresh, updated Windows XP screenshots to replace the ones on the IDLE tutorial. Basically, I'm asking for unpaid slave labor. *grin* Silly as this may sound, I suddenly have about a week of free time, but I no longer have access to anything other than my personal Powerbook, and Jack Jansen's already covered MacPython already. So if someone with Windows XP would be willing to do this, I'd be greatly appreciative and will be happy to properly attribute the work. (Side explanations: I just finished my last day at my job. I have about a week of time before I fly to my graduate school studies. I expect that grad school will monopolize a great deal of my time. I hope I can get some loose ends tied before then!) Thanks a lot! From alan.gauld at freenet.co.uk Sun May 7 09:51:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 7 May 2006 08:51:37 +0100 Subject: [Tutor] Call for volunteer to help revise images for One Day ofIDLE Toying References: Message-ID: <00f801c671ab$1218a870$0c01a8c0@XPpro> Danny, I'm happy to do that. I assume you just want the same shots that you currently have? Alan G. ----- Original Message ----- > One of the major complaints that people have made about the "One Day > of IDLE Toying" tutorial I've written is that the screenshots are > badly outdated. > > http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ > > I was curious if anyone wanted to volunteer to provide fresh, > updated Windows XP screenshots to replace the ones on the IDLE > tutorial. From john.corry at ntlworld.com Sun May 7 13:50:47 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 7 May 2006 12:50:47 +0100 Subject: [Tutor] Button Signals Message-ID: <000001c671cc$7f37d3b0$4a3ea8c0@JOHNC> Hi, I am having difficulty with using signal handlers. I am using Glade 2 and Pygtk. My editor is Pythoncard. The following code connects to button one and calls a function which hides button one. self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) process = self.wTree.get_widget("button1") process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process): process.hide() The above code works fine. However I want button one to remain on my GUI. Thus, I want to just stop the signal being emitted after it is pressed once. I have used the following code which is trying to disconnect the button one: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) process = self.wTree.get_widget("button1") process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process): process.disconnect() When I run this code I get the error TyoeError: Object takes exactly one argument(0 given) When I put an argument in, it says that the argument must be an integer. I have tried a number of integers at random but none work. On the Pygtk tutorial it states the following: 3.1. More on Signal Handlers Lets take another look at the connect() call. object.connect(name, func, func_data) The return value from a connect() call is an integer tag that identifies your callback. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached. This tag allows you to remove this callback from the list by using: object.disconnect(id) So, by passing in the tag returned by one of the signal connect methods, you can disconnect a signal handler. How do I find out what the integer tag is, so that I can put this in my code? I have tried the pygtk faq page but it is currently unavailable. Any help greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060507/6ba375ed/attachment.html From ml.cyresse at gmail.com Sun May 7 14:06:03 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 8 May 2006 00:06:03 +1200 Subject: [Tutor] Button Signals In-Reply-To: <000001c671cc$7f37d3b0$4a3ea8c0@JOHNC> References: <000001c671cc$7f37d3b0$4a3ea8c0@JOHNC> Message-ID: Hi John, I'll answer your questions, but first: Pythoncard is for wxPython. wxPython is vastly different to PyGTK afaik. The docs you quote answer your question: The return value from a connect() call is an integer tag that identifies your callback. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached. This tag allows you to remove this callback from the list by using: object.disconnect(id) So, by passing in the tag returned by one of the signal connect methods, you can disconnect a signal handler. Your code needs the following: self.callback_id1 = process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process): process.disconnect(self.callback_id1) On 5/7/06, John CORRY wrote: > > Hi, > > > > I am having difficulty with using signal handlers. I am using Glade 2 and > Pygtk. My editor is Pythoncard. The following code connects to button > one and calls a function which hides button one. > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > dic={"on_window1_destroy" : self.quit, } > > self.wTree.signal_autoconnect (dic) > > > > > > process = self.wTree.get_widget("button1") > > process.connect("clicked", self.callback1, start_date, process) > > > > def callback1(self,data,start_date,process): > > process.hide() > > > > The above code works fine. However I want button one to remain on my GUI. > Thus, I want to just stop the signal being emitted after it is pressed > once. I have used the following code which is trying to disconnect the > button one: > > > > self.wTree = gtk.glade.XML ("phonelog.glade", "window1") > > dic={"on_window1_destroy" : self.quit, } > > self.wTree.signal_autoconnect (dic) > > > > > > process = self.wTree.get_widget("button1") > > process.connect("clicked", self.callback1, start_date, process) > > > > def callback1(self,data,start_date,process): > > process.disconnect() > > > > When I run this code I get the error > > TyoeError: Object takes exactly one argument(0 given) > > > > When I put an argument in, it says that the argument must be an integer. I > have tried a number of integers at random but none work. On the Pygtktutorial it states the following: > > > > *3.1. More on Signal Handlers* > > Lets take another look at the connect() call. > > object.connect(name, func, func_data) > > The return value from a connect() call is an integer tag that identifies > your callback. As stated above, you may have as many callbacks per signal > and per object as you need, and each will be executed in turn, in the order > they were attached. > > This tag allows you to remove this callback from the list by using: > > object.disconnect(id) > > So, by passing in the tag returned by one of the signal connect methods, > you can disconnect a signal handler. > > How do I find out what the integer tag is, so that I can put this in my > code? > > > > I have tried the pygtk faq page but it is currently unavailable. > > > > Any help greatly appreciated. > > > > Thanks, > > > > John. > > > > _______________________________________________ > 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/20060508/1d9c6cc5/attachment-0001.htm From john.corry at ntlworld.com Sun May 7 14:44:42 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 7 May 2006 13:44:42 +0100 Subject: [Tutor] Button Signals In-Reply-To: Message-ID: <000001c671d4$07a46ea0$4a3ea8c0@JOHNC> Liam, Thanks for the prompt reply. That is working for me. Regards, John, -----Original Message----- From: Liam Clarke [mailto:ml.cyresse at gmail.com] Sent: 07 May 2006 13:06 To: john.corry at ntlworld.com Cc: tutor at python.org Subject: Re: [Tutor] Button Signals Hi John, I'll answer your questions, but first: Pythoncard is for wxPython. wxPython is vastly different to PyGTK afaik. The docs you quote answer your question: The return value from a connect () call is an integer tag that identifies your callback. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached. This tag allows you to remove this callback from the list by using: object.disconnect(id) So, by passing in the tag returned by one of the signal connect methods, you can disconnect a signal handler. Your code needs the following: self. callback_id1 = process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process ): process.disconnect(self.callback_id1) On 5/7/06, John CORRY < john.corry at ntlworld.com > wrote: Hi, I am having difficulty with using signal handlers. I am using Glade 2 and Pygtk. My editor is Pythoncard. The following code connects to button one and calls a function which hides button one. self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) process = self.wTree.get_widget("button1") process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process ): process.hide() The above code works fine. However I want button one to remain on my GUI. Thus, I want to just stop the signal being emitted after it is pressed once. I have used the following code which is trying to disconnect the button one: self.wTree = gtk.glade.XML ("phonelog.glade", "window1") dic={"on_window1_destroy" : self.quit, } self.wTree.signal_autoconnect (dic) process = self.wTree.get_widget("button1") process.connect("clicked", self.callback1, start_date, process) def callback1(self,data,start_date,process ): process.disconnect() When I run this code I get the error TyoeError: Object takes exactly one argument(0 given) When I put an argument in, it says that the argument must be an integer. I have tried a number of integers at random but none work. On the Pygtk tutorial it states the following: 3.1. More on Signal Handlers Lets take another look at the connect() call. object.connect(name, func, func_data) The return value from a connect() call is an integer tag that identifies your callback. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached. This tag allows you to remove this callback from the list by using: object.disconnect(id) So, by passing in the tag returned by one of the signal connect methods, you can disconnect a signal handler. How do I find out what the integer tag is, so that I can put this in my code? I have tried the pygtk faq page but it is currently unavailable. Any help greatly appreciated. Thanks, John. _______________________________________________ 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/20060507/d6b94d9d/attachment.html From rschroev_nospam_ml at fastmail.fm Sun May 7 15:52:38 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 07 May 2006 15:52:38 +0200 Subject: [Tutor] Nested list comprehensions In-Reply-To: <013b01c6709f$6af15670$0c01a8c0@XPpro> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> Message-ID: Alan Gauld schreef: >> I am having trouble wrapping my mind around >> nested list comprehensions Me too: I feel it should be better with the order reversed. >> and my initial reaction to this is that it should be expressed as: >> >> result = [eachSubObject for eachSubObject in eachObject.m() for >> eachObject in C1] That's what I initially expected too. > My take on that is that it doesn't work from a scoping point of view. > You have to fetch eachObject before you can send m() to it. > Doing it the way you have it here would involve calling > eachObject.m() before eachObject had been fetched from C1 Not exactly; to me, the above list comprehension is just an extension from the way non-nested comprehensions work: [2 * i for i in range(10)] I interpret that as: 2 * i: we state an expression for: we're going to evaluate that expression using the values that we're going to define after this i in range(10): which is, in this case, every i in range(10) For the nested case, let's consider an admittedly contrived example: a = range(10) def f(n): return [i + n*100 for i in range(10)] I'd expect to be able to write [j for j in f(i) for i in a] Interpreting it as: j: evaluate j for every value for: in the sequence defined by j in f(i): this expression, where f(i) is evaluated for every value for: in i in a: the sequence a But that turns out to be the wrong way around. Not that if you literally nest the list comprehensions (giving a list of lists instead of a flat list as result), the order is as I would expect: [[j for j in f(i)] for i in a] So I would have expected that just dropping the inner [ and ] would return the same thing, but flattened. Actually I don't use nested list comprehensions all that often, and when I do use them or encounter them I just remember that the for's should be in the same order as in the non-LC solution. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From kermit at polaris.net Sun May 7 23:35:24 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 7 May 2006 17:35:24 -0400 (Eastern Daylight Time) Subject: [Tutor] query python mastery via programming exercises Message-ID: <445E681C.000003.03636@YOUR-4105E587B6> Hello. I would like to try to master python programming this summer. All the programming classes that I have taken previously used the technique of assigning programming exercises with examples of relevant techniques, and the task of the student is to study the examples, and apply them to solve the programming exercise. So. Has someone organized a set of exercises that when solved in the order presented teaches mastery of Python programming. Second, if or when I master Python, how may I contact folks who wish to pay for programs written in Python. Kermit < Kermit at polaris.net > From cappy2112 at gmail.com Mon May 8 03:39:27 2006 From: cappy2112 at gmail.com (Tony C) Date: Sun, 7 May 2006 18:39:27 -0700 Subject: [Tutor] Should I use generators here? Message-ID: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> I wrote a small Python program to count some simple statistics on a Visual Basic program thatI am maintaining. The Python program counts total lines, whitespace lines, comment lines, Public & Private Subroutines, Public and Private Functions. The Python program takes about 20-40 seconds to count all these stats since I started using Psyco, but I am wondering if I can eliminate Pysco and improve the program performance using generators (or some other technique). The running time is quick enough, I'm just wondering if there are other simple performance tweaks to use. I've already eliminated all . (dot) references inside the loops. I haven't quite got my head around generators yet, or when to use /not use them, even though I have seen tutorials and examples. I'll only include the higher level calling functions, for brevity.. ProcessAllFiles() and ProcessFileType() are the functions I am interested in improving the performance. Here is what the output "summary" looks like Total Lines= 54932 in 45 Files Total Comment Lines = 7408, Total Whitespace = 33679 Total Private Subs = 608, Total Public Subs = 145 Total Private Funcs = 86, Total Public Funcs = 165 Thanks for any advice! Tony def ProcessFiletype(Thesefiles, Summary, Stats): """Iterate over all the files in 'Thesefiles', and process each file, one at a time""" global TotalAllLines LongestFilenameLen=0 for Onefile in Thesefiles: Onefile = Onefile.lower().capitalize() FilenameLen = len(Onefile) if( FilenameLen > LongestFilenameLen): LongestFilenameLen = FilenameLen #print Onefile try: fh=open(Onefile, "r") except IOError: print("\nFATAL ERROR ocurred opening %s for input" % Onefile) else: try: Filecontents = fh.readlines() # these files are very small, less than 100k each, so reading in an entire file isn't a problem fh.close() except IOError: print("\nFatal error occurred reading from %s\n\n" % InputFilename) else: Summary[Onefile] = deepcopy(Stats) # associate each filename with a new stats dict with 0 counts for all alttributes Filestats = Summary[Onefile] Filestats["TotalLines"] = len(Filecontents) Summary[Onefile] = Filestats for line in Filecontents: TotalAllLines = TotalAllLines + 1 #Filteredline=line.strip() Filteredline=line if( not IsCommentLine(Filteredline, Summary[Onefile] ) ): if( not IsWhitespaceLine(Filteredline, Summary[Onefile] )) : if( not IsPrivateSub(Filteredline, Summary[Onefile] )): if( not IsPrivateFunc(Filteredline, Summary[Onefile] ) ): if( not IsPublicSub(Filteredline, Summary[Onefile] )): IsPublicFunc(Filteredline, Summary[Onefile] ) return FilenameLen #///////////////////////////////////////////////////////// def ProcessAllFiles(Summary, Stats, FileTypes, FiletypeStats): """Iterates over all Files in current directory that have the extensions in Filetypes""" from glob import glob LongestFilenameLen = 0 for Filetype in FileTypes: TheseFiles = glob("*" + Filetype) TheseFiles.sort() FiletypeStats[Filetype]=len(TheseFiles) Longest = ProcessFiletype(TheseFiles, Summary, Stats) if( Longest > LongestFilenameLen): LongestFilenameLen = Longest return LongestFilenameLen #///////////////////////////////////////////////////////// def main(args): import psyco psyco.full() global TotalAllLines, TotalFilecount, TotalCommentLines, TotalWhitespaceLines, TotalPrivateSubs, TotalPublicSubs, TotalPrivateFuncs, TotalPublicFuncs TotalAllLines = 0 FileTypes=[".frm", ".bas", ".cls"] # Visual Basic source file extensions FiletypeStats={} FileStats={ "TotalLines":0, "WhitespaceLines":0, "CommentLines":0, "PrivateSubCount":0, "PublicSubCount":0, "PrivateFuncCount":0, "PublicFuncCount":0 } FileSummary={} LongestFilenameLen = ProcessAllFiles(FileSummary, FileStats, FileTypes, FiletypeStats) for Type, Count in FiletypeStats.iteritems(): print("\nThere are %3lu files with the %s extension" % (Count, Type.upper()) ) print("\n") TotalFilecount = 0 for File, Stats in FileSummary.iteritems(): TotalFilecount = TotalFilecount + 1 print("%s - %4lu Lines, %3lu Whitespace lines, %4lu Comments, %4lu Private Subs, %4lu Public Subs, %4lu Private Functions, %4lu Public Functions\n" % ( File, Stats["TotalLines"], Stats["WhitespaceLines"], Stats["CommentLines"], Stats["PrivateSubCount"], Stats["PublicSubCount"], Stats["PrivateFuncCount"], Stats["PublicFuncCount"] ) ) print("\nTotal Lines= %5lu in %lu Files\n" % (TotalAllLines, TotalFilecount) ) print("\nTotal Comment Lines = %5lu, Total Whitespace = %lu" % (TotalCommentLines, TotalWhitespaceLines) ) print("Total Private Subs = %5lu, Total Public Subs = %5lu" % (TotalPrivateSubs, TotalPublicSubs) ) print("Total Private Funcs = %5lu, Total Public Funcs = %5lu\n\n\n" % (TotalPrivateFuncs, TotalPublicFuncs) ) return None -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060507/5ea33db6/attachment.htm From kent37 at tds.net Mon May 8 12:02:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 May 2006 06:02:10 -0400 Subject: [Tutor] Should I use generators here? In-Reply-To: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> References: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> Message-ID: <445F1722.6070007@tds.net> Tony C wrote: > > I wrote a small Python program to count some simple statistics on a > Visual Basic program thatI am maintaining. > > The Python program counts total lines, whitespace lines, comment lines, > Public & Private Subroutines, Public and Private Functions. > The Python program takes about 20-40 seconds to count all these stats > since I started using Psyco, but I am wondering if I can > eliminate Pysco and improve the program performance using generators (or > some other technique). > > The running time is quick enough, I'm just wondering if there are other > simple performance tweaks to use. > I've already eliminated all . (dot) references inside the loops. Hi Tony, I don't see any obvious performance problems in the code you posted. If you are serious about speeding up your program you should learn to use the profile module. It will tell you where the time is going, rather than just asking us to guess. Take a look at the module docs and ask again here if you can't figure it out. > > I haven't quite got my head around generators yet, or when to use /not > use them, even though I have seen tutorials and examples. Generators are not an optimization technique so much as a way to structure code that includes iteration. Using generators can reduce memory consumption but that doesn't seem to be your problem. A few minor style notes below... > > def ProcessFiletype(Thesefiles, Summary, Stats): > > """Iterate over all the files in 'Thesefiles', and process each > file, one at a time""" > > global TotalAllLines The usual Python naming convention is to start variable names with a lower-case letter. There is no reason you have to do this though. > > LongestFilenameLen=0 > for Onefile in Thesefiles: > Onefile = Onefile.lower().capitalize() > FilenameLen = len(Onefile) > if( FilenameLen > LongestFilenameLen): > LongestFilenameLen = FilenameLen > #print Onefile > > try: > fh=open(Onefile, "r") > except IOError: > print("\nFATAL ERROR ocurred opening %s for input" % Onefile) > else: > try: > Filecontents = fh.readlines() # these files are very > small, less than 100k each, so reading in an entire file isn't a problem > fh.close() > except IOError: > print("\nFatal error occurred reading from %s\n\n" % > InputFilename) > else: > Summary[Onefile] = deepcopy(Stats) # associate each > filename with a new stats dict with 0 counts for all alttributes > > Filestats = Summary[Onefile] > Filestats["TotalLines"] = len(Filecontents) > Summary[Onefile] = Filestats You don't have to assign Filestats back into Summary. Filestats is a reference to the stats already stored in Summary. > > for line in Filecontents: > TotalAllLines = TotalAllLines + 1 > #Filteredline=line.strip() > Filteredline=line > if( not IsCommentLine(Filteredline, Summary[Onefile] > ) ): You could use Filestats instead of Summary[Onefile] in each of these lines. Kent > if( not IsWhitespaceLine(Filteredline, > Summary[Onefile] )) : > if( not IsPrivateSub(Filteredline, > Summary[Onefile] )): > if( not IsPrivateFunc(Filteredline, > Summary[Onefile] ) ): > if( not IsPublicSub(Filteredline, > Summary[Onefile] )): > IsPublicFunc(Filteredline, > Summary[Onefile] ) > > return FilenameLen > > #///////////////////////////////////////////////////////// > > def ProcessAllFiles(Summary, Stats, FileTypes, FiletypeStats): > > """Iterates over all Files in current directory that have the > extensions in Filetypes""" > > from glob import glob > LongestFilenameLen = 0 > for Filetype in FileTypes: > TheseFiles = glob("*" + Filetype) > TheseFiles.sort() > FiletypeStats[Filetype]=len(TheseFiles) > Longest = ProcessFiletype(TheseFiles, Summary, Stats) > if( Longest > LongestFilenameLen): > LongestFilenameLen = Longest > > return LongestFilenameLen > > #///////////////////////////////////////////////////////// > > def main(args): > > import psyco > psyco.full() > > global TotalAllLines, TotalFilecount, TotalCommentLines, > TotalWhitespaceLines, TotalPrivateSubs, TotalPublicSubs, > TotalPrivateFuncs, TotalPublicFuncs > > TotalAllLines = 0 > > FileTypes=[".frm", ".bas", ".cls"] # Visual Basic source file extensions > FiletypeStats={} > FileStats={ "TotalLines":0, "WhitespaceLines":0, "CommentLines":0, > "PrivateSubCount":0, "PublicSubCount":0, "PrivateFuncCount":0, > "PublicFuncCount":0 } > FileSummary={} > > LongestFilenameLen = ProcessAllFiles(FileSummary, FileStats, > FileTypes, FiletypeStats) > > for Type, Count in FiletypeStats.iteritems(): > print("\nThere are %3lu files with the %s extension" % (Count, > Type.upper()) ) > > > print("\n") > > TotalFilecount = 0 > > for File, Stats in FileSummary.iteritems(): > TotalFilecount = TotalFilecount + 1 > print("%s - %4lu Lines, %3lu Whitespace lines, %4lu Comments, > %4lu Private Subs, %4lu Public Subs, %4lu Private Functions, %4lu Public > Functions\n" % ( File, Stats["TotalLines"], Stats["WhitespaceLines"], > Stats["CommentLines"], Stats["PrivateSubCount"], > Stats["PublicSubCount"], Stats["PrivateFuncCount"], > Stats["PublicFuncCount"] ) ) > > print("\nTotal Lines= %5lu in %lu Files\n" % (TotalAllLines, > TotalFilecount) ) > print("\nTotal Comment Lines = %5lu, Total Whitespace = %lu" % > (TotalCommentLines, TotalWhitespaceLines) ) > print("Total Private Subs = %5lu, Total Public Subs = %5lu" % > (TotalPrivateSubs, TotalPublicSubs) ) > print("Total Private Funcs = %5lu, Total Public Funcs = %5lu\n\n\n" > % (TotalPrivateFuncs, TotalPublicFuncs) ) > > > return None > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon May 8 12:20:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 8 May 2006 11:20:28 +0100 Subject: [Tutor] query python mastery via programming exercises References: <445E681C.000003.03636@YOUR-4105E587B6> Message-ID: <000b01c67289$07cf4cf0$0c01a8c0@XPpro> Hello again, > Has someone organized a set of exercises that when solved in the > order > presented teaches mastery of Python programming. The nearest to that is the Python Challenge 'game' web site. It presents a series of challenges to be solved in Python. Each challenge uses a specific feature of Python and the challenges get harder as you go. If you complete all challenges you will have a very good knowledge of pyuthon and some of its more interesting modules. You will need a basic knowledge of pytho0n to start with, the official tutor is the best place to go if you altready know other programming languages. > Second, if or when I master Python, how may I contact folks who > wish to > pay for programs written in Python. There is a job listing page on the Python web site. Also some jobs get posted on Python mailing lists (esp regional ones) and on the comp.lanmg.python newsgroup. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon May 8 12:43:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 8 May 2006 11:43:33 +0100 Subject: [Tutor] Should I use generators here? References: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> Message-ID: <001701c6728c$425e1dd0$0c01a8c0@XPpro> Hi Tony, One point that jumps out at me is: # ------------------ def ProcessFiletype(Thesefiles, Summary, Stats): # ... try: fh=open(Onefile, "r") except IOError: print("\nFATAL ERROR ocurred opening %s for input" % Onefile) else: try: Filecontents = fh.readlines() # these files are very small, # --------------- The whole idea of try/except style is that you can write the happy path code in one place and put all the exception handling at the bottom. This helps to clarify the code significantly. Thus you should probably do: try: fh=open(Onefile, "r") Filecontents = fh.readlines() # these files are very small, # other code here Summary[Onefile] = deepcopy(Stats) # associate each fh.close() except IOError: print("\nFATAL ERROR ocurred opening %s for input" % Onefile) except IOError: print("\nFatal error occurred reading from %s\n\n" % InputFilename) The problem of course is that you have two cases with the same exception but you can handle that within the except by looking at the exception information (or more simply by setting a flag to ok once the file is opened which is initially simpler but that can lead to its own problems maintaining the flag status!.) Even if you decide to stick with two try blocks you shouldn't need the else construct. Either break or exit as part of the first except handler. The fewer levels of control you have in the program the easier it is to see what is happening and the lower the likeliehood of indentation level bugs being introduced. ############################### def ProcessAllFiles(Summary, Stats, FileTypes, FiletypeStats): """Iterates over all Files in current directory that have the extensions in Filetypes""" from glob import glob LongestFilenameLen = 0 for Filetype in FileTypes: TheseFiles = glob("*" + Filetype) TheseFiles.sort() FiletypeStats[Filetype]=len(TheseFiles) Longest = ProcessFiletype(TheseFiles, Summary, Stats) if( Longest > LongestFilenameLen): LongestFilenameLen = Longest return LongestFilenameLen ############################# I'm also somewhat confused as to why you seem so interested in the length of the longest filename? You seem to spend a fair bit of time finding the longest filename length? No big performance improvements there however I'm just looking at the superficial level of the code first. HTH, Alan G From kermit at polaris.net Mon May 8 16:14:20 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 8 May 2006 10:14:20 -0400 (Eastern Daylight Time) Subject: [Tutor] query python mastery via programming exercises References: <000b01c67289$07cf4cf0$0c01a8c0@XPpro> Message-ID: <445F523C.000005.03892@YOUR-4105E587B6> From: Alan Gauld Date: 05/08/06 06:20:42 To: Kermit Rose; tutor at python.org Subject: Re: [Tutor] query python mastery via programming exercises The nearest to that is the Python Challenge 'game' web site. It presents a series of challenges to be solved in Python. Each challenge uses a specific feature of Python and the challenges get harder as you go. If you complete all challenges you will have a very good knowledge of pyuthon and some of its more interesting modules. You will need a basic knowledge of pytho0n to start with, the official tutor is the best place to go if you altready know other programming languages. ***** Thank you very much. I have bookmarked the game site, and plan to explore it as soon as possible. ******* There is a job listing page on the Python web site. Also some jobs get posted on Python mailing lists (esp regional ones) and on the comp.lanmg.python newsgroup. ******** Thanks. I've now bookmarked the http://www.python.org/ web page for future referrence. Kermit < kermit at polaris.net > ***** -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060508/7cf4bdd9/attachment.htm From jjabson at yahoo.com Mon May 8 17:21:39 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Mon, 8 May 2006 08:21:39 -0700 (PDT) Subject: [Tutor] using variables as args Message-ID: <20060508152139.89896.qmail@web53713.mail.yahoo.com> Hello, I'm trying to start a shell script with 4 arguments from my python script. I'm having problems trying to figure out the best way to do this. I'm using variables as the arguments to the shell script. I want to use popen3 to keep track of stdin, stdout, and err, but from the docs I only see using spawnlp to use args in starting an other process. Can someone help me choice the best way to do this and the correct syntax how? Your help is much appreciated, Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From lipofib at yahoo.com Mon May 8 19:00:39 2006 From: lipofib at yahoo.com (Liviu Antoniu) Date: Mon, 8 May 2006 10:00:39 -0700 (PDT) Subject: [Tutor] python for beginners Message-ID: <20060508170039.7529.qmail@web31910.mail.mud.yahoo.com> I want to learn Python and for this I need a good tutorial for beginners. Please tell where can I find these tutorials. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060508/743943a0/attachment.htm From kent37 at tds.net Mon May 8 19:32:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 May 2006 13:32:04 -0400 Subject: [Tutor] python for beginners In-Reply-To: <20060508170039.7529.qmail@web31910.mail.mud.yahoo.com> References: <20060508170039.7529.qmail@web31910.mail.mud.yahoo.com> Message-ID: <445F8094.5000606@tds.net> Liviu Antoniu wrote: > I want to learn Python and for this I need a good tutorial for > beginners. Please tell where can I find these tutorials. If you are new to programming: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers If you are an experienced programmer new to Python: http://wiki.python.org/moin/BeginnersGuide/Programmers Kent From john.ertl at fnmoc.navy.mil Mon May 8 19:40:29 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Mon, 8 May 2006 10:40:29 -0700 Subject: [Tutor] trouble with re Message-ID: I have a file with 10,000 + lines and it has a coma delimited string on each line. The file should look like: DFRE,ship name,1234567 FGDE,ship 2, ,sdfsf The ,sdfsf line is bad data Some of the lines are messed up...I want to find all lines that do not end in a comma or seven digits and do some work on them. I can do the search for just the last seven digits but I can not do the seven digits or the comma at the end in the same search. Any ideas import re import sys import os p = re.compile('\d{7}$ | [,]$') # this is the line that I can not get correct I an trying to find lines that end in a comma or 7 digits newFile = open("newFile.txt",'w') oldFile = open("shipData.txt",'r') for line in oldFile: if p.search(line): newFile.write(line) else: newFile.write("*BAD DATA " + line) newFile.close() oldFile.close() From kent37 at tds.net Mon May 8 19:53:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 May 2006 13:53:24 -0400 Subject: [Tutor] trouble with re In-Reply-To: References: Message-ID: <445F8594.50306@tds.net> Ertl, John wrote: > I have a file with 10,000 + lines and it has a coma delimited string on each > line. > > The file should look like: > > DFRE,ship name,1234567 > FGDE,ship 2, > ,sdfsf > > The ,sdfsf line is bad data > > p = re.compile('\d{7}$ | [,]$') # this is the line that I can not get > correct I an trying to find lines that end in a comma or 7 digits Spaces are significant in regular expressions unless you compile them with the re.VERBOSE flag. Also you don't need to make a group for a single character. Try p = re.compile('\d{7}$|,$') or maybe p = re.compile('(\d{7}|,)$') Actually since the seven digits are preceded by the comma you could just make the digits optional: p = re.compile(',(\d{7})?$') Kent From john.ertl at fnmoc.navy.mil Mon May 8 20:00:25 2006 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Mon, 8 May 2006 11:00:25 -0700 Subject: [Tutor] trouble with re Message-ID: Kent, Thanks for the nock on the head, that has bitten me before. Taking out the spaces worked great. Thanks again, John Ertl -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Monday, May 08, 2006 10:53 AM Cc: tutor at python.org Subject: Re: [Tutor] trouble with re Ertl, John wrote: > I have a file with 10,000 + lines and it has a coma delimited string on each > line. > > The file should look like: > > DFRE,ship name,1234567 > FGDE,ship 2, > ,sdfsf > > The ,sdfsf line is bad data > > p = re.compile('\d{7}$ | [,]$') # this is the line that I can not get > correct I an trying to find lines that end in a comma or 7 digits Spaces are significant in regular expressions unless you compile them with the re.VERBOSE flag. Also you don't need to make a group for a single character. Try p = re.compile('\d{7}$|,$') or maybe p = re.compile('(\d{7}|,)$') Actually since the seven digits are preceded by the comma you could just make the digits optional: p = re.compile(',(\d{7})?$') Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From cappy2112 at gmail.com Mon May 8 20:08:38 2006 From: cappy2112 at gmail.com (Tony C) Date: Mon, 8 May 2006 11:08:38 -0700 Subject: [Tutor] Should I use generators here? In-Reply-To: <001701c6728c$425e1dd0$0c01a8c0@XPpro> References: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> <001701c6728c$425e1dd0$0c01a8c0@XPpro> Message-ID: <8249c4ac0605081108u1620b927t41b4e92a4f89283a@mail.gmail.com> Thus you should probably do: > > try: > fh=open(Onefile, "r") > Filecontents = fh.readlines() # these files are very > small, > > # other code here > Summary[Onefile] = deepcopy(Stats) # associate each > > fh.close() > except IOError: > print("\nFATAL ERROR ocurred opening %s for input" % > Onefile) > except IOError: > print("\nFatal error occurred reading from %s\n\n" % > InputFilename) > > > >>Even if you decide to stick with two try blocks you shouldn't need the > >>else construct. Either break or exit as part of the first except > >>handler. Got it. > > >>I'm also somewhat confused as to why you seem so interested > >> the length of the longest filename? Apologies fo rnot elaborating fully. The program is about 98% finished. It collects the stats just fine, and displays them. Howevr, I wanted to display the stats for each file, as well as an overall summary of all files. Knowing the length of the longest filename is only to be used for formatting the output on the screen, so all the stats below it will line up in the same column. example... (this is how the stats for each file is displayed now) File1.bas 100 Lines, 200 subs, 300 funcs RealllyBigFilename.bas 2000 lines, 2000 subs, 4000 funcs This is what I what it will look like when the display formatting is finished File1.bas 100 Lines, 200 subs, 300 funcs RealllyBigFilename.bas 2000 lines, 2000 subs, 4000 funcs No need to deal with this issue, I can figure that out. I'm more interested in performance tweaks. Thanks for your reply Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060508/f9c3e7ce/attachment.html From ema at linux.it Mon May 8 19:55:07 2006 From: ema at linux.it (Emanuele Rocca) Date: Mon, 8 May 2006 19:55:07 +0200 Subject: [Tutor] simple question about numeric types In-Reply-To: <4457DC12.9090603@aon.at> References: <4457DC12.9090603@aon.at> Message-ID: <20060508175507.GA18362@darkmoon.home> Hello list, I've got a question partially related to this thread. * Gregor Lingl , [2006-05-03 0:24 +0200]: > v= > if isinstance(v, int) or isinstance(v, float): > I wonder which is the recommended way to check the type of a value. In other words, what should I choose between: isinstance(v, int) type(v) is int v.__class__ is int There's simply more than one way to do it or some of them are discouraged? I've been told on #python that .__class__ is probably the worst one, but without precise motivation, just as a personal opinion. ciao, ema -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20060508/d37548be/attachment.pgp From alan.gauld at freenet.co.uk Mon May 8 22:19:40 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 8 May 2006 21:19:40 +0100 Subject: [Tutor] using variables as args References: <20060508152139.89896.qmail@web53713.mail.yahoo.com> Message-ID: <003d01c672dc$bca83670$0c01a8c0@XPpro> > I'm trying to start a shell script with 4 arguments > from my python script. I'm having problems trying to > figure out the best way to do this. Use a format string: cmd = "myscript %s %s %s %s" os.system(cmd % (p1,p2,p3,p4)) OR cmdstr = cmd % p1,p2,p3,p4 os.system(cmdstr) The second form is easier to debug... > to use popen3 to keep track of stdin, stdout, and err, Ok, substitute popen3 for system(). Or better still use the subprocess module and the Popen class. See the OS topic in my tutor for more on the subprocess module. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jjabson at yahoo.com Mon May 8 22:22:17 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Mon, 8 May 2006 13:22:17 -0700 (PDT) Subject: [Tutor] using variables as args In-Reply-To: <003d01c672dc$bca83670$0c01a8c0@XPpro> Message-ID: <20060508202217.7687.qmail@web53702.mail.yahoo.com> Thank you, Alan! I'll try using POPEN. Jerome --- Alan Gauld wrote: > > I'm trying to start a shell script with 4 > arguments > > from my python script. I'm having problems trying > to > > figure out the best way to do this. > > Use a format string: > > cmd = "myscript %s %s %s %s" > os.system(cmd % (p1,p2,p3,p4)) > > OR > > cmdstr = cmd % p1,p2,p3,p4 > os.system(cmdstr) > > The second form is easier to debug... > > > to use popen3 to keep track of stdin, stdout, and > err, > > Ok, substitute popen3 for system(). > Or better still use the subprocess module and > the Popen class. > > See the OS topic in my tutor for more on the > subprocess > module. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at gmail.com Tue May 9 00:15:02 2006 From: flaxeater at gmail.com (Chad Crabtree) Date: Mon, 8 May 2006 18:15:02 -0400 Subject: [Tutor] simple question about numeric types In-Reply-To: <20060508175507.GA18362@darkmoon.home> References: <4457DC12.9090603@aon.at> <20060508175507.GA18362@darkmoon.home> Message-ID: <584940990605081515h2685c23fva6f4bad13f1e826c@mail.gmail.com> I think isinstance() is probably the best way to do this. I however always do type(x)==TestType: where TestType is a string that is returned from type() or not what ever the case. On 5/8/06, Emanuele Rocca wrote: > Hello list, > I've got a question partially related to this thread. > > * Gregor Lingl , [2006-05-03 0:24 +0200]: > > v= > > if isinstance(v, int) or isinstance(v, float): > > > > I wonder which is the recommended way to check the type of a value. > > In other words, what should I choose between: > isinstance(v, int) > type(v) is int > v.__class__ is int > > There's simply more than one way to do it or some of them are > discouraged? > > I've been told on #python that .__class__ is probably the worst one, but > without precise motivation, just as a personal opinion. > > ciao, > ema > > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.3 (GNU/Linux) > > iD8DBQFEX4X7C6DuA+rxm2ARAio8AJ9VWrIjlXL5bk43o0LwS1ZwPE3gZACdGTWI > eIRPzxfs6KRpYc3bF2W4RwU= > =Tmcs > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From flaxeater at gmail.com Tue May 9 00:29:48 2006 From: flaxeater at gmail.com (Chad Crabtree) Date: Mon, 8 May 2006 18:29:48 -0400 Subject: [Tutor] web intefaces? In-Reply-To: <445CE2E5.5060008@yahoo.es> References: <445CE2E5.5060008@yahoo.es> Message-ID: <584940990605081529w25071848g58f2956db260e005@mail.gmail.com> While everything that Alan Guald said is true, there are a couple of options for you. Provided you know HTML (you must), you could generate html pragmatically but, knowledge of html is still mandatory. Your options are, basically http://www.cherrypy.org Which is an app server that should be fairly easy to package up with, say py2exe. Another option, with CGI (pretty easy) is found in the standard library. http://docs.python.org/lib/module-CGIHTTPServer.html If you do this as a personal app I would make sure to use an alternate port number like 11224, or something. HTH Best of Luck. On 5/6/06, Alfonso wrote: > I would like to experiment with web interfaces and python. After some googling, I'm quite confused, does somebody know of a good link about this topic / what do you think that is the best software option to design web user intefaces with python? I mean web interfaces for common programms (so it's not important to me to have a very robust web server), the web server should run in the machine of the user of the programm.And it should be easy installed, as bundle, when I distribute the programm. > > Thank very much for your help. > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue May 9 02:26:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 May 2006 20:26:06 -0400 Subject: [Tutor] simple question about numeric types In-Reply-To: <20060508175507.GA18362@darkmoon.home> References: <4457DC12.9090603@aon.at> <20060508175507.GA18362@darkmoon.home> Message-ID: <445FE19E.8050307@tds.net> Emanuele Rocca wrote: > Hello list, > I've got a question partially related to this thread. > > * Gregor Lingl , [2006-05-03 0:24 +0200]: >> v= >> if isinstance(v, int) or isinstance(v, float): >> > > I wonder which is the recommended way to check the type of a value. Often the recommendation is just to assume that a value is the correct type and be ready to catch an exception if it is not. This allows 'duck typing' to work - your function (or whatever) will accept any value that implements the correct methods, whether it has a particular inheritance relationship with the expected type or not. For example you could make a function that accepted any mapping object whether it inherits from dict or not. > > In other words, what should I choose between: > isinstance(v, int) This is good because it will accept subclasses of int as well as plain ints. (Not that subclasses of int are that common, but other classes might be subclassed.) > type(v) is int > v.__class__ is int I think these are equivalent, though I would prefer the first. They are the most restrictive choice because they require an exact class match. Kent > > There's simply more than one way to do it or some of them are > discouraged? > > I've been told on #python that .__class__ is probably the worst one, but > without precise motivation, just as a personal opinion. > > ciao, > ema > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ronin_cpim at hotmail.com Tue May 9 04:04:30 2006 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 08 May 2006 22:04:30 -0400 Subject: [Tutor] Python media player? Message-ID: Is there such a thing as a Python coded media player? I'm having troble with my Windows Media Player playing commercial DVDs and can't fathom why it should be so difficult to debug. I'm hoping the logic would be much clearer in Python. RC _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From john at fouhy.net Tue May 9 04:50:04 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 9 May 2006 14:50:04 +1200 Subject: [Tutor] Python media player? In-Reply-To: References: Message-ID: <5e58f2e40605081950n7cdb6760sd211808f0636d865@mail.gmail.com> On 09/05/06, CPIM Ronin wrote: > Is there such a thing as a Python coded media player? I'm having troble with > my Windows Media Player playing commercial DVDs and can't fathom why it > should be so difficult to debug. I'm hoping the logic would be much clearer > in Python. pyMedia, maybe? I got that from the cheese shop (under the links menu at python.org): http://cheeseshop.python.org/pypi/PyMedia/1.2.3.0 See also http://cheeseshop.python.org/pypi?:action=browse&asdf=338. -- John. From falcon3166 at hotmail.com Tue May 9 06:25:40 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 8 May 2006 22:25:40 -0600 Subject: [Tutor] How do I do cubic roots and cubic exponents (and higher roots and exponents) in Python? Message-ID: Hi all, How do I do cubic (and higher) roots and exponents in Python? I already took a look in Python and didn't find anything. Thanks, Nathan Pinno Web Surfer's Store http://www.websurfstore.ca MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060508/b122f11a/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060508/b122f11a/attachment.gif From dyoo at hkn.eecs.berkeley.edu Tue May 9 07:23:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 May 2006 22:23:49 -0700 (PDT) Subject: [Tutor] How do I do cubic roots and cubic exponents (and higher roots and exponents) in Python? In-Reply-To: References: Message-ID: > How do I do cubic (and higher) roots and exponents in Python? I already > took a look in Python and didn't find anything. Hi Nathan, I think you're looking for the '**' operator. Like addition and multiplication, it can take in two numbers. ########## >>> 2 ** 2 4 >>> 2 ** 3 8 >>> 2 ** 4 16 ########## Best of wishes! From glingl at aon.at Tue May 9 09:53:34 2006 From: glingl at aon.at (Gregor Lingl) Date: Tue, 09 May 2006 09:53:34 +0200 Subject: [Tutor] How do I do cubic roots and cubic exponents (and higher roots and exponents) in Python? In-Reply-To: References: Message-ID: <44604A7E.80103@aon.at> Danny Yoo schrieb: > > >>How do I do cubic (and higher) roots ... >> > >I think you're looking for the '**' operator. Like addition and >multiplication, it can take in two numbers. > >########## > > >>>>2 ** 2 >>>> >>>> >4 > > And they also can be floating point numbers >>> 2 ** 0.5 1.4142135623730951 >>> 2 **(1.0/3) 1.2599210498948732 >>> 1.2599210498948732**3 2.0 :-) gregor From traviesomono at yahoo.es Tue May 9 11:19:46 2006 From: traviesomono at yahoo.es (Alfonso) Date: Tue, 09 May 2006 11:19:46 +0200 Subject: [Tutor] web intefaces? In-Reply-To: <584940990605081529w25071848g58f2956db260e005@mail.gmail.com> References: <445CE2E5.5060008@yahoo.es> <584940990605081529w25071848g58f2956db260e005@mail.gmail.com> Message-ID: <44605EB2.4050606@yahoo.es> Chad Crabtree wrote: > While everything that Alan Guald said is true, there are a couple of > options for you. Provided you know HTML (you must), you could > generate html pragmatically but, knowledge of html is still mandatory. > Your options are, basically > > http://www.cherrypy.org > Which is an app server that should be fairly easy to package up with, > say py2exe. > > Another option, with CGI (pretty easy) is found in the standard library. > http://docs.python.org/lib/module-CGIHTTPServer.html > > If you do this as a personal app I would make sure to use an alternate > port number like 11224, or something. > > HTH > Best of Luck. > > On 5/6/06, Alfonso wrote: >> I would like to experiment with web interfaces and python. After some >> googling, I'm quite confused, does somebody know of a good link about >> this topic / what do you think that is the best software option to >> design web user intefaces with python? I mean web interfaces for >> common programms (so it's not important to me to have a very robust >> web server), the web server should run in the machine of the user of >> the programm.And it should be easy installed, as bundle, when I >> distribute the programm. >> >> Thank very much for your help. >> >> >> >> ______________________________________________ >> LLama Gratis a cualquier PC del Mundo. >> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. >> http://es.voice.yahoo.com >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Thank you very much for your answers ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From janos.juhasz at VELUX.com Tue May 9 12:07:24 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 9 May 2006 12:07:24 +0200 Subject: [Tutor] 7bit - 8bit In-Reply-To: Message-ID: Dear All, I have to convert a binary stream from a monitoring device to another format. The highets bit of data bytes is replaced by 0 and placed after every 7 bytes into a correction byte. I would like to decode it as simple as possible. May someone suggest an elegant solution for that ? Yours sincerely, ______________________________ Janos Juhasz From RPhillips at engineer.co.summit.oh.us Tue May 9 12:47:21 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Tue, 09 May 2006 06:47:21 -0400 Subject: [Tutor] web intefaces? Message-ID: I like Karrigell ...http://www.karrigell.com/ for being flexible, complete, lightweight, and easy to learn. I don't know how it scales, but that's not really a consideration for the applications you describe. Ron >>> "Chad Crabtree" 5/8/2006 6:29 PM >>> While everything that Alan Guald said is true, there are a couple of options for you. Provided you know HTML (you must), you could generate html pragmatically but, knowledge of html is still mandatory. Your options are, basically http://www.cherrypy.org Which is an app server that should be fairly easy to package up with, say py2exe. Another option, with CGI (pretty easy) is found in the standard library. http://docs.python.org/lib/module-CGIHTTPServer.html If you do this as a personal app I would make sure to use an alternate port number like 11224, or something. HTH Best of Luck. On 5/6/06, Alfonso < traviesomono at yahoo.es > wrote: > I would like to experiment with web interfaces and python. After some googling, I'm quite confused, does somebody know of a good link about this topic / what do you think that is the best software option to design web user intefaces with python? I mean web interfaces for common programms (so it's not important to me to have a very robust web server), the web server should run in the machine of the user of the programm.And it should be easy installed, as bundle, when I distribute the programm. > > Thank very much for your help. > > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > 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/20060509/b1690f15/attachment.htm From payal-python at scriptkitchen.com Tue May 9 13:16:03 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 9 May 2006 07:16:03 -0400 Subject: [Tutor] opening multiple connections to a port Message-ID: <20060509111603.GA29408@tranquility.scriptkitchen.com> Hi, I have to see how many open connection can a particular service handle. So, I want to similuate something like this but using Python. telnet I will be keeping these connections open for around 60 seconds. Can anyone tell me how do I start with this in Python? I read a bit about telnetlib, but unable to figure how to open multiple simeltaneous connections. With warm regards, -Payal From kent37 at tds.net Tue May 9 14:09:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 May 2006 08:09:59 -0400 Subject: [Tutor] opening multiple connections to a port In-Reply-To: <20060509111603.GA29408@tranquility.scriptkitchen.com> References: <20060509111603.GA29408@tranquility.scriptkitchen.com> Message-ID: <44608697.1020009@tds.net> Payal Rathod wrote: > Hi, > I have to see how many open connection can a particular service handle. > So, I want to similuate something like this but using Python. > telnet > > I will be keeping these connections open for around 60 seconds. Can > anyone tell me how do I start with this in Python? I read a bit about > telnetlib, but unable to figure how to open multiple simeltaneous > connections. If you create and open multiple instances of telnetlib.Telnet you should have multiple connections to the host. Of course for this test to give meaningful results the machine running the test must be able to open more outgoing ports than the number of connections supported by the host, or you will have to use multiple client machines. Kent From kent37 at tds.net Tue May 9 14:14:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 May 2006 08:14:45 -0400 Subject: [Tutor] 7bit - 8bit In-Reply-To: References: Message-ID: <446087B5.4020306@tds.net> J?nos Juh?sz wrote: > Dear All, > > I have to convert a binary stream from a monitoring device to another > format. > The highets bit of data bytes is replaced by 0 and placed after every 7 > bytes into a correction byte. > I would like to decode it as simple as possible. > May someone suggest an elegant solution for that ? By decode, do you mean go from the 7bit representation to the 8-bit binary? A few things you may need: To convert a string to a list of integer values use a list comprehension and ord(): [ ord(c) for c in s ] or map(): map(ord, s) To extract or set bits use the bitwise logical operators & and | To assemble a list of integers back into a string use chr(), list comp or map(), and join(): ''.join([chr(b) for b in bytes]) or ''.join(map(chr, bytes)) HTH Kent From kent37 at tds.net Tue May 9 14:58:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 May 2006 08:58:11 -0400 Subject: [Tutor] Should I use generators here? In-Reply-To: <445F1722.6070007@tds.net> References: <8249c4ac0605071839x741eb6car1a4284f613ac5c86@mail.gmail.com> <445F1722.6070007@tds.net> Message-ID: <446091E3.8050003@tds.net> Kent Johnson wrote: > Generators are not an optimization technique so much as a way to > structure code that includes iteration. This recipe is a good example of how using a simple generator can encapsulate a bit of processing that might be awkward to include in a larger processing loop. Generators are really useful when you want to process items in a sequence, producing a new sequence, and the processing requires maintaining some state. A generator lets you encapsulate the state and the logic using the state into a function that is usable by client code as a simple sequence. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496682 Kent From traviesomono at yahoo.es Tue May 9 16:12:50 2006 From: traviesomono at yahoo.es (Alfonso) Date: Tue, 09 May 2006 16:12:50 +0200 Subject: [Tutor] web intefaces? In-Reply-To: References: Message-ID: <4460A362.80109@yahoo.es> Ron Phillips wrote: > I like Karrigell ...http://www.karrigell.com/ for being flexible, > complete, lightweight, and easy to learn. I don't know how it scales, > but that's not really a consideration for the applications you describe. > > Ron > > >>> "Chad Crabtree" 5/8/2006 6:29 PM >>> > While everything that Alan Guald said is true, there are a couple of > options for you. Provided you know HTML (you must), you could > generate html pragmatically but, knowledge of html is still mandatory. > Your options are, basically > > _http://www.cherrypy.org _ > Which is an app server that should be fairly easy to package up with, > say py2exe. > > Another option, with CGI (pretty easy) is found in the standard library. > _http://docs.python.org/lib/module-CGIHTTPServer.html_ > > If you do this as a personal app I would make sure to use an alternate > port number like 11224, or something. > > HTH > Best of Luck. > > On 5/6/06, Alfonso <_ traviesomono at yahoo.es > _ > wrote: > > I would like to experiment with web interfaces and python. After > some googling, I'm quite confused, does somebody know of a good link > about this topic / what do you think that is the best software option > to design web user intefaces with python? I mean web interfaces for > common programms (so it's not important to me to have a very robust > web server), the web server should run in the machine of the user of > the programm.And it should be easy installed, as bundle, when I > distribute the programm. > > > > Thank very much for your help. > > > > > > > > ______________________________________________ > > LLama Gratis a cualquier PC del Mundo. > > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > > _http://es.voice.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 > Thank you Ron, I will have a look at that too ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From m_webber_sydney at yahoo.com.au Tue May 9 18:21:38 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Tue, 9 May 2006 17:21:38 +0100 Subject: [Tutor] Summing part of a list Message-ID: <001e01c67384$a5f19c70$0200a8c0@kookaburra> I have a list that looks a bit like this - [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] The list items are tuples, the first item of which is a country code, and the second of which is a numeric count. The list is guarenteed SORTED in descending order of the numeric count. What I need is a list with all the members whose count is less than 3 replaced by a single member with the counts added together. In this case, I want : [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), (u'OTHER', 17)] Any ideas about neat ways to do this? The simplest way is to just build the new list with a basic loop over the original list. A slightly more sophisticated way is to split the original list using a list comprehension with an IF clause. I have the feeling that there's probably really neat and more Pythonic way - there are possibilities like zip, map, itertools. Any hints about what to look at? Remember that the list is sorted already. If you can point me in the right direction, I'm sure I can work out the specifics of the code. Thanks Matthew From kent37 at tds.net Tue May 9 18:54:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 May 2006 12:54:09 -0400 Subject: [Tutor] Summing part of a list In-Reply-To: <001e01c67384$a5f19c70$0200a8c0@kookaburra> References: <001e01c67384$a5f19c70$0200a8c0@kookaburra> Message-ID: <4460C931.9060701@tds.net> Matthew Webber wrote: > I have a list that looks a bit like this - > > [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), > (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), > (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] > > The list items are tuples, the first item of which is a country code, and > the second of which is a numeric count. The list is guarenteed SORTED in > descending order of the numeric count. > > What I need is a list with all the members whose count is less than 3 > replaced by a single member with the counts added together. In this case, I > want : > [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), > (u'fin', 6), (u'ven', 6), (u'OTHER', 17)] > > Any ideas about neat ways to do this? The simplest way is to just build the > new list with a basic loop over the original list. A slightly more > sophisticated way is to split the original list using a list comprehension > with an IF clause. > > I have the feeling that there's probably really neat and more Pythonic way - > there are possibilities like zip, map, itertools. Any hints about what to > look at? Remember that the list is sorted already. If you can point me in > the right direction, I'm sure I can work out the specifics of the code. Hmm, must be generator day today. Here is a generator that does what you want: In [1]: data = [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), ...: (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), ...: (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] In [10]: def summarize(data): ....: sum = 0 ....: othersFound = False ....: for item in data: ....: if item[1] > 3: ....: yield item ....: else: ....: sum += item[1] ....: othersFound = True ....: if othersFound: ....: yield ('OTHER', sum) ....: In [11]: print list(summarize(data)) [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), ('OTHER', 17)] In [12]: print list(summarize(data[:4])) [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299)] The loop yields all the pairs that have values bigger than three. When the end of the loop is reached, if there were any residuals the 'OTHER' item is yielded. (If the values are always >0 you could get rid of the othersFound flag and just use sum as the flag.) You could probably work out a solution using itertools.groupby() also, or you could use two list comps, one filtering for value>3 and one filtering for value < 3. This gives a one-line solution but it iterates the list twice. List comps are fast enough that this might actually be faster than the generator solution: In [5]: [ item for item in data if item[1] > 3 ] + [('OTHER', sum([item[1] for item in data if item[1] <= 3]))] Out[5]: [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), ('OTHER', 17)] Neither of these solutions rely on the list being sorted. In fact I originally wrote a generator that did rely on the list sort and it was longer than the one I show here! HTH Kent From bgailer at alum.rpi.edu Tue May 9 18:56:23 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 09 May 2006 09:56:23 -0700 Subject: [Tutor] Summing part of a list In-Reply-To: <001e01c67384$a5f19c70$0200a8c0@kookaburra> References: <001e01c67384$a5f19c70$0200a8c0@kookaburra> Message-ID: <4460C9B7.3010808@alum.rpi.edu> Matthew Webber wrote: > I have a list that looks a bit like this - > > [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), > (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), > (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] > > The list items are tuples, the first item of which is a country code, and > the second of which is a numeric count. The list is guarenteed SORTED in > descending order of the numeric count. > > What I need is a list with all the members whose count is less than 3 > Do you mean less than 4? That's how your example works. > replaced by a single member with the counts added together. In this case, I > want : > [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), > (u'fin', 6), (u'ven', 6), (u'OTHER', 17)] > > Any ideas about neat ways to do this? cnt = 0 for pos, item in enumerate(yourList[::-1]): if item[1] >= 4: break cnt += item[1] yourList = yourList[:len(yourList)-pos] + (u'OTHER', cnt) > The simplest way is to just build the > new list with a basic loop over the original list. A slightly more > sophisticated way is to split the original list using a list comprehension > with an IF clause. > > I have the feeling that there's probably really neat and more Pythonic way - > there are possibilities like zip, map, itertools. Any hints about what to > look at? Remember that the list is sorted already. If you can point me in > the right direction, I'm sure I can work out the specifics of the code. > > Thanks > Matthew > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From m_webber_sydney at yahoo.com.au Tue May 9 18:56:43 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Tue, 9 May 2006 17:56:43 +0100 Subject: [Tutor] Summing part of a list In-Reply-To: <001e01c67384$a5f19c70$0200a8c0@kookaburra> Message-ID: <002001c67389$8ceddb30$0200a8c0@kookaburra> To expand on my original posting, I came up with this code which works ok : count_country_aggregated = [cc for cc in count_country if cc[1]>3] count_country_aggregated.append(('OTHER',sum([cc[1] for cc in count_country if cc[1]<=3]))) But it uses 2 list comprehensions (therefore 2 passes of the original list). Surely there is a neater way. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Matthew Webber Sent: 09 May 2006 17:22 To: tutor at python.org Subject: [Tutor] Summing part of a list I have a list that looks a bit like this - [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] The list items are tuples, the first item of which is a country code, and the second of which is a numeric count. The list is guarenteed SORTED in descending order of the numeric count. What I need is a list with all the members whose count is less than 3 replaced by a single member with the counts added together. In this case, I want : [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), (u'OTHER', 17)] Any ideas about neat ways to do this? The simplest way is to just build the new list with a basic loop over the original list. A slightly more sophisticated way is to split the original list using a list comprehension with an IF clause. I have the feeling that there's probably really neat and more Pythonic way - there are possibilities like zip, map, itertools. Any hints about what to look at? Remember that the list is sorted already. If you can point me in the right direction, I'm sure I can work out the specifics of the code. From dyoo at hkn.eecs.berkeley.edu Tue May 9 20:03:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 9 May 2006 11:03:36 -0700 (PDT) Subject: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying In-Reply-To: References: Message-ID: > One of the major complaints that people have made about the "One Day of IDLE > Toying" tutorial I've written is that the screenshots are badly outdated. > > http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ > > I was curious if anyone wanted to volunteer to provide fresh, updated > Windows XP screenshots to replace the ones on the IDLE tutorial. Thanks everyone! I got some screenshots from Alan Gauld, and will revise the main page later today with the updated images. From Christian.Wyglendowski at greenville.edu Tue May 9 20:13:21 2006 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue, 9 May 2006 13:13:21 -0500 Subject: [Tutor] web intefaces? Message-ID: > > >>> "Chad Crabtree" 5/8/2006 6:29 PM >>> > > While everything that Alan Guald said is true, there are a > couple of > > options for you. Provided you know HTML (you must), you > could generate > > html pragmatically but, knowledge of html is still mandatory. > > Your options are, basically > > > > _http://www.cherrypy.org _ Which > is an app > > server that should be fairly easy to package up with, say py2exe. If you do go with CherryPy, check out this recipe I submitted to the online Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481 It was written for CherryPy 2.1 but should still work with the current 2.2 release. Christian http://www.dowski.com From m_webber_sydney at yahoo.com.au Tue May 9 21:18:20 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Tue, 9 May 2006 20:18:20 +0100 Subject: [Tutor] Summing part of a list In-Reply-To: <4460C931.9060701@tds.net> Message-ID: <002701c6739d$57449550$0200a8c0@kookaburra> Thanks Kent, I liked the generator solution (I knew there had to be something like that). -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: 09 May 2006 17:54 Cc: tutor at python.org Subject: Re: [Tutor] Summing part of a list << snip >> Hmm, must be generator day today. Here is a generator that does what you want: In [1]: data = [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), ...: (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3), ...: (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)] In [10]: def summarize(data): ....: sum = 0 ....: othersFound = False ....: for item in data: ....: if item[1] > 3: ....: yield item ....: else: ....: sum += item[1] ....: othersFound = True ....: if othersFound: ....: yield ('OTHER', sum) ....: In [11]: print list(summarize(data)) [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin', 6), (u'ven', 6), ('OTHER', 17)] << snip >> From andre.roberge at gmail.com Tue May 9 21:21:44 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 9 May 2006 16:21:44 -0300 Subject: [Tutor] web intefaces? In-Reply-To: References: Message-ID: <7528bcdd0605091221w549f2225p253513624409f6e5@mail.gmail.com> On 5/9/06, Christian Wyglendowski wrote: [on creating a web app...] > > If you do go with CherryPy, check out this recipe I submitted to the > online Python Cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481 > > It was written for CherryPy 2.1 but should still work with the current > 2.2 release. > I second this, absolutely. I have started creating such an app ["Crunchy Frog"] using CherryPy. There are 10 tutorial examples included in the distribution, which are a big help to get started. Andr? P.S. Thank you Christian for your CherryPy newbie friendly recipe! > Christian > http://www.dowski.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From python at venix.com Tue May 9 21:46:55 2006 From: python at venix.com (Python) Date: Tue, 09 May 2006 15:46:55 -0400 Subject: [Tutor] web intefaces? In-Reply-To: <584940990605081529w25071848g58f2956db260e005@mail.gmail.com> References: <445CE2E5.5060008@yahoo.es> <584940990605081529w25071848g58f2956db260e005@mail.gmail.com> Message-ID: <1147204015.20702.817.camel@www.venix.com> On Mon, 2006-05-08 at 18:29 -0400, Chad Crabtree wrote: > While everything that Alan Guald said is true, there are a couple of > options for you. Provided you know HTML (you must), you could > generate html pragmatically but, knowledge of html is still mandatory. > Your options are, basically > > http://www.cherrypy.org > Which is an app server that should be fairly easy to package up with, > say py2exe. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481 This is an example of configuring a cherrypy application so that it runs and starts the browser. It's a convenient way to make sure that the web application is running before the browser tries to access it. It also shows how a cherrypy application can stop itself. -- Lloyd Kvam Venix Corp From jjabson at yahoo.com Wed May 10 01:06:09 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Tue, 9 May 2006 16:06:09 -0700 (PDT) Subject: [Tutor] help with erros using subprocess module Message-ID: <20060509230609.5952.qmail@web53706.mail.yahoo.com> Hi, I've been trying to write a wrapper around some shells scripts using the subprocess module. But I'm getting errors I quite don't know how to debug. I've only been writing Python for a few months and starting processes are new to me. Here's my code: import os import re import subprocess #################### #### Definition #### #################### def proc(cmd_in): cmd = cmd_in os.chdir("/home/qauser/jerome") outFile = os.path.join(os.curdir, "output.log") outptr = file(outFile, "w") errFile = os.path.join(os.curdir, "error.log") errptr = file(errFile, "w") retval = subprocess.call(cmd, 0, None, None, outptr, errptr) errptr.close() outptr.close() if not retval == 0: errptr = file(errFile, "r") errData = errptr.read() errptr.close() raise Exception("Error executing command: " + repr(errData)) def setup(): print "=== Starting Setup ===" proc("/home/qauser/jerome/qaSetup.sh") print "=== Setup Complete ===" def run_junit(): file_in = open("/home/qauser/automation/testdata/junit_master_file", "r") match = re.compile('#+') work_list = [] for line in file_in: work = line work = work.rstrip('\n') if match.search(work): found = False else: found = True if found == True: work_list = work.split(',') arg1 = work_list[0] arg2 = work_list[1] arg3 = work_list[2] arg4 = work_list[3] cmd = "/home/qauser/jerome/qaRun.sh %s %s %s %s" cmdstr = cmd % (arg1,arg2,arg3,arg4) print "=== Starting JUnit Run ===" proc(cmdstr) print "=== JUnit Run Complete ===" #################### ###### Main ###### #################### setup() run_junit() The setup() def seems to work great, but the run_junit() seems to have problems. I believe due to the params I'm passing. Here are the errors I'm getting: [qauser at gary automation]$ ./runJunit.py === Starting JUnit Run === Traceback (most recent call last): File "/home/qauser/automation/runJunit.py", line 63, in ? run_junit() File "/home/qauser/automation/runJunit.py", line 54, in run_junit proc(cmdstr) File "/home/qauser/automation/runJunit.py", line 18, in proc retval = subprocess.call(cmd, 0, None, None, outptr, errptr) File "/opt/python-2.4.3/lib/python2.4/subprocess.py", line 412, in call return Popen(*args, **kwargs).wait() File "/opt/python-2.4.3/lib/python2.4/subprocess.py", line 542, in __init__ errread, errwrite) File "/opt/python-2.4.3/lib/python2.4/subprocess.py", line 975, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I can't seem to figure out what file or directory is missing. Your help is greatly appreciated, Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From yi at yiqiang.net Wed May 10 01:45:58 2006 From: yi at yiqiang.net (Yi Qiang) Date: Tue, 09 May 2006 16:45:58 -0700 Subject: [Tutor] question regarding subprocess.Popen Message-ID: <446129B6.8080807@yiqiang.net> Hi list, I am launching another python program in my python daemon like this: pobj = subprocess.Popen(tlsmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, close_fds = True, bufsize = 0) I want to detect when the process has exited abnormally (or when I ctrl+c it)so I thought I could use pobj.returncode. However after fiddling with it for a while my KeyboardInterrupt does not seem to be sent to pobj (i tried re-raising a KeyboardInterrupt there as well) nor did testing for pobj.returncode yield any results. Any ideas? Thanks From Gideon.STREET at ergon.com.au Wed May 10 08:37:58 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Wed, 10 May 2006 16:37:58 +1000 Subject: [Tutor] For loop question Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9B@ebnewem01.ergon> Hi all, Been trying to understand why the following doesn't work: HostFile = open("hosts.txt", 'r') host = HostFile.readlines() for item in host: print "Connecting to device",item tn = telnetlib.Telnet(item) ... Do some other stuff here ... I get the following error: Traceback (most recent call last): File "testtelnet.py", line 14, in ? tn = telnetlib.Telnet(item) File "c:\gideon\python24\lib\telnetlib.py", line 208, in __init__ self.open(host, port) File "c:\gideon\python24\lib\telnetlib.py", line 225, in open for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): socket.gaierror: (11001, 'getaddrinfo failed') The hosts.txt file contains device names on separate lines. If I remove the tn = .... Line the for loop iterates as I expect it to. Can't understand why I can't pass "item" as a string to the telnetlib.Telnet command. Cheers Gideon This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 From wescpy at gmail.com Wed May 10 09:25:17 2006 From: wescpy at gmail.com (w chun) Date: Wed, 10 May 2006 00:25:17 -0700 Subject: [Tutor] For loop question In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9B@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9B@ebnewem01.ergon> Message-ID: <78b3a9580605100025p3e89dc13n66686518960cc949@mail.gmail.com> > Been trying to understand why the following doesn't work: > > HostFile = open("hosts.txt", 'r') > host = HostFile.readlines() > > for item in host: > print "Connecting to device",item > tn = telnetlib.Telnet(item) > : > File "c:\gideon\python24\lib\telnetlib.py", line 225, in open > for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): > socket.gaierror: (11001, 'getaddrinfo failed') > > Can't > understand why I can't pass "item" as a string to the telnetlib.Telnet > command. hi gideon, welcome to Python! your program is very close to working. without actually being where you are, i'm going to try to figure out the problem: the error socket.gaierror means that it cannot find the address information for the host you passed it. because you are reading in the hostnames from a file, my guess is that the trailing line separators (NEWLINE [\n] for Unix-based machines and carriage RETURN followed by NEWLINE [\r\n] on Win32 hosts) is being considered as part of the hostname. Python does not strip the trailing line separators for you (which is useful if you need to write the same strings out to another file). i would do something like: item = item.strip() before creating the telnet session... that should help. another thing is that if the host file is large, you may wish to iterate through the file one line at a time with a list comprehension to do the stripping for you: HostFile = open("hosts.txt", 'r') for item in [x.strip() for x in HostFile]: : if you are using Python 2.4+, you can come up with an even better solution by using a generator expression that does lazier, ad hoc evaluation: HostFile = open("hosts.txt", 'r') for item in (x.strip() for x in HostFile): : this one will read and strip one line from the file as you process it while the previous solution still needs to come up with the entire list of stripped hosts before the for-loop can begin. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Wed May 10 11:52:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 May 2006 05:52:14 -0400 Subject: [Tutor] For loop question In-Reply-To: <78b3a9580605100025p3e89dc13n66686518960cc949@mail.gmail.com> References: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9B@ebnewem01.ergon> <78b3a9580605100025p3e89dc13n66686518960cc949@mail.gmail.com> Message-ID: <4461B7CE.9060609@tds.net> w chun wrote: > another thing is that if the host file is large, you may wish to > iterate through the file one line at a time with a list comprehension > to do the stripping for you: > > HostFile = open("hosts.txt", 'r') > for item in [x.strip() for x in HostFile]: > : Why is this better when the file is large? It still creates a list with all lines in it. > > if you are using Python 2.4+, you can come up with an even better > solution by using a generator expression that does lazier, ad hoc > evaluation: > > HostFile = open("hosts.txt", 'r') > for item in (x.strip() for x in HostFile): > : > > this one will read and strip one line from the file as you process it > while the previous solution still needs to come up with the entire > list of stripped hosts before the for-loop can begin. I would use this, it avoids reading the entire file at once and IMO is clear and straightforward: HostFile = open('hosts.txt') for item in HostFile: item = item.strip() ... or even HostFile = open('hosts.txt') for item in HostFile: tn = telnetlib.Telnet(item.strip()) ... Kent From kent37 at tds.net Wed May 10 14:55:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 May 2006 08:55:56 -0400 Subject: [Tutor] For loop question In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> References: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> Message-ID: <4461E2DC.7090802@tds.net> Smith, Jeff wrote: > At least with Python there's only one obvious way to do something :-) Yeah, right. A couple of minutes reading comp.lang.python will disabuse you of that notion :-) > > I'll see your simplification and raise (or lower) you a line. > > Why not simply: > > for item in file('hosts.txt'): > tn = telnetlib.Telnet(item.strip()) If you are willing to depend on the runtime to close the file that is fine. If you want to close it yourself you have to keep a reference to the open file. For short Python scripts I usually allow the runtime to close the file. For longer programs and anything written in Jython (which has different garbage collection behaviour) I usually use an explicit close(). Kent > > Jeff > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Kent Johnson > Sent: Wednesday, May 10, 2006 5:52 AM > Cc: tutor at python.org > Subject: Re: [Tutor] For loop question > > > w chun wrote: >> another thing is that if the host file is large, you may wish to >> iterate through the file one line at a time with a list comprehension >> to do the stripping for you: >> >> HostFile = open("hosts.txt", 'r') >> for item in [x.strip() for x in HostFile]: >> : > > Why is this better when the file is large? It still creates a list with > all lines in it. >> if you are using Python 2.4+, you can come up with an even better >> solution by using a generator expression that does lazier, ad hoc >> evaluation: >> >> HostFile = open("hosts.txt", 'r') >> for item in (x.strip() for x in HostFile): >> : >> >> this one will read and strip one line from the file as you process it >> while the previous solution still needs to come up with the entire >> list of stripped hosts before the for-loop can begin. > > I would use this, it avoids reading the entire file at once and IMO is > clear and straightforward: > HostFile = open('hosts.txt') > for item in HostFile: > item = item.strip() > ... > > or even > HostFile = open('hosts.txt') > for item in HostFile: > tn = telnetlib.Telnet(item.strip()) > ... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jsmith at medplus.com Wed May 10 14:42:47 2006 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 10 May 2006 08:42:47 -0400 Subject: [Tutor] For loop question Message-ID: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> At least with Python there's only one obvious way to do something :-) I'll see your simplification and raise (or lower) you a line. Why not simply: for item in file('hosts.txt'): tn = telnetlib.Telnet(item.strip()) Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Wednesday, May 10, 2006 5:52 AM Cc: tutor at python.org Subject: Re: [Tutor] For loop question w chun wrote: > another thing is that if the host file is large, you may wish to > iterate through the file one line at a time with a list comprehension > to do the stripping for you: > > HostFile = open("hosts.txt", 'r') > for item in [x.strip() for x in HostFile]: > : Why is this better when the file is large? It still creates a list with all lines in it. > > if you are using Python 2.4+, you can come up with an even better > solution by using a generator expression that does lazier, ad hoc > evaluation: > > HostFile = open("hosts.txt", 'r') > for item in (x.strip() for x in HostFile): > : > > this one will read and strip one line from the file as you process it > while the previous solution still needs to come up with the entire > list of stripped hosts before the for-loop can begin. I would use this, it avoids reading the entire file at once and IMO is clear and straightforward: HostFile = open('hosts.txt') for item in HostFile: item = item.strip() ... or even HostFile = open('hosts.txt') for item in HostFile: tn = telnetlib.Telnet(item.strip()) ... Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Wed May 10 16:59:21 2006 From: wescpy at gmail.com (w chun) Date: Wed, 10 May 2006 07:59:21 -0700 Subject: [Tutor] For loop question In-Reply-To: <4461E2DC.7090802@tds.net> References: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> <4461E2DC.7090802@tds.net> Message-ID: <78b3a9580605100759y3e98cde7ma8c21438d230c421@mail.gmail.com> >> HostFile = open("hosts.txt", 'r') >> for item in [x.strip() for x in HostFile]: >> : >> >>Why is this better when the file is large? It still creates a list with all lines in it. yup, that's why i mention this fact below while giving the genex solution. > > Why not simply: > > > > for item in file('hosts.txt'): > > tn = telnetlib.Telnet(item.strip()) > > If you are willing to depend on the runtime to close the file that is > fine. If you want to close it yourself you have to keep a reference to > the open file. > > For short Python scripts I usually allow the runtime to close the file. > For longer programs and anything written in Jython (which has different > garbage collection behaviour) I usually use an explicit close(). i'm still not comfortable without doing my own explicit close(), esp. for writing to files... maybe i'm just used to malloc/new-free pairs like i am with open-close, although on the other hand, getting rid of another line of code is tempting -- so i will actually do this with a short piece of code that is read-only. note for the uninitiated, open() == file(), or rather, open == file, or rather: >>> open is file True -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Wed May 10 17:02:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 May 2006 11:02:47 -0400 Subject: [Tutor] For loop question In-Reply-To: <78b3a9580605100759y3e98cde7ma8c21438d230c421@mail.gmail.com> References: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> <4461E2DC.7090802@tds.net> <78b3a9580605100759y3e98cde7ma8c21438d230c421@mail.gmail.com> Message-ID: <44620097.1090209@tds.net> w chun wrote: > Kent Johnson wrote: >> For short Python scripts I usually allow the runtime to close the file. >> For longer programs and anything written in Jython (which has different >> garbage collection behaviour) I usually use an explicit close(). > > i'm still not comfortable without doing my own explicit close(), esp. > for writing to files... maybe i'm just used to malloc/new-free pairs > like i am with open-close, although on the other hand, getting rid of > another line of code is tempting -- so i will actually do this with a > short piece of code that is read-only. Yes, for writing files I always use an explicit close(), thanks for the correction! Kent From struggleyb at gmail.com Wed May 10 18:51:35 2006 From: struggleyb at gmail.com (Bo Yang) Date: Thu, 11 May 2006 00:51:35 +0800 Subject: [Tutor] help with erros using subprocess module In-Reply-To: <20060509230609.5952.qmail@web53706.mail.yahoo.com> References: <20060509230609.5952.qmail@web53706.mail.yahoo.com> Message-ID: <44621A17.9030405@gmail.com> Jerome Jabson ??: > Hi, > > I've been trying to write a wrapper around some shells > scripts using the subprocess module. But I'm getting > errors I quite don't know how to debug. I've only been > writing Python for a few months and starting processes > are new to me. Here's my code: > > import os > import re > import subprocess > > #################### > #### Definition #### > #################### > > def proc(cmd_in): > cmd = cmd_in > os.chdir("/home/qauser/jerome") > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + > repr(errData)) > > def setup(): > print "=== Starting Setup ===" > proc("/home/qauser/jerome/qaSetup.sh") > print "=== Setup Complete ===" > > def run_junit(): > file_in = > open("/home/qauser/automation/testdata/junit_master_file", > "r") > Could you put the contents in the junit_master_file here ? Are the first field in every line where the cmd name locates contain the full path to the command ? > match = re.compile('#+') > work_list = [] > for line in file_in: > work = line > work = work.rstrip('\n') > if match.search(work): > found = False > else: > found = True > if found == True: > work_list = work.split(',') > arg1 = work_list[0] > arg2 = work_list[1] > arg3 = work_list[2] > arg4 = work_list[3] > cmd = "/home/qauser/jerome/qaRun.sh %s %s %s > %s" > cmdstr = cmd % (arg1,arg2,arg3,arg4) > print "=== Starting JUnit Run ===" > proc(cmdstr) > print "=== JUnit Run Complete ===" > > > #################### > ###### Main ###### > #################### > > setup() > run_junit() > > The setup() def seems to work great, but the > run_junit() seems to have problems. I believe due to > the params I'm passing. Here are the errors I'm > getting: > > [qauser at gary automation]$ ./runJunit.py > === Starting JUnit Run === > Traceback (most recent call last): > File "/home/qauser/automation/runJunit.py", line 63, > in ? > run_junit() > File "/home/qauser/automation/runJunit.py", line 54, > in run_junit > proc(cmdstr) > File "/home/qauser/automation/runJunit.py", line 18, > in proc > retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 412, in call > return Popen(*args, **kwargs).wait() > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 542, in __init__ > errread, errwrite) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 975, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I can't seem to figure out what file or directory is > missing. > > Your help is greatly appreciated, > Jerome > > __________________________________________________ > 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 jjabson at yahoo.com Wed May 10 19:18:41 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Wed, 10 May 2006 10:18:41 -0700 (PDT) Subject: [Tutor] help with erros using subprocess module Message-ID: <20060510171841.49719.qmail@web53715.mail.yahoo.com> Hi Bo, Jerome Jabson ??????: > Hi, > > I've been trying to write a wrapper around some shells > scripts using the subprocess module. But I'm getting > errors I quite don't know how to debug. I've only been > writing Python for a few months and starting processes > are new to me. Here's my code: > > import os > import re > import subprocess > > #################### > #### Definition #### > #################### > > def proc(cmd_in): > cmd = cmd_in > os.chdir("/home/qauser/jerome") > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + > repr(errData)) > > def setup(): > print "=== Starting Setup ===" > proc("/home/qauser/jerome/qaSetup.sh") > print "=== Setup Complete ===" > > def run_junit(): > file_in = > open("/home/qauser/automation/testdata/junit_master_file", > "r") > Could you put the contents in the junit_master_file here ? Are the first field in every line where the cmd name locates contain the full path to the command ? Here is the content of the junit_master_file: #################################################################### # This is the input file parameter for the JUnit test. Here is how # # the prameters are used: # # # # qaRun.sh # # # # There are 3 different test_type: # # netmap_perf # # threatmap_perf # # netmap_func # #################################################################### netmap_func,/home/qauser/junit/static_nat/simple_nat,10.1.1.0,172.16.200.0 Basically once I have this running there will be 100s of lines that map to the comma separated line. From the comments you can tell what the qaRun.sh script is looking for as far as params, and that's what this file is for. Thanks for your help! Jerome > match = re.compile('#+') > work_list = [] > for line in file_in: > work = line > work = work.rstrip('\n') > if match.search(work): > found = False > else: > found = True > if found == True: > work_list = work.split(',') > arg1 = work_list[0] > arg2 = work_list[1] > arg3 = work_list[2] > arg4 = work_list[3] > cmd = "/home/qauser/jerome/qaRun.sh %s %s %s > %s" > cmdstr = cmd % (arg1,arg2,arg3,arg4) > print "=== Starting JUnit Run ===" > proc(cmdstr) > print "=== JUnit Run Complete ===" > > > #################### > ###### Main ###### > #################### > > setup() > run_junit() > > The setup() def seems to work great, but the > run_junit() seems to have problems. I believe due to > the params I'm passing. Here are the errors I'm > getting: > > [qauser at gary automation]$ ./runJunit.py > === Starting JUnit Run === > Traceback (most recent call last): > File "/home/qauser/automation/runJunit.py", line 63, > in ? > run_junit() > File "/home/qauser/automation/runJunit.py", line 54, > in run_junit > proc(cmdstr) > File "/home/qauser/automation/runJunit.py", line 18, > in proc > retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 412, in call > return Popen(*args, **kwargs).wait() > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 542, in __init__ > errread, errwrite) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 975, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I can't seem to figure out what file or directory is > missing. > > Your help is greatly appreciated, > Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From philipasmith at blueyonder.co.uk Wed May 10 20:12:04 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Wed, 10 May 2006 19:12:04 +0100 Subject: [Tutor] Refactoring Message-ID: <005e01c6745d$3e352a50$16792d52@PANDORA> This is a subject which seems to pop up periodically so apoliogies but I wonder whether anyone can help: a) Is there yet an alternative Python refactoring tool to bicycle repair man (bike)? b) If not is there any documentation on the appropriate use of bike? I can't seem to get to grips with it unaided. Thanks much Phil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060510/dceed8be/attachment.htm From alan.gauld at freenet.co.uk Wed May 10 22:01:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 10 May 2006 21:01:04 +0100 Subject: [Tutor] How do I do cubic roots and cubic exponents (and higherroots and exponents) in Python? References: Message-ID: <003f01c6746c$783161b0$0c01a8c0@XPpro> > How do I do cubic (and higher) roots and exponents in Python? I > already took > a look in Python and didn't find anything. The nth root is just the number raised to the power of 1/n x = 27 n = 3 exp = 1/n cube_root = x**exp or if you prefer: def root(number, n): return number**(1/n) HTH, Alan G. Catching up on mail aftrer 2 days out... From wescpy at gmail.com Wed May 10 22:26:57 2006 From: wescpy at gmail.com (w chun) Date: Wed, 10 May 2006 13:26:57 -0700 Subject: [Tutor] For loop question In-Reply-To: <44620097.1090209@tds.net> References: <3B05FA2AD704244BB0CAB99D8026F555F42350@medexch2.medplus.com> <4461E2DC.7090802@tds.net> <78b3a9580605100759y3e98cde7ma8c21438d230c421@mail.gmail.com> <44620097.1090209@tds.net> Message-ID: <78b3a9580605101326l46f3e4dam11953f007c66dced@mail.gmail.com> > >> For short Python scripts I usually allow the runtime to close the file. > >> For longer programs and anything written in Jython (which has different > >> garbage collection behaviour) I usually use an explicit close(). > > > > i'm still not comfortable without doing my own explicit close(), esp. > > for writing to files... maybe i'm just used to malloc/new-free pairs > > like i am with open-close, although on the other hand, getting rid of > > another line of code is tempting -- so i will actually do this with a > > short piece of code that is read-only. > > Yes, for writing files I always use an explicit close(), thanks for the > correction! those of you who are going to be using 2.5 have this feature automated for you when using the new 'with' statement: when the 'with' clause (or suite) finishes, Python will automagically close() your file for you, read or write, so this is one case you can leave it out. for example: --- with open('log.txt', 'w') as f: : f.write(...) : # f is closed when we get here --- without going into the details of context managers here for objects to be used with the 'with' statement, let's just say that an __enter__() method is called before the block is executed, and an __exit__() method is called after the suite has completed. for file objects, file.__exit__ *is* file.close. (for the curious, this is implemented in Objects/fileobject.c if you've got the 2.5 source.) looking fwd, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Wed May 10 23:55:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 10 May 2006 14:55:41 -0700 (PDT) Subject: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying In-Reply-To: References: Message-ID: >> One of the major complaints that people have made about the "One Day of >> IDLE Toying" tutorial I've written is that the screenshots are badly >> outdated. >> >> http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ >> >> I was curious if anyone wanted to volunteer to provide fresh, updated >> Windows XP screenshots to replace the ones on the IDLE tutorial. > > Thanks everyone! I got some screenshots from Alan Gauld, and will > revise the main page later today with the updated images. Hi everyone, I have a preliminary version of the updated images here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/new/index-new.html It's going to replace the current page as soon as I just double check a few issues. But one thing that's missing is an image for selecting Python from the Windows XP Start menu. Can someone generate that for me? Thanks! From Smoove1162 at aol.com Thu May 11 02:58:10 2006 From: Smoove1162 at aol.com (Smoove1162 at aol.com) Date: Wed, 10 May 2006 20:58:10 EDT Subject: [Tutor] Crossword program Message-ID: <26c.a2f50fd.3193e622@aol.com> ok checking out crossword program how do i run this program -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060510/b6e7c243/attachment.html From Gideon.STREET at ergon.com.au Thu May 11 03:55:15 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Thu, 11 May 2006 11:55:15 +1000 Subject: [Tutor] For loop question Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9D@ebnewem01.ergon> Thanks all, appears it is the newline character which was causing me grief. For some reason I still have to do a readlines on the open file at this stage, but I can muck about with that to figure it out. Cheers -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Thursday, 11 May 2006 1:03 AM Cc: tutor at python.org Subject: Re: [Tutor] For loop question w chun wrote: > Kent Johnson wrote: >> For short Python scripts I usually allow the runtime to close the file. >> For longer programs and anything written in Jython (which has >> different garbage collection behaviour) I usually use an explicit close(). > > i'm still not comfortable without doing my own explicit close(), esp. > for writing to files... maybe i'm just used to malloc/new-free pairs > like i am with open-close, although on the other hand, getting rid of > another line of code is tempting -- so i will actually do this with a > short piece of code that is read-only. Yes, for writing files I always use an explicit close(), thanks for the correction! Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 From wescpy at gmail.com Thu May 11 05:10:56 2006 From: wescpy at gmail.com (w chun) Date: Wed, 10 May 2006 20:10:56 -0700 Subject: [Tutor] For loop question In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9D@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC87EF9D@ebnewem01.ergon> Message-ID: <78b3a9580605102010q5d6f5f7y1e71652062c00824@mail.gmail.com> > Thanks all, appears it is the newline character which was causing me > grief. For some reason I still have to do a readlines on the open file > at this stage, but I can muck about with that to figure it out. that is surprising... i would be interested in hearing what problems you are encountering while iterating through a file. if you have any output or problem description to share with us, that would be great. what version of Python are you running? cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at alum.rpi.edu Thu May 11 05:15:09 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 10 May 2006 20:15:09 -0700 Subject: [Tutor] Crossword program In-Reply-To: <26c.a2f50fd.3193e622@aol.com> References: <26c.a2f50fd.3193e622@aol.com> Message-ID: <4462AC3D.9020003@alum.rpi.edu> Smoove1162 at aol.com wrote: > ok checking out crossword program how do i run this program Sorry but that is not enough information for us to act on. What "crossword program"? From Gideon.STREET at ergon.com.au Thu May 11 06:51:01 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Thu, 11 May 2006 14:51:01 +1000 Subject: [Tutor] For loop question Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC0A2583@ebnewem01.ergon> I'm running version 2.4.2 Just set up another test file and it's working with: HostFile = open("hosts.txt", 'r') for item in (x.strip() for x in HostFile): print "Connecting to device",item ..telnet and do other stuff here... I must have typed something incorrectly previously :\ Thanks again Gideon (aka Fatfingers) -----Original Message----- From: w chun [mailto:wescpy at gmail.com] Sent: Thursday, 11 May 2006 1:11 PM To: STREET Gideon (SPARQ) Cc: tutor at python.org Subject: Re: [Tutor] For loop question > Thanks all, appears it is the newline character which was causing me > grief. For some reason I still have to do a readlines on the open > file at this stage, but I can muck about with that to figure it out. that is surprising... i would be interested in hearing what problems you are encountering while iterating through a file. if you have any output or problem description to share with us, that would be great. what version of Python are you running? cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 From alan.gauld at freenet.co.uk Thu May 11 10:29:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 11 May 2006 09:29:42 +0100 Subject: [Tutor] Big mistake in my tutor Message-ID: <000301c674d5$0dc79ec0$0c01a8c0@XPpro> A reader has just pointed out that there are some very bad mistakes in my database topic. Having reviewed the code in question I obviously never tested it as it is completely wrong and even invalid syntax in one case! Dunno what happened there, too many late nights and whiskys maybe... Anyhow, I'll fix it this weekend, in the meantime, profuse apologies to anyone struggling with the SQL code in the database topic. In particular the pure SQL addressbook and author/book examples - the python example works ok ironically! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From shivayogiks at gmail.com Thu May 11 12:18:28 2006 From: shivayogiks at gmail.com (shivayogi kumbar) Date: Thu, 11 May 2006 15:48:28 +0530 Subject: [Tutor] Fwd: eclipseplugin for python In-Reply-To: <6434a4300605110310k66631abbg4b4a9efa3bb75b98@mail.gmail.com> References: <6434a4300605110310k66631abbg4b4a9efa3bb75b98@mail.gmail.com> Message-ID: <6434a4300605110318p222160a3kefb2ecb6b7fa2a3a@mail.gmail.com> I downloaded python plugin for eclipse by directly downloading zip file and extracting under eclipse folder; because it could not update via PROXY. It was suggested to update plugins from eclipse IDE only. I am unable to use that plugin(Python) in eclipse. Is it a problem of proxy or any other? I want to know how to configure eclipse to adapt to python. Let me know latest version of eclipse and python plugin. Thanks. -- regards Shiv -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060511/fdff6626/attachment.htm From mwhite3 at ttsd.k12.or.us Wed May 10 18:59:14 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 10 May 2006 09:59:14 -0700 Subject: [Tutor] ossaudiodev, pygtk, and flushing buffers Message-ID: <20060510165914.GC18249@rothko.ttsd.k12.or.us> Hello All, I'm writing a little audio player that plays voicemail files. (I realize I'm reinventing the wheel, but it's still fun.) The problem I'm experiencing is that I'm hearing the last fraction of the sound clip twice, either when the clip is done playing or when the program exits. I've tried a few things and none of them have worked. The bit of code that does the playing is here: def play(self): if self.data_written < self.file_length: buf = self.data.read(self.buf_size) self.data_written += self.dsp.write(buf) self.percent_done = self.data_written / self.file_length if self.data_written == self.file_length: self._reopen_audio_device() This causes the second playing of the "last little bit" when the end of the file is reached. When I don't include the second if statement, the "last little bit" gets played when the program exits. According to the documentaiton, closing the audio device will flush any data in the sound card buffer. I guess what I'm hearing is that buffered clip being flushed. I've thought about using the mixer device to put the volume to zero, flush the buffer, then turning the volume back up again, but that seems like a hack. If anyone decides to use this program, you'll need to use a .wav file and change the value of self.sample_rate in vmPlayer.py from 8000 to 44100 (or whatever rate your file is encoded in) (Also, I plan on auto-detecting the sample rate in the future. I hard coded 8000 because that's the rate the voice mail system uses.) See attached files for the code. -mtw -------------- next part -------------- A non-text attachment was scrubbed... Name: player_py.RENAMED_BY_TTSD-0 Type: application/renamed_by_ttsd-0 Size: 1770 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060510/62d453bd/attachment.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: vmPlayer_py.RENAMED_BY_TTSD-2 Type: application/renamed_by_ttsd-2 Size: 1216 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060510/62d453bd/attachment-0001.bin From klappnase at freenet.de Thu May 11 19:15:52 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 11 May 2006 19:15:52 +0200 Subject: [Tutor] ossaudiodev, pygtk, and flushing buffers In-Reply-To: <20060510165914.GC18249@rothko.ttsd.k12.or.us> References: <20060510165914.GC18249@rothko.ttsd.k12.or.us> Message-ID: <20060511191552.593fa91c.klappnase@freenet.de> On Wed, 10 May 2006 09:59:14 -0700 Matthew White wrote: > Hello All, > > I'm writing a little audio player that plays voicemail files. (I realize > I'm reinventing the wheel, but it's still fun.) > > The problem I'm experiencing is that I'm hearing the last fraction of > the sound clip twice, either when the clip is done playing or when the > program exits. > > I've tried a few things and none of them have worked. The bit of code > that does the playing is here: > > def play(self): > if self.data_written < self.file_length: > buf = self.data.read(self.buf_size) > self.data_written += self.dsp.write(buf) > self.percent_done = self.data_written / self.file_length > > if self.data_written == self.file_length: > self._reopen_audio_device() > > This causes the second playing of the "last little bit" when the end of > the file is reached. When I don't include the second if statement, the > "last little bit" gets played when the program exits. > > According to the documentaiton, closing the audio device will flush any > data in the sound card buffer. I guess what I'm hearing is that buffered > clip being flushed. I've thought about using the mixer device to put the > volume to zero, flush the buffer, then turning the volume back up again, > but that seems like a hack. > Hi Matthew, you never explicitely close the audio device, except when calling self._reopen_audio_device(). According to the OSS programmer's guide (http://www.opensound.com/pguide/index.html ) this is generally considered bad practice, because no other application will be able to access the audio device. Probably it is not guaranteed that the device's buffers will be flushed until calling close(), too (maybe calling reset() also flushes the buffers, but after reset() you should close and reopen the device anyway). I have not tried it, but I think the effect you describe may depend on the driver in use. Does it help if you change your play() method like this: def play(self): if self.data_written < self.file_length: buf = self.data.read(self.buf_size) self.data_written += self.dsp.write(buf) self.percent_done = self.data_written / self.file_length if self.data_written == self.file_length: self.dsp.close() # then reopen the device right before starting playback, probably from player.PlayerWindow.play() ? There may be a short delay between the call to self.dsp.close() and the actual stopping of playback, (which can be avoided by calling self.dsp.reset() before self.dsp.close()), however this should not be a problem if you play the file to the end, I think. I hope this helps Michael From jjabson at yahoo.com Thu May 11 19:59:19 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Thu, 11 May 2006 10:59:19 -0700 (PDT) Subject: [Tutor] help with erros using subprocess module In-Reply-To: <44648126.1090302@gmail.com> Message-ID: <20060511175919.15972.qmail@web53713.mail.yahoo.com> Hi Bo, Thank you very much for all your help!! But I'm having some problems with the line of code you recommended: if isinstance(cmd, types.StringTypes): cmd = cmd.split(' ') I'm getting the following error: NameError: global name 'types' is not defined As you instructed, I put in the beginning of the functon proc: def proc(cmd_in): cmd = cmd_in if isinstance(cmd, types.StringTypes): cmd = cmd.split(' ') os.chdir("/home/qauser/jerome") outFile = os.path.join(os.curdir, "output.log") outptr = file(outFile, "w") errFile = os.path.join(os.curdir, "error.log") errptr = file(errFile, "w") retval = subprocess.call(cmd, 0, None, None, outptr, errptr) errptr.close() outptr.close() if not retval == 0: errptr = file(errFile, "r") errData = errptr.read() errptr.close() raise Exception("Error executing command: " + repr(errData)) Am I missing some module you are referencing with "types"? Thanks again, Jerome >I think I find what is wrong here ! > >First , I run the program in windows , and it execute >well without any >error and execption . >Second , I run it in Linux and the error you provide >occured . > >And then I debug the script in Linux , and found that >below : >The subprocess.call method pass its arguments to the >Popen object and >then the later fork the process , in the python >library reference I >found that : > >args should be a string, or a sequence of program >arguments. The >program >to execute is normally the first item in the args >sequence or string, >but can be explicitly set by using the executable >argument. > > >If the first argument is a string , then the Popen >class assume it is >only the command without arguments , and if the first >argument is a >sequence , the Popen class >assume that the first elment in the sequence is a >command name and >others else are arguments for the command . >So , if you want to pass arguments to your shell , you >must pass the >call method a sequence instead of a command . >I add a clause in the begin of the function proc : > >if isinstance( cmd , types.StringTypes): >cmd = cmd.split(' ') > >and everything is OK ! > >And I also there is a function called >list2cmdline(args) , which will >be >called in the windows version of Popen , and it is >this function make >the program through in windows with no error . __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From nospamformeSVP at gmail.com Thu May 11 20:17:12 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Thu, 11 May 2006 14:17:12 -0400 Subject: [Tutor] Refactoring In-Reply-To: <005e01c6745d$3e352a50$16792d52@PANDORA> References: <005e01c6745d$3e352a50$16792d52@PANDORA> Message-ID: Philip Smith wrote: > This is a subject which seems to pop up periodically so apoliogies but I > wonder whether anyone can help: > > a) Is there yet an alternative Python refactoring tool to bicycle > repair man (bike)? > Find and Replace ;-) > b) If not is there any documentation on the appropriate use of bike? > I can't seem to get to grips with it unaided. > BRM is nicely integrated into Eclipse/Pydev but BRM itself is incomplete and brittle, I only trust it to make changes in the current module. There does not seem to be any prospect of an update to BRM any time soon. Don. From nospamformeSVP at gmail.com Thu May 11 20:33:47 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Thu, 11 May 2006 14:33:47 -0400 Subject: [Tutor] Fwd: eclipseplugin for python In-Reply-To: <6434a4300605110318p222160a3kefb2ecb6b7fa2a3a@mail.gmail.com> References: <6434a4300605110310k66631abbg4b4a9efa3bb75b98@mail.gmail.com> <6434a4300605110318p222160a3kefb2ecb6b7fa2a3a@mail.gmail.com> Message-ID: shivayogi kumbar wrote: > > > I downloaded python plugin for eclipse by directly downloading zip file > and extracting under eclipse folder; because it could not update via > PROXY. It was suggested to update plugins from eclipse IDE only. I am > unable to use that plugin(Python) in eclipse. Is it a problem of proxy > or any other? I want to know how to configure eclipse to adapt to python. > Let me know latest version of eclipse and python plugin. > Thanks. > I don't know about your proxy question - that sounds like a question for the Eclipse folks. I have installed the Pydev from the .zip file and as long you have unpacked it and moved the contents into the correct folders under Eclipse then it should work fine. Read this and follow it carefully and you should be OK: http://www.fabioz.com/pydev/manual_101_install.html The .zip install procedure is about halfway down. If you still have problems then try asking Fabio Zadrozny on the Pydev user list. He is always very helpful. http://sourceforge.net/forum/forum.php?forum_id=293649 or pydev-users at lists.sourceforge.net Don. From zubinw at zapdomain.ca Thu May 11 21:03:53 2006 From: zubinw at zapdomain.ca (Zubin Wadia) Date: Thu, 11 May 2006 15:03:53 -0400 (EDT) Subject: [Tutor] laying out a menu widget inside a frame Message-ID: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> Hello All, from Tkinter import * class App: #create a frame def __init__(self, master): frame = Frame(master, bg="LIGHTBLUE", relief=RIDGE, bd=3) frame.pack(side=TOP, ipadx=15, ipady=15, fill=X) ##create dropdown menu menubar = Menu(frame) filemenu = Menu(menubar) menubar.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New") root.config(menu=menubar) ##edit root = Tk() root.minsize(100,100) app = App(root) root.mainloop() This works great but I can't get the dropdown menu to layout in the frame widget instead of the root. I tried frame.config() in the ##edit line but I don't think there is a config method for the frame widget, it errors out. Any pointers? thanks in advance, --zubin From mwhite3 at ttsd.k12.or.us Thu May 11 22:33:05 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Thu, 11 May 2006 13:33:05 -0700 Subject: [Tutor] ossaudiodev, pygtk, and flushing buffers In-Reply-To: <20060511191552.593fa91c.klappnase@freenet.de> References: <20060510165914.GC18249@rothko.ttsd.k12.or.us> <20060511191552.593fa91c.klappnase@freenet.de> Message-ID: <20060511203304.GW18249@rothko.ttsd.k12.or.us> Michael, Calling .reset() did the trick. The code now waits for the user to press play before opening the audio device and closes it when paused or EOF is reached. Thanks for your help! -mtw On Thu, May 11, 2006 at 07:15:52PM +0200, Michael Lange (klappnase at freenet.de) wrote: > On Wed, 10 May 2006 09:59:14 -0700 > Matthew White wrote: > > > Hello All, > > > > I'm writing a little audio player that plays voicemail files. (I realize > > I'm reinventing the wheel, but it's still fun.) > > > > The problem I'm experiencing is that I'm hearing the last fraction of > > the sound clip twice, either when the clip is done playing or when the > > program exits. > > > > I've tried a few things and none of them have worked. The bit of code > > that does the playing is here: > > > > def play(self): > > if self.data_written < self.file_length: > > buf = self.data.read(self.buf_size) > > self.data_written += self.dsp.write(buf) > > self.percent_done = self.data_written / self.file_length > > > > if self.data_written == self.file_length: > > self._reopen_audio_device() > > > > This causes the second playing of the "last little bit" when the end of > > the file is reached. When I don't include the second if statement, the > > "last little bit" gets played when the program exits. > > > > According to the documentaiton, closing the audio device will flush any > > data in the sound card buffer. I guess what I'm hearing is that buffered > > clip being flushed. I've thought about using the mixer device to put the > > volume to zero, flush the buffer, then turning the volume back up again, > > but that seems like a hack. > > > > Hi Matthew, > > you never explicitely close the audio device, except when calling self._reopen_audio_device(). > According to the OSS programmer's guide (http://www.opensound.com/pguide/index.html ) this is generally considered bad practice, > because no other application will be able to access the audio device. Probably it is not guaranteed that the device's > buffers will be flushed until calling close(), too (maybe calling reset() also flushes the buffers, but after reset() you > should close and reopen the device anyway). > I have not tried it, but I think the effect you describe may depend on the driver in use. > > Does it help if you change your play() method like this: > > def play(self): > if self.data_written < self.file_length: > buf = self.data.read(self.buf_size) > self.data_written += self.dsp.write(buf) > self.percent_done = self.data_written / self.file_length > if self.data_written == self.file_length: > self.dsp.close() > # then reopen the device right before starting playback, probably from player.PlayerWindow.play() > > ? > > There may be a short delay between the call to self.dsp.close() and the actual stopping of playback, > (which can be avoided by calling self.dsp.reset() before self.dsp.close()), however this should not be a problem if you > play the file to the end, I think. > > I hope this helps > > Michael > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fiveholiday55 at hotmail.com Fri May 12 01:44:12 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Fri, 12 May 2006 00:44:12 +0100 Subject: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying References: Message-ID: Hello guys, I have sent the screen shot of the IDLE being selected from Windows XP start menu to Danny, incase someone is making another screen shot. Lets wait till he requests another one. Evans ----- Original Message ----- From: "Danny Yoo" To: "Tutor" Sent: Wednesday, May 10, 2006 10:55 PM Subject: Re: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying >>> One of the major complaints that people have made about the "One Day of >>> IDLE Toying" tutorial I've written is that the screenshots are badly >>> outdated. >>> >>> http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ >>> >>> I was curious if anyone wanted to volunteer to provide fresh, updated >>> Windows XP screenshots to replace the ones on the IDLE tutorial. >> >> Thanks everyone! I got some screenshots from Alan Gauld, and will >> revise the main page later today with the updated images. > > Hi everyone, > > I have a preliminary version of the updated images here: > > > http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/new/index-new.html > > It's going to replace the current page as soon as I just double check a > few issues. But one thing that's missing is an image for selecting Python > from the Windows XP Start menu. Can someone generate that for me? > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri May 12 02:33:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 11 May 2006 17:33:44 -0700 (PDT) Subject: [Tutor] Call for volunteer to help revise images for One Day of IDLE Toying In-Reply-To: References: Message-ID: > I have sent the screen shot of the IDLE being selected from Windows XP start > menu to Danny, incase someone is making another screen shot. Lets wait till > he requests another one. Thank you Alan and Evans! I've updated with those screenshots, and added a small cosmetic change to refer to Python 2.4-specific stuff. The new page is at: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ I've left the old page at: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/old/ just in case anyone misses it. *grin* From jramakrishnan at neuropace.com Fri May 12 02:38:30 2006 From: jramakrishnan at neuropace.com (Janesh Ramakrishnan) Date: Thu, 11 May 2006 17:38:30 -0700 Subject: [Tutor] Beep Beep sound sometimes while running PythonWin (Python 2.1) Message-ID: <405EDF2FA0855E43B27EA6DAFA1C78CEE66DAF@laguna.neuropace.com> Hi Folks: Has anyone of you experienced this beep - beep sound from the deskstation CPU when Python crashes? It apparently has happened a few times when I was running some .py scripts in PythonWin. The scripts do not play any audio files. I then have to reboot the CPU to get the system up and running again. Would appreciate any input you may have on this issue. Thanks. J.Ramakrishnan From Barry.Carroll at psc.com Fri May 12 02:50:22 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 11 May 2006 17:50:22 -0700 Subject: [Tutor] selecting and ordering file names on a remote machine Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3692@eugsrv400.psc.pscnet.com> Greetings: I'm adding a new page to our test system's browser based UI. This page implements the process of sending one more barcode 'images' to the system for decoding by the unit under test. Each 'image' is in a file in a known directory on the test system. The file(s) to be presented, and the order of their presentation, are selected by the user via the web page. There are other fields on the page, including a button to start the presentation, but I know how to implement those features. It's the selecting and ordering of the files I find challenging. Essentially, page must do the following: 1. present the files in the directory to the user as some sort of list from which multiple names can be selected, 2. present the selected file names in the order in which they were selected, 3. allow the user to add additional names, remove existing names and change their order at will. I've seen dialog boxes in GUI based programs that do this sort of things. Is there a widget or recipe extant that does this on a web page? I've looked in the "Python Cookbook" and the recipe pages on aspn.activestate.com. I didn't see anything promising. Any ideas? My site is currently hand-built: no web application framework in use. But, if there is a lightweight framework out there that has this functionality I'd be happy to use it, if it doesn't take months to install, configure and become proficient in. As always, thanks for your help. Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Fri May 12 06:17:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 May 2006 00:17:14 -0400 Subject: [Tutor] selecting and ordering file names on a remote machine In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3692@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3692@eugsrv400.psc.pscnet.com> Message-ID: <44640C4A.2080300@tds.net> Carroll, Barry wrote: > Greetings: > > Essentially, page must do the following: > > 1. present the files in the directory to the user as some sort > of list from which multiple names can be selected, > 2. present the selected file names in the order in which they > were selected, > 3. allow the user to add additional names, remove existing names > and change their order at will. > > I've seen dialog boxes in GUI based programs that do this sort of > things. Is there a widget or recipe extant that does this on a web > page? I've looked in the "Python Cookbook" and the recipe pages on > aspn.activestate.com. I didn't see anything promising. Any ideas? Sounds like a good time to learn some AJAX. Something like this? http://wiki.script.aculo.us/scriptaculous/show/SortableListsDemo To do this on a web page you need to use JavaScript, not Python. It's not too hard to write the classic list-on-the-left, move left button, move right button, list-on-the-right. But these days you can do much fancier stuff such as the link above. Kent From klappnase at freenet.de Fri May 12 09:30:34 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 12 May 2006 09:30:34 +0200 Subject: [Tutor] help with erros using subprocess module In-Reply-To: <20060511175919.15972.qmail@web53713.mail.yahoo.com> References: <44648126.1090302@gmail.com> <20060511175919.15972.qmail@web53713.mail.yahoo.com> Message-ID: <20060512093034.70425f02.klappnase@freenet.de> On Thu, 11 May 2006 10:59:19 -0700 (PDT) Jerome Jabson wrote: > > Am I missing some module you are referencing with > "types"? > Hi Jerome, that's right, try import types first. Michael From klappnase at freenet.de Fri May 12 09:41:24 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 12 May 2006 09:41:24 +0200 Subject: [Tutor] laying out a menu widget inside a frame In-Reply-To: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> Message-ID: <20060512094124.56ca7c7b.klappnase@freenet.de> On Thu, 11 May 2006 15:03:53 -0400 (EDT) "Zubin Wadia" wrote: > Hello All, > > from Tkinter import * > > class App: > #create a frame > def __init__(self, master): > frame = Frame(master, bg="LIGHTBLUE", relief=RIDGE, bd=3) > frame.pack(side=TOP, ipadx=15, ipady=15, fill=X) > > ##create dropdown menu > > menubar = Menu(frame) > > filemenu = Menu(menubar) > menubar.add_cascade(label="File", menu=filemenu) > filemenu.add_command(label="New") > > root.config(menu=menubar) ##edit > > root = Tk() > root.minsize(100,100) > app = App(root) > root.mainloop() > > This works great but I can't get the dropdown menu to layout in the frame > widget instead of the root. I tried frame.config() in the ##edit line but > I don't think there is a config method for the frame widget, it errors > out. > Hi Zubin, there is a typo in your code, it should be master.config(menu=menubar) but this does not seem to be your problem? If you just want the menu to be inside the "lightblue", "RIDGE" part of the window, try: root.config(relief=RIDGE, bg="lightblue", bd=3) and relief="flat", bg="lightblue" on the frame. I hope this helps Michael From Barry.Carroll at psc.com Fri May 12 20:51:01 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 12 May 2006 11:51:01 -0700 Subject: [Tutor] selecting and ordering file names on a remote machine Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3695@eugsrv400.psc.pscnet.com> Kent: <> > > > > Essentially, page must do the following: > > > > 1. present the files in the directory to the user as some sort > > of list from which multiple names can be selected, > > 2. present the selected file names in the order in which they > > were selected, > > 3. allow the user to add additional names, remove existing names > > and change their order at will. > > > <> > > Sounds like a good time to learn some AJAX. Something like this? > http://wiki.script.aculo.us/scriptaculous/show/SortableListsDemo > > To do this on a web page you need to use JavaScript, not Python. It's > not too hard to write the classic list-on-the-left, move left button, > move right button, list-on-the-right. But these days you can do much > fancier stuff such as the link above. > > Kent > Yes, something like that would be great. I've been reading an AJAX text for awhile. I guess now's a good time to start applying it. =8^) Thank you for the tips. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From fiveholiday55 at hotmail.com Fri May 12 22:24:25 2006 From: fiveholiday55 at hotmail.com (Henry Dominik) Date: Fri, 12 May 2006 21:24:25 +0100 Subject: [Tutor] Runing a Python program Message-ID: Hello people, As a new python programmer, I created a directory in 'C:\python24\myPythonFiles', and added a simple python under the myPythonFiles directory; but when I tried running it on the Python Shell, I got the following error. >>> import myPythonFiles.readOut Traceback (most recent call last): File "", line 1, in -toplevel- import mypythonFiles.readOut ImportError: No module named myPythonFiles.readOut >>> How do I run a program that is placed on its own folder/directory? Thanks Henry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060512/01cb6e5f/attachment.htm From fiveholiday55 at hotmail.com Sat May 13 13:55:08 2006 From: fiveholiday55 at hotmail.com (Evans Anyokwu) Date: Sat, 13 May 2006 12:55:08 +0100 Subject: [Tutor] Runing a Python program References: Message-ID: There's a simple way you can add your directory to the execution path. try this >>> sys.path.append(r'C:\python24\myPythonFiles') now, you can import your file with the import command >>> import yourFile Note: This is only a temporary solution, when you close the interpreter, it will need to be appended again. Hope that help. ----- Original Message ----- From: Henry Dominik To: Tutor Sent: Friday, May 12, 2006 9:24 PM Subject: [Tutor] Runing a Python program Hello people, As a new python programmer, I created a directory in 'C:\python24\myPythonFiles', and added a simple python under the myPythonFiles directory; but when I tried running it on the Python Shell, I got the following error. >>> import myPythonFiles.readOut Traceback (most recent call last): File "", line 1, in -toplevel- import mypythonFiles.readOut ImportError: No module named myPythonFiles.readOut >>> How do I run a program that is placed on its own folder/directory? Thanks Henry ------------------------------------------------------------------------------ _______________________________________________ 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/20060513/62038016/attachment.htm From kent37 at tds.net Sat May 13 14:51:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 May 2006 08:51:57 -0400 Subject: [Tutor] Runing a Python program In-Reply-To: References: Message-ID: <4465D66D.2080508@tds.net> Henry Dominik wrote: > Hello people, > > As a new python programmer, I created a directory in > 'C:\python24\myPythonFiles', > and added a simple python under the myPythonFiles directory; but when I > tried running it on the Python Shell, I got the following error. > > >>> import myPythonFiles.readOut To be able to import a module, the directory containing the module must be in sys.path. sys.path is just a list of directory paths. The Python runtime searches each of these directories for your module. So one thing you can do is make sure your module is in a directory that is in sys.path. A couple of possibilities are the current working directory and the site-packages directory. On my computer (Win2K) Python puts the current working directory in sys.path. (I'm not sure this happens on Linux.) You can see this if you print sys.path; it is the empty string that starts the list. So I often cd to the directory containing a program before starting Python. Then I can import modules from that directory. For modules you want to be able to use from several programs, you can put them in C:\Python24\Lib\site-packages. This directory is always added to sys.path and it is intended as a place to install extra modules and packages. Most third-party modules will install to site-packages. Alternately you can modify sys.path to include the dir you want. There are several ways to do this. One way, as Evans showed, is to change it at runtime by appending a new path. This is fine for temporary changes but not very convenient in the long run. Another possibility is to edit the environment variable PYTHONPATH and add your dir to it. You can also create a .pth file in site-packages that contains the path to the dir to add to sys.path. You can find more info here: http://docs.python.org/tut/node8.html#SECTION008110000000000000000 http://docs.python.org/lib/module-site.html Kent From alan.gauld at freenet.co.uk Sat May 13 15:58:50 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 13 May 2006 14:58:50 +0100 Subject: [Tutor] Runing a Python program References: Message-ID: <003601c67695$5cc5cf30$0c01a8c0@XPpro> Hi Henry, > As a new python programmer, I created a directory in > 'C:\python24\myPythonFiles', and added a simple python > under the myPythonFiles directory; but when I tried > running it on the Python Shell, I got the following error. > >>> import myPythonFiles.readOut > ImportError: No module named myPythonFiles.readOut Ok, the first thing to say is that you are not running the program but importing it, there is a difference. To run a Python program in Windows either double click it in Windows Explorer (it should have a snake icon to show that the association is set up correctly) or at a DOS command prompt (or the Start->Run dialog) type C:\> python C:\python24\myPythonFiles\readOut.py In either case you may find the program runs so fast you can't see the output. In that case add a final line like: raw_input("Hit ENTER to quit") When you import a module it does indeed execute the code in that module and so might appear to run the program, but there is one important distinction (which you may not have come across yet!) You can put a clause into the module like: if __name__ == "__main__": # some code here and the code under the if will only be executed when the file is run as a program, it will NOT be executed when the file is imported as a module. (This is a powerful feature that greatly eases the task of writing reusable code in Python.) Now the second thing to note is that your import syntax is wrong. To make the files in your directory visible toi the import command you need to modify the value in sys.path. There are a number of ways to do this, the one that I use is to create a PYTHONPATH environment variable (MyComputer->Properties->Advanced->Environment Variables) which points to all the folders where I keep Python code, in the same way that the DOS PATH variable points to my executable files. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat May 13 16:04:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 13 May 2006 15:04:58 +0100 Subject: [Tutor] Database topic now fixed Message-ID: <003c01c67696$3808a360$0c01a8c0@XPpro> The mistakes in my databae topic have now been rectified. I have no idea how I managed to post the file without testing that section of code. And unfortunately it's one of the areas where SqlLite SQL syntax varies from the Oracle syntax that I'm most familiar with. But that's only a partial excuse since my code wasn't actually valid Oracle code either, it was just wrong! Hopefully all errors are now removed apologies once again, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Sat May 13 20:23:06 2006 From: wescpy at gmail.com (w chun) Date: Sat, 13 May 2006 11:23:06 -0700 Subject: [Tutor] Runing a Python program In-Reply-To: <4465D66D.2080508@tds.net> References: <4465D66D.2080508@tds.net> Message-ID: <78b3a9580605131123y22c42c27v2a5863e1b92cc14d@mail.gmail.com> > On my computer (Win2K) Python puts the current working directory in > sys.path. (I'm not sure this happens on Linux.) yes it does, on any unix-flavored system (Linux, FreeBSD, MacOS X, Solaris, etc.). since we're on the topic, there is another attribute in the sys module, sys.modules that shows you all the imported (and loaded) modules and where they live in the filesystem. it's a good way to figure out path problems too. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at alum.rpi.edu Sat May 13 21:54:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 13 May 2006 12:54:56 -0700 Subject: [Tutor] Database topic now fixed In-Reply-To: <003c01c67696$3808a360$0c01a8c0@XPpro> References: <003c01c67696$3808a360$0c01a8c0@XPpro> Message-ID: <44663990.4030804@alum.rpi.edu> Alan Gauld wrote: > The mistakes in my databae topic have now been rectified. > I have no idea how I managed to post the file without testing > that section of code. And unfortunately it's one of the areas > where SqlLite SQL syntax varies from the Oracle syntax that > I'm most familiar with. But that's only a partial excuse since > my code wasn't actually valid Oracle code either, it was just > wrong! > > Hopefully all errors are now removed This is my first reading of that topic. Thank you for all the effort you put into this, as well as your willingness to admit and fix problems. If only Microsoft had that attitude. Some observations: 1 - people familiar with other databases might be puzzled by the lack of column datatypes. I'd mention that sqlite allows but does not require types at the first introduction of CREATE TABLE,. 2 - The introduction of NULL: "NOT NULL is self explanatory, it indicates that the value must exist and not be NULL." To someone completely new to SQL this is IMHO not self explanatory. This is the first appearance of "NULL" in the tutorial, and I deem a little explanation would help. Perhaps a definition of NULL then an INSERT statement that does not cover all columns, showing what happens when a NULL column is omitted and then the result of a SELECT, then showing what happens when a NOT NULL column is omitted (Error). 3 - "UNIQUE means that the value must be unique within the table. If it is not, an error results and the row will not be inserted." This is slightly confusing (and not totally true "unique within the table" really is within the column). I'd reword it something like "an insert statement that would put a value in a unique column that is already in that column will raise an error and not insert a row" 4 - introducing WHERE. I'd first show it as WHERE x = y and then introduce the table prefix. 5 - following the explanation of UNIQUE under constraints, please also explain DEFAULT. 6- the table structure in Address Book Revised looks like it is for UK addresses. Consider saying this. Also consider a structure that would accommodate US/Canadian address also. 7 - "SELECT First,Last, Phone FROM Address WHERE First Like Dav%;" Shouldn't Dav% be in quotes? HTH From alan.gauld at freenet.co.uk Sat May 13 22:35:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 13 May 2006 21:35:23 +0100 Subject: [Tutor] Database topic now fixed References: <003c01c67696$3808a360$0c01a8c0@XPpro> <44663990.4030804@alum.rpi.edu> Message-ID: <004001c676cc$c2d73ed0$0c01a8c0@XPpro> Thanks Bob, Feedback is always appreciated, its how the tutor improves. > 1 - people familiar with other databases might be puzzled by the > lack of column datatypes. I'd mention that sqlite allows but does > not require types at the first introduction of CREATE TABLE,. Fair point, although by definition my tutor is aimed at absolute novices so they are less likely to know about SQL. But I will make a comment. > 2 - The introduction of NULL: "NOT NULL is self explanatory, it > indicates that the value must exist and not be NULL." Oops, self referencing definitions are never good (unless its GNU) I'll fix that one. > > 3 - "UNIQUE means that the value must be unique within the table. > > If it > slightly confusing (and not totally true "unique within the table" > really is within the column). Quite right, I'll clarify it. > 4 - introducing WHERE. I'd first show it as WHERE x = y and then > introduce the table prefix. My general style in the tutor is to teach the most general case first then introduce the shortcuts. Fully specified names will never go wrong but shortened names can cause confusion in my experience. So for this one I'lll stick with the long way first then introduce the shoirter form. > 5 - following the explanation of UNIQUE under constraints, please > also explain DEFAULT. Fair point. > 6- the table structure in Address Book Revised looks like it is for > UK addresses. Consider saying this. Also consider a structure that > would accommodate US/Canadian address also. Erm, What is the difference exactly? > 7 - "SELECT First,Last, Phone FROM Address WHERE First Like Dav%;" > Shouldn't Dav% be in quotes? Oops yes, it is in my actual code but they have been dropped in the editing somewhere. Oh well, not quite as faultless as I hoped but better than it was! :-) Thanks for the feedback Bob, I'll incorporate most of it in the next upload. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From clsdaniel at gmail.com Sat May 13 22:50:43 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Sat, 13 May 2006 13:50:43 -0700 Subject: [Tutor] Spanish Tutorials Message-ID: <4fae7dfa0605131350g1dc30af6s40fc80db945b31af@mail.gmail.com> Hello! At my university we are creating a Wiki with information about the careers and articles, one of the most important section is the Systems Engineering, which sports a Python section :) Spanish Python Tutorials at: http://wikitec.itnogales.edu.mx/index.php/Python Saludos! From john.corry at ntlworld.com Sat May 13 23:37:06 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 13 May 2006 22:37:06 +0100 Subject: [Tutor] Problems with Treeview Message-ID: <000001c676d5$6760da30$4a3ea8c0@JOHNC> Hi, I am having problems selecting a row in treeview. I am using Pythoncard, Glade 2 and Python 2.4. I am using the following code:- combo3 = self.wTree.get_widget("treeview1") model=gtk.TreeStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE _STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobj ect.TYPE_STRING,gobject.TYPE_STRING) self.hostsmodel = model combo3.set_model(model) combo3.connect("row_activated", self.callback53, combo3,model) def callback53(self,data,combo3,data2,data3,model): view = gtk.TreeView(model) selection = view.get_selection().get_selected() print selection result = model.get_value(iter,0) print result I get the following error: (, None) Traceback (most recent call last): File "C:\Documents and Settings\Johnc\Projects\project7\shopcall.py", line 1 , in callback53 result = model.get_value(iter,0) TypeError: iter must be a GtkTreeIter What do I need to assign to iter to make this code work? Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060513/66ba974a/attachment.htm From falcon3166 at hotmail.com Sun May 14 00:48:50 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 13 May 2006 16:48:50 -0600 Subject: [Tutor] How do I create the equivalent of a Java class in Python? Message-ID: Hey all, How do I create the equivalent of a Java class in Python? I've been looking at the reference, and it's been confusing to me at least. Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060513/1410adb1/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060513/1410adb1/attachment.gif From alan.gauld at freenet.co.uk Sun May 14 01:00:50 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 14 May 2006 00:00:50 +0100 Subject: [Tutor] Database topic now fixed References: <003c01c67696$3808a360$0c01a8c0@XPpro> <44663990.4030804@alum.rpi.edu> Message-ID: <005d01c676e1$14508be0$0c01a8c0@XPpro> > Some observations: These have now all been addressed as previously discussed. I've also added a section at the end covering the use of execute() to insert parameters rather than relying on format strings since the latter can be a security risk. Hopefully its now complete! :-) Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Sun May 14 07:53:37 2006 From: wescpy at gmail.com (w chun) Date: Sat, 13 May 2006 22:53:37 -0700 Subject: [Tutor] How do I create the equivalent of a Java class in Python? In-Reply-To: References: Message-ID: <78b3a9580605132253j1ef3e0d9u1634d5c9faf4e123@mail.gmail.com> > How do I create the equivalent of a Java class in Python? I've been looking > at the reference, and it's been confusing to me at least. can you clarify what you are looking for? do you want to create a class using Python, create the equivalent of a Java class using Python via Jython, accessing a preexisting Java class from Python, or what? you cannot simply write Java code in Python, but Python classes do get turned into Java classes under the covers. also, what is confusing you in the documentation? can you send a pointer to it? thanks, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Sun May 14 08:53:12 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 13 May 2006 23:53:12 -0700 (PDT) Subject: [Tutor] How do I create the equivalent of a Java class in Python? In-Reply-To: References: Message-ID: > How do I create the equivalent of a Java class in Python? I've been > looking at the reference, and it's been confusing to me at least. You may want to look at a tutorial on classes, like: http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm Does this help? Best of wishes! From john.corry at ntlworld.com Sun May 14 12:47:02 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 14 May 2006 11:47:02 +0100 Subject: [Tutor] Treeview Message-ID: <000001c67743$c0105d90$4a3ea8c0@JOHNC> Hi, I have managed to find the solution to my problem. I have defined iter as Iter = model.get_iter(combo3) The code now works. I will show it below for completeness: combo3 = self.wTree.get_widget("treeview1") model=gtk.TreeStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE _STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobj ect.TYPE_STRING,gobject.TYPE_STRING) self.hostsmodel = model combo3.set_model(model) combo3.connect("row_activated", self.callback53, combo3,model) def callback53(self,data,combo3,data2,data3,model): lookup = [] iter = model.get_iter(combo3) counter = 0 while counter < 8: result = model.get_value(iter,counter) lookup.append(result) counter = counter + 1 print lookup Technically this is the first solution that I have been able to post on the mailing list. Does this mean I am improving? Or does it not count as I have solved my own problem? Regards, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060514/9ea60351/attachment.htm From alan.gauld at freenet.co.uk Sun May 14 16:41:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 14 May 2006 15:41:58 +0100 Subject: [Tutor] How do I create the equivalent of a Java class in Python? References: Message-ID: <002601c67764$8dd661f0$0c01a8c0@XPpro> > How do I create the equivalent of a Java class in Python? I've been looking > at the reference, and it's been confusing to me at least. Adapted from my book: Java code: class Msg{ private String txt; public Msg(String s){ this.txt = s; } public void say(){ if (this.txt == "") System.out.println("No message"); else System.out.println(this.txt); } } Python code: class Msg: def __init__(self,s): self.s = s def say(self): if self.s: print "No message" else: print self.s Does that help? There is more on writing classes in the OOP topic of my tutor. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060514/bf0c9c3c/attachment.htm From stan at coll52.freeserve.co.uk Sun May 14 18:05:51 2006 From: stan at coll52.freeserve.co.uk (S W Collier) Date: Sun, 14 May 2006 17:05:51 +0100 Subject: [Tutor] Database topic now fixed Message-ID: <200605141705.51460.stan@coll52.freeserve.co.uk> Alan, Does that mean you will soon fix the tutor.tgz :-) Thanks for all the hard work you put into this. Stan. From wescpy at gmail.com Mon May 15 01:26:14 2006 From: wescpy at gmail.com (w chun) Date: Sun, 14 May 2006 16:26:14 -0700 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> Message-ID: <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> i agree with everyone above, kent, alan, roel... in fact, i have do a doubletake everytime i write code like this and have to look things up and/or play with some sample code as you all have done, just to make sure i got it working. (kinda reminds of going back to look at a perl script i wrote... have to check with the camel book to figure out what i really did.) i like alan's idea of splitting up the loops onto different lines so that you can more clearly see the loops. the syntax does support it altho it seems kind of clunky as: print\ [ j for i in a for j in f(i) ] originally, i thought that this would work: print [j for j in [f(i) for i in a]] but then realized that because of the inner grouping, it works just the same as the original and obvious print [f(i) for i in a] i think the point of the EXPR in... [EXPR for i in XXX for j in YYY for k in ZZZ...] ...is that EXPR is an expression that can be made up of components of any of the inner loops, i.e., i, j, k, etc., so you should really just think about the loops inside. perhaps you can consider that you're digging a hole and jumping into it. while inside the hole, you dig another one, and jump into *that*, ad nauseum. back at the top, you're only collating the things you want to save and have thrown out from all the holes you've dug yourself into. :-) anyone know if list comps work the same way in haskell? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From john at fouhy.net Mon May 15 01:55:38 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 15 May 2006 11:55:38 +1200 Subject: [Tutor] Nested list comprehensions In-Reply-To: <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> Message-ID: <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> On 15/05/06, w chun wrote: > anyone know if list comps work the same way in haskell? Slightly not what you asked, but you can do some funky things with list comprehensions in Haskell. Check this out: fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)] The python translation would be something like: fibs = [0, 1] + [ a+b for (a, b) in zip(fibs, fibs[1:])] But you can't quite do that in python :-) -- John. From kent37 at tds.net Mon May 15 02:16:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 May 2006 20:16:23 -0400 Subject: [Tutor] Nested list comprehensions In-Reply-To: <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> Message-ID: <4467C857.7020400@tds.net> John Fouhy wrote: > On 15/05/06, w chun wrote: >> anyone know if list comps work the same way in haskell? > > Slightly not what you asked, but you can do some funky things with > list comprehensions in Haskell. > > Check this out: > > fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)] > > The python translation would be something like: > > fibs = [0, 1] + [ a+b for (a, b) in zip(fibs, fibs[1:])] > > But you can't quite do that in python :-) You can come pretty close with generators, though it hurts to think about what is actually going on behind the scenes here: In [1]: import itertools In [2]: def fibs(): ...: yield 0 ...: yield 1 ...: fib1 = fibs() ...: fib2 = fibs() ...: fib2.next() ...: for a, b in itertools.izip(fib1, fib2): ...: yield a+b ...: ...: In [3]: f=fibs() In [4]: [f.next() for i in range(10)] Out[4]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Kent From john at fouhy.net Mon May 15 02:50:12 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 15 May 2006 12:50:12 +1200 Subject: [Tutor] Nested list comprehensions In-Reply-To: <4467C857.7020400@tds.net> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> <4467C857.7020400@tds.net> Message-ID: <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> On 15/05/06, Kent Johnson wrote: > You can come pretty close with generators, though it hurts to think > about what is actually going on behind the scenes here: > > In [1]: import itertools > > In [2]: def fibs(): > ...: yield 0 > ...: yield 1 > ...: fib1 = fibs() > ...: fib2 = fibs() > ...: fib2.next() > ...: for a, b in itertools.izip(fib1, fib2): > ...: yield a+b Yikes! f = fibs() for i in range(100): start = time.clock() x = f.next() dur = time.clock() - start print i, x, dur if dur > 10: break 0 0 2.03936533833e-005 1 1 5.5873022968e-006 2 1 1.59238115459e-005 3 2 1.25714301678e-005 4 3 1.95555580388e-005 5 5 2.15111138427e-005 6 8 2.93333370582e-005 7 13 6.06222299203e-005 8 21 7.87809623849e-005 9 34 0.000119568269152 10 55 0.000383568302675 11 89 0.000409269893241 12 144 0.000650082622233 13 233 0.000979454092629 14 377 0.00172200656787 15 610 0.00713330884232 16 987 0.00450979104886 17 1597 0.0128720270314 18 2584 0.0150373860365 19 4181 0.0283779083654 20 6765 0.0490199173359 21 10946 0.135228918759 22 17711 0.240615497221 23 28657 0.365666586116 24 46368 0.827867508301 25 75025 2.14721368219 26 121393 4.08266218193 27 196418 20.1769099145 Hmm, do you know an easy way to check how much memory python is using? My HDD was swapping like crazy by the end of that.. -- John. From alan.gauld at freenet.co.uk Mon May 15 09:58:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 15 May 2006 08:58:58 +0100 Subject: [Tutor] Database topic now fixed References: <200605141705.51460.stan@coll52.freeserve.co.uk> Message-ID: <001701c677f5$6c018690$0c01a8c0@XPpro> > Does that mean you will soon fix the tutor.tgz :-) > Thanks for all the hard work you put into this. I updated the PDF. zip and tgz files at the same time I uploaded the fixed database topic, but before I made the additional fixes Bob suggested.... Alan G. From kent37 at tds.net Mon May 15 12:09:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 May 2006 06:09:18 -0400 Subject: [Tutor] Nested list comprehensions In-Reply-To: <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> <4467C857.7020400@tds.net> <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> Message-ID: <4468534E.5070401@tds.net> John Fouhy wrote: > Hmm, do you know an easy way to check how much memory python is using? > My HDD was swapping like crazy by the end of that.. Use Windows Task Manager or top for a rough estimate...or try one of these: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 http://www.softwareverify.com/pythonMemoryValidator/index.html (website down at the moment) Kent From kent37 at tds.net Mon May 15 12:55:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 May 2006 06:55:00 -0400 Subject: [Tutor] Nested list comprehensions In-Reply-To: <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> <4467C857.7020400@tds.net> <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> Message-ID: <44685E04.2090108@tds.net> John Fouhy wrote: > On 15/05/06, Kent Johnson wrote: >> You can come pretty close with generators, though it hurts to think >> about what is actually going on behind the scenes here: >> >> In [1]: import itertools >> >> In [2]: def fibs(): >> ...: yield 0 >> ...: yield 1 >> ...: fib1 = fibs() >> ...: fib2 = fibs() >> ...: fib2.next() >> ...: for a, b in itertools.izip(fib1, fib2): >> ...: yield a+b > > Yikes! > > f = fibs() > for i in range(100): > start = time.clock() > x = f.next() > dur = time.clock() - start > print i, x, dur > if dur > 10: > break > > 0 0 2.03936533833e-005 > 1 1 5.5873022968e-006 > 2 1 1.59238115459e-005 > 3 2 1.25714301678e-005 > 4 3 1.95555580388e-005 > 5 5 2.15111138427e-005 > 6 8 2.93333370582e-005 > 7 13 6.06222299203e-005 > 8 21 7.87809623849e-005 > 9 34 0.000119568269152 > 10 55 0.000383568302675 > 11 89 0.000409269893241 > 12 144 0.000650082622233 > 13 233 0.000979454092629 > 14 377 0.00172200656787 > 15 610 0.00713330884232 > 16 987 0.00450979104886 > 17 1597 0.0128720270314 > 18 2584 0.0150373860365 > 19 4181 0.0283779083654 > 20 6765 0.0490199173359 > 21 10946 0.135228918759 > 22 17711 0.240615497221 > 23 28657 0.365666586116 > 24 46368 0.827867508301 > 25 75025 2.14721368219 > 26 121393 4.08266218193 > 27 196418 20.1769099145 > > Hmm, do you know an easy way to check how much memory python is using? > My HDD was swapping like crazy by the end of that.. Does the Haskell version do any better? ISTM this formulation is fundamentally inefficient; calculating fib(n) is going to create something like fib(n-1) fib objects. In the Python case each fib is a generator which I imagine means it has some kind of stack frame associated with it. Kent From kraus at hagen-partner.de Mon May 15 13:12:38 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Mon, 15 May 2006 13:12:38 +0200 Subject: [Tutor] Nested list comprehensions In-Reply-To: <44685E04.2090108@tds.net> References: <1107400.1146842874915.JavaMail.clajo04@mac.com> <013b01c6709f$6af15670$0c01a8c0@XPpro> <78b3a9580605141626y606453aeq8af11d65175e7f8e@mail.gmail.com> <5e58f2e40605141655y3b524d91v4904abf54cc71ca0@mail.gmail.com> <4467C857.7020400@tds.net> <5e58f2e40605141750t50fcc23bhe24332e0a7bc1587@mail.gmail.com> <44685E04.2090108@tds.net> Message-ID: Kent Johnson wrote: > John Fouhy wrote: > >>On 15/05/06, Kent Johnson wrote: >> >>>You can come pretty close with generators, though it hurts to think >>>about what is actually going on behind the scenes here: >>> >>>In [1]: import itertools >>> >>>In [2]: def fibs(): >>> ...: yield 0 >>> ...: yield 1 >>> ...: fib1 = fibs() >>> ...: fib2 = fibs() >>> ...: fib2.next() >>> ...: for a, b in itertools.izip(fib1, fib2): >>> ...: yield a+b >> >>Yikes! >> >>f = fibs() >>for i in range(100): >> start = time.clock() >> x = f.next() >> dur = time.clock() - start >> print i, x, dur >> if dur > 10: >> break >> >>0 0 2.03936533833e-005 >>1 1 5.5873022968e-006 >>2 1 1.59238115459e-005 >>3 2 1.25714301678e-005 >>4 3 1.95555580388e-005 >>5 5 2.15111138427e-005 >>6 8 2.93333370582e-005 >>7 13 6.06222299203e-005 >>8 21 7.87809623849e-005 >>9 34 0.000119568269152 >>10 55 0.000383568302675 >>11 89 0.000409269893241 >>12 144 0.000650082622233 >>13 233 0.000979454092629 >>14 377 0.00172200656787 >>15 610 0.00713330884232 >>16 987 0.00450979104886 >>17 1597 0.0128720270314 >>18 2584 0.0150373860365 >>19 4181 0.0283779083654 >>20 6765 0.0490199173359 >>21 10946 0.135228918759 >>22 17711 0.240615497221 >>23 28657 0.365666586116 >>24 46368 0.827867508301 >>25 75025 2.14721368219 >>26 121393 4.08266218193 >>27 196418 20.1769099145 >> >>Hmm, do you know an easy way to check how much memory python is using? >> My HDD was swapping like crazy by the end of that.. > > > Does the Haskell version do any better? ISTM this formulation is > fundamentally inefficient; calculating fib(n) is going to create > something like fib(n-1) fib objects. In the Python case each fib is a > generator which I imagine means it has some kind of stack frame > associated with it. > > Kent > fib is the standard use-case for the memoize decorator: http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622201abfac735ea47ffade5 HTH, Wolfram From jjabson at yahoo.com Mon May 15 18:16:47 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Mon, 15 May 2006 09:16:47 -0700 (PDT) Subject: [Tutor] Running Java process doesn't return to subprocess.call Message-ID: <20060515161647.95100.qmail@web53711.mail.yahoo.com> Hello, I'm running a Java process from my python script using the subprocess module. But there seems to be some problem with the return code to subprocess and the Java program is just hanging waiting for something. If I run the Java program from shell it terminates normally and if run the same program through a shell script it does the same thing. Is there something different I need to handle when running a Java program vs other programs? Here's my code: def proc(cmd_in): cmd = cmd_in if isinstance(cmd, types.StringTypes): cmd = cmd.split(' ') print cmd os.chdir("/home/qauser/jerome") outFile = os.path.join(os.curdir, "output.log") outptr = file(outFile, "w") errFile = os.path.join(os.curdir, "error.log") errptr = file(errFile, "w") retval = subprocess.call(cmd, 0, None, None, outptr, None) errptr.close() outptr.close() if retval != 0: errptr = file(errFile, "r") errData = errptr.read() errptr.close() raise Exception("Error executing command: " + repr(errData)) def setClass(): print "=== Setting Classpath ===" src = "/home/qauser/automation/setClass.sh" dst = "/home/qauser/jerome/setClass.sh" os.chdir("/home/qauser/jerome") shutil.copyfile(src, dst) os.chmod(dst, 0777) proc("/home/qauser/jerome/setClass.sh") classFile = open("/home/qauser/jerome/output.log", "r") CP = classFile.read() CP = CP.rstrip('\n') print "=== Complete Classpath Setup ===" return CP def run_junit(classpath): file_in = open("/home/qauser/automation/testdata/junit_master_file", "r") match = re.compile('#+') work_list = [] for line in file_in: work = line work = work.rstrip('\n') if match.search(work): found = False else: found = True if found == True: work_list = work.split(',') arg1 = work_list[0] arg2 = work_list[1] arg3 = work_list[2] arg4 = work_list[3] os.chdir("/home/qauser/jerome") cmd = "java -cp %s com.redsealsys.srm.server.analysis.NetmapTest %s %s %s %s" cmdstr = cmd % (classpath,arg1,arg2,arg3,arg4) print "=== Starting JUnit Run ===" proc(cmdstr) print "=== JUnit Run Complete ===" #################### ###### Main ###### #################### cp = setClass() run_junit(cp) The junit_master_file is just a comma separted file: netmap_func,/home/qauser/junit/static_nat/simple_nat,10.1.1.0,172.16.200.0 which has the prameters that I need to pass into the Java program. I would appreciate any insight or help in this matter. Much Thanks, Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From zubinw at zapdomain.ca Mon May 15 21:42:48 2006 From: zubinw at zapdomain.ca (Zubin Wadia) Date: Mon, 15 May 2006 15:42:48 -0400 (EDT) Subject: [Tutor] laying out frames In-Reply-To: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> Message-ID: <6353.66.6.192.154.1147722168.squirrel@www.zapdomain.ca> Hello Everyone, Another basic question in regard to frame layouts with Tkinter. I want to create a basic quadrant of frames but am not able to follow the logic to do so, whats the right way or an easier way to control layout of frames and wigets. A pixel approach would be nice (where by you can specify pixel locations for a frame or a widget to be located) instead of specifying arbitary location positions like LEFT, RIGHT, etc and things moving constantly when you add more widgets or resize windows. Here's my code bit ... from Tkinter import * class App: def __init__(self, root): fm1= Frame(root, width=200, height=200, bg="blue") fm1.pack(side=TOP, anchor= NW) fm2 = Frame(root, width=200, height=200, bg="RED") fm2.pack(side=TOP, anchor= NW) fm3 = Frame(root, width=200, height=200, bg="YELLOW") fm3.pack(side=LEFT, anchor= NE) fm4 = Frame(root, width=200, height=200, bg="TAN") fm4.pack(side=LEFT, anchor=NE) root = Tk() root.wm_title("layout") display = App(root) root.mainloop Thanks in advance. --zubin From klappnase at freenet.de Mon May 15 23:54:51 2006 From: klappnase at freenet.de (Michael Lange) Date: Mon, 15 May 2006 23:54:51 +0200 Subject: [Tutor] laying out frames In-Reply-To: <6353.66.6.192.154.1147722168.squirrel@www.zapdomain.ca> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> <6353.66.6.192.154.1147722168.squirrel@www.zapdomain.ca> Message-ID: <20060515235451.4a816006.klappnase@freenet.de> On Mon, 15 May 2006 15:42:48 -0400 (EDT) "Zubin Wadia" wrote: > Hello Everyone, > > Another basic question in regard to frame layouts with Tkinter. > > I want to create a basic quadrant of frames but am not able to follow the > logic to do so, whats the right way or an easier way to control layout of > frames and wigets. A pixel approach would be nice (where by you can > specify pixel locations for a frame or a widget to be located) instead of > specifying arbitary location positions like LEFT, RIGHT, etc and things > moving constantly when you add more widgets or resize windows. > Hi Zubin, there are three different geometry managers in Tkinter, pack(), grid() and place(). As you have noticed, pack() is very handy to use for simple gui layouts but more complex ones may be hard to achieve. grid() is more flexible than pack(), it lets you arrange widgets in row and columns, e.g.: from Tkinter import * root = Tk() # define rows and columns that should expand on window resizing root.grid_rowconfigure(1, weight=1) root.grid_rowconfigure(2, weight=1) root.grid_columnconfigure(0, weight=1) Label(root, text='Label1', bg='white').grid(row=0, column=0, sticky='ew') Label(root, text='Label2', bg='yellow').grid(row=0, column=1) Label(root, text='Label3', bg='green').grid(row=0, column=2) Label(root, text='Label4', bg='red').grid(row=1, column=0, columnspan=2, sticky='nsew') Label(root, text='Label5', bg='blue').grid(row=2, column=0, columnspan=3, sticky='nsew') root.mainloop() place() is even much more flexible than grid(), but it is much more complex to use, too, so I recommend to think twice if you really need its capabilities. With place() you can define absolute or relative x ynd y coords of a widget in its container and relative or absolute dimensions, e.g: from Tkinter import * root = Tk() Label(root, text='Label1', bg='green').place(x=10, y=40, relwidth=0.5, relheight=0.3) Label(root, text='Label2', bg='yellow').place(relx=0.1, rely=0.8, width=60, height=30) root.mainloop() I hope this helps Michael From zubinw at zapdomain.ca Tue May 16 00:38:44 2006 From: zubinw at zapdomain.ca (Zubin Wadia) Date: Mon, 15 May 2006 18:38:44 -0400 (EDT) Subject: [Tutor] laying out frames In-Reply-To: <20060515235451.4a816006.klappnase@freenet.de> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> <6353.66.6.192.154.1147722168.squirrel@www.zapdomain.ca> <20060515235451.4a816006.klappnase@freenet.de> Message-ID: <22656.66.6.192.154.1147732724.squirrel@www.zapdomain.ca> Thats great, thanks Michael for the examples, I'll tinker with grid() and place(). Cheers! --zubin > On Mon, 15 May 2006 15:42:48 -0400 (EDT) > "Zubin Wadia" wrote: > >> Hello Everyone, >> >> Another basic question in regard to frame layouts with Tkinter. >> >> I want to create a basic quadrant of frames but am not able to follow >> the >> logic to do so, whats the right way or an easier way to control layout >> of >> frames and wigets. A pixel approach would be nice (where by you can >> specify pixel locations for a frame or a widget to be located) instead >> of >> specifying arbitary location positions like LEFT, RIGHT, etc and things >> moving constantly when you add more widgets or resize windows. >> > > Hi Zubin, > > there are three different geometry managers in Tkinter, pack(), grid() and > place(). > As you have noticed, pack() is very handy to use for simple gui layouts > but more complex > ones may be hard to achieve. > grid() is more flexible than pack(), it lets you arrange widgets in row > and columns, e.g.: > > from Tkinter import * > root = Tk() > # define rows and columns that should expand on window resizing > root.grid_rowconfigure(1, weight=1) > root.grid_rowconfigure(2, weight=1) > root.grid_columnconfigure(0, weight=1) > Label(root, text='Label1', bg='white').grid(row=0, column=0, sticky='ew') > Label(root, text='Label2', bg='yellow').grid(row=0, column=1) > Label(root, text='Label3', bg='green').grid(row=0, column=2) > Label(root, text='Label4', bg='red').grid(row=1, column=0, columnspan=2, > sticky='nsew') > Label(root, text='Label5', bg='blue').grid(row=2, column=0, columnspan=3, > sticky='nsew') > root.mainloop() > > place() is even much more flexible than grid(), but it is much more > complex to use, too, > so I recommend to think twice if you really need its capabilities. > With place() you can define absolute or relative x ynd y coords of a > widget in its container and > relative or absolute dimensions, e.g: > > from Tkinter import * > root = Tk() > Label(root, text='Label1', bg='green').place(x=10, y=40, relwidth=0.5, > relheight=0.3) > Label(root, text='Label2', bg='yellow').place(relx=0.1, rely=0.8, > width=60, height=30) > root.mainloop() > > I hope this helps > > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "People demand freedom of speech to make up for the freedom of thought which they avoid." -- Socrates (470?-399 BC), From zubinw at zapdomain.ca Tue May 16 00:47:16 2006 From: zubinw at zapdomain.ca (Zubin Wadia) Date: Mon, 15 May 2006 18:47:16 -0400 (EDT) Subject: [Tutor] laying out a menu widget inside a frame In-Reply-To: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> Message-ID: <22767.66.6.192.154.1147733236.squirrel@www.zapdomain.ca> Hi Michael, root.config(relief=RIDGE, bg="lightblue", bd=3) doesn't seem to work I'm not sure if the menu() widget can be packed in a frame container?? Thanks --zubin >Hi Zubin, >there is a typo in your code, it should be > > master.config(menu=menubar) > >but this does not seem to be your problem? >If you just want the menu to be inside the "lightblue", "RIDGE" part of the >window, try: > > root.config(relief=RIDGE, bg="lightblue", bd=3) > >and relief="flat", bg="lightblue" on the frame. > >I hope this helps > >Michael > Hello All, > > from Tkinter import * > > class App: > #create a frame > def __init__(self, master): > frame = Frame(master, bg="LIGHTBLUE", relief=RIDGE, bd=3) > frame.pack(side=TOP, ipadx=15, ipady=15, fill=X) > > ##create dropdown menu > > menubar = Menu(frame) > > filemenu = Menu(menubar) > menubar.add_cascade(label="File", menu=filemenu) > filemenu.add_command(label="New") > > root.config(menu=menubar) ##edit > > root = Tk() > root.minsize(100,100) > app = App(root) > root.mainloop() > > This works great but I can't get the dropdown menu to layout in the frame > widget instead of the root. I tried frame.config() in the ##edit line but > I don't think there is a config method for the frame widget, it errors > out. > > Any pointers? thanks in advance, > --zubin > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From shaleh at speakeasy.net Tue May 16 03:26:49 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Mon, 15 May 2006 18:26:49 -0700 Subject: [Tutor] Python challenge In-Reply-To: <20060504165020.15946.qmail@web25915.mail.ukl.yahoo.com> References: <20060504165020.15946.qmail@web25915.mail.ukl.yahoo.com> Message-ID: <44692A59.1010500@speakeasy.net> David Holland wrote: > I looked at this and got stuck on the first one :- Thanks for this. I missed it the first time it showed up on this list. Kinda fun and reminds me why I love python. Four lines in the interactive interpreter and most of the challenges are solved. From dyoo at hkn.eecs.berkeley.edu Tue May 16 03:56:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 15 May 2006 18:56:38 -0700 (PDT) Subject: [Tutor] Running Java process doesn't return to subprocess.call In-Reply-To: <20060515161647.95100.qmail@web53711.mail.yahoo.com> References: <20060515161647.95100.qmail@web53711.mail.yahoo.com> Message-ID: On Mon, 15 May 2006, Jerome Jabson wrote: > I'm running a Java process from my python script using the subprocess > module. But there seems to be some problem with the return code to > subprocess and the Java program is just hanging waiting for something. Hi Jerome, I see that you're using subprocess.call(): retval = subprocess.call(cmd, 0, None, None,outptr, None) I expected to see some reference to 'errFile' in the call here; otherwise, the java subprocess won't know that you want to dump error output there. Does your Java program expect anything out of standard input as well? Best of wishes! From carroll at tjc.com Tue May 16 07:25:45 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 15 May 2006 22:25:45 -0700 (PDT) Subject: [Tutor] Bit-level field extraction Message-ID: I want to see if I'm reinventing a wheel here, or maybe doing it unpythonically. I need to extract from a byte (i.e., a one-character string) a field of an certain number of bits. For example, a certain byte of an MP3 frame header has the format xxxVVxxx, where the value of VV (00, 01, 10 or 11) tels what version of MPEG Audio is being used. The other bits marked 'x' are not relevant to the version id, and may be 1s or 0s. Here's my stab: def getbits(byte, fieldlength, rightpad): ''' returns an integer with the value derived from a string of bits of length fieldlength, right-padded with rightpad number of bits. e.g., getbyte(byte, 2, 3) returns a value from bits 3-4 (counting from the right) ''' bitmask = (2**fieldlength-1) << rightpad return (ord(byte) & bitmask) >> rightpad testbytes = ["\xC0", "\x08", "\xF0", "\x19"] for byte in testbytes: print getbits(byte, 2, 3) # should get 0, 1, 2, 3 This works (at least for these 4 test cases). But is this the best way to extract a bit-level field, or am I missing some appropriate module or something? From alan.gauld at freenet.co.uk Tue May 16 09:49:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 16 May 2006 08:49:26 +0100 Subject: [Tutor] laying out frames References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> <6353.66.6.192.154.1147722168.squirrel@www.zapdomain.ca> Message-ID: <001701c678bd$41718ab0$0c01a8c0@XPpro> > I want to create a basic quadrant of frames but am not able to > follow the > logic to do so, whats the right way or an easier way to control > layout of > frames and wigets. A pixel approach would be nice (where by you can > specify pixel locations for a frame or a widget to be located) > instead of > specifying arbitary location positions like LEFT, RIGHT, etc and > things > moving constantly when you add more widgets or resize windows. You can use the placer widget manager instead of grid or pack to specify pixel based locations. But grid or pack are preferred precisely because they do automatically move things around when you resize screens - one of the hardest things to do when using pixel arrangements! Also pixel based layouts tend not to be very portable between systems - some use square pixels, others rectangular etc So the GUI looks different on different machines. Intelligent layout managers make life much easier if you are running on anything other than a single defined computer spec. For a quadrant layout the grid manager is probably the best option. Simply define a 2x2 grid and put the frames/widgets in that. However even using pack its easy enough, just define two frames, top and bottom. insert two frames(left and right) into reach of those two frames. This gives you 6 frames in total. HTH, Alan G. From kent37 at tds.net Tue May 16 12:03:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 May 2006 06:03:04 -0400 Subject: [Tutor] Bit-level field extraction In-Reply-To: References: Message-ID: <4469A358.5020101@tds.net> Terry Carroll wrote: > I want to see if I'm reinventing a wheel here, or maybe doing it > unpythonically. > > I need to extract from a byte (i.e., a one-character string) a field of an > certain number of bits. For example, a certain byte of an MP3 frame > header has the format xxxVVxxx, where the value of VV (00, 01, 10 or 11) > tels what version of MPEG Audio is being used. The other bits marked 'x' > are not relevant to the version id, and may be 1s or 0s. > > Here's my stab: > > def getbits(byte, fieldlength, rightpad): > ''' > returns an integer with the value derived from a string of bits of > length fieldlength, right-padded with rightpad number of bits. > e.g., getbyte(byte, 2, 3) returns a value from bits 3-4 > (counting from the right) > ''' > bitmask = (2**fieldlength-1) << rightpad > return (ord(byte) & bitmask) >> rightpad > > testbytes = ["\xC0", "\x08", "\xF0", "\x19"] > for byte in testbytes: > print getbits(byte, 2, 3) > # should get 0, 1, 2, 3 > > > This works (at least for these 4 test cases). But is this the best way to > extract a bit-level field, or am I missing some appropriate module or > something? You might be interested in Construct, it aims to make it easy to parse and create structures based on bit fields: http://pyconstruct.wikispaces.com/ It seems to work by assembling a string representing the bit values of the target, then converting to binary. My guess is your method will be faster but Construct looks pretty convenient to work with. If you try it let us know how it goes... Kent From klappnase at freenet.de Tue May 16 11:57:24 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 16 May 2006 11:57:24 +0200 Subject: [Tutor] laying out a menu widget inside a frame In-Reply-To: <22767.66.6.192.154.1147733236.squirrel@www.zapdomain.ca> References: <23386.66.6.192.154.1147374233.squirrel@www.zapdomain.ca> <22767.66.6.192.154.1147733236.squirrel@www.zapdomain.ca> Message-ID: <20060516115724.55727c71.klappnase@freenet.de> On Mon, 15 May 2006 18:47:16 -0400 (EDT) "Zubin Wadia" wrote: Hi Zubin, > root.config(relief=RIDGE, bg="lightblue", bd=3) doesn't seem to work it works for me (linux), maybe a platform issue? > I'm not sure if the menu() widget can be packed in a frame container?? > I don't think you can: >>> m=Menu(frame) >>> m.pack(side='top', fill='x') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1595, in pack_configure self.tk.call( TclError: can't pack ".135695884.135828540": it's a top-level window It seems like the Pmw.MenuBar widget can do what you want: >>> mb =Pmw.MenuBar(frame) >>> mb.pack(side='top', fill='x') >>> mb.addmenu('File', 'File') >>> adds a menu bar to the Frame, so maybe you will want to have a look at Pmw. I hope this helps Michael From ml.cyresse at gmail.com Tue May 16 14:47:39 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 17 May 2006 00:47:39 +1200 Subject: [Tutor] Treeview In-Reply-To: <000001c67743$c0105d90$4a3ea8c0@JOHNC> References: <000001c67743$c0105d90$4a3ea8c0@JOHNC> Message-ID: Sometimes it's your own problem that is hardest to solve, as you're too familiar with the code. :) Congratulations on making sense of pyGTK, the documentation isn't overly helpful... ...I'm used to the wxPython docs and still got confused with the pyGTK ones. Regards, Liam Clarke On 5/14/06, John CORRY wrote: > > > > > Hi, > > > > I have managed to find the solution to my problem. > > > > I have defined iter as > > > > Iter = model.get_iter(combo3) > > > > The code now works. I will show it below for completeness: > > > > combo3 = self.wTree.get_widget("treeview1") > > > > model=gtk.TreeStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) > > self.hostsmodel = model > > combo3.set_model(model) > > combo3.connect("row_activated", self.callback53, combo3,model) > > > > def callback53(self,data,combo3,data2,data3,model): > > > > > > lookup = [] > > > > iter = model.get_iter(combo3) > > counter = 0 > > while counter < 8: > > > > result = model.get_value(iter,counter) > > lookup.append(result) > > counter = counter + 1 > > print lookup > > > > Technically this is the first solution that I have been able to post on the > mailing list. Does this mean I am improving? Or does it not count as I > have solved my own problem? > > > > Regards, > > > > John. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kieran.flanagan at gmail.com Tue May 16 15:10:37 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Tue, 16 May 2006 14:10:37 +0100 Subject: [Tutor] Python new comer Message-ID: Hey I am currently learning Python to start scripting automated tests. A lot of these tests require me to strip out values from xml docs using the minidom feature. So really I am just looking for any good articles to start learning Python as a whole and to learn about using Python as a node iterator to strip out required info from an xml doc. Thanks k -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060516/b6f1924f/attachment.html From kent37 at tds.net Tue May 16 15:40:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 May 2006 09:40:48 -0400 Subject: [Tutor] Python new comer In-Reply-To: References: Message-ID: <4469D660.1020505@tds.net> kieran flanagan wrote: > Hey > > I am currently learning Python to start scripting automated tests. A lot > of these tests require me to strip out values from xml docs using the > minidom feature. So really I am just looking for any good articles to > start learning Python as a whole and to learn about using Python as a > node iterator to strip out required info from an xml doc. Welcome! Have you found the page of beginners' tutorials? http://wiki.python.org/moin/BeginnersGuide/NonProgrammers If you are just starting with Python and XML I recommend ElementTree rather than minidom. It is an add-on module that will be part of the standard library in Python 2.5. http://effbot.org/zone/element-index.htm This page talks about searching an ElementTree for subelements: http://effbot.org/zone/element.htm#searching-for-subelements Ask questions here as needed, we're very friendly! Try to be specific - if you have a question about how to process XML, show a snippet of XML and any code you have tried. If you get an error you don't understand, copy and paste the entire error message into your email. Kent From alan.gauld at freenet.co.uk Tue May 16 17:01:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 16 May 2006 16:01:23 +0100 Subject: [Tutor] Bit-level field extraction References: Message-ID: <002001c678f9$ae034ec0$0c01a8c0@XPpro> Terry, Your approach is fine. Personally however I'd just have defined some constants and done a direct bitwise and - this is the approach used in the stat module: VMASK = 0x14 # 00011000 VER00 = 0x00 VER01 = 0x04 VER10 = 0x10 VER11 = 0x14 version = byte & VMASK if version == VER00: #do something elif version == VER01: # do another etc... But I'm just an old assembler programmer in disguise :-) A function approach is OK too... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Terry Carroll" To: Sent: Tuesday, May 16, 2006 6:25 AM Subject: [Tutor] Bit-level field extraction >I want to see if I'm reinventing a wheel here, or maybe doing it > unpythonically. > > I need to extract from a byte (i.e., a one-character string) a field > of an > certain number of bits. For example, a certain byte of an MP3 frame > header has the format xxxVVxxx, where the value of VV (00, 01, 10 or > 11) > tels what version of MPEG Audio is being used. The other bits > marked 'x' > are not relevant to the version id, and may be 1s or 0s. > > Here's my stab: > > def getbits(byte, fieldlength, rightpad): > ''' > returns an integer with the value derived from a string of bits > of > length fieldlength, right-padded with rightpad number of bits. > e.g., getbyte(byte, 2, 3) returns a value from bits 3-4 > (counting from the right) > ''' > bitmask = (2**fieldlength-1) << rightpad > return (ord(byte) & bitmask) >> rightpad > > testbytes = ["\xC0", "\x08", "\xF0", "\x19"] > for byte in testbytes: > print getbits(byte, 2, 3) > # should get 0, 1, 2, 3 > > > This works (at least for these 4 test cases). But is this the best > way to > extract a bit-level field, or am I missing some appropriate module > or > something? > > > From andrew.arobert at gmail.com Tue May 16 18:31:46 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 12:31:46 -0400 Subject: [Tutor] Question on option parser Message-ID: <4469FE72.2050604@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, I have a program that I'd would like to enhance flexibility in calling. Is there a way to leverage optionparser so it can accept input from both command line and a configuration file? Current code block is: # # Parse command line options and automatically build # help/usage display # parser = OptionParser() parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-t","--to", dest="mto", help="\t\taddress any mail messages will be sent to") (options, args) = parser.parse_args() Any help you can provide on this would be greatly appreciated. Thanks, Andy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEaf5xDvn/4H0LjDwRAnzAAJ94RcBxTxARkvX5pwMtvVM9n/vntgCfZ1bV FvMSiQpo/2EneM9hvuxpCi8= =2Il4 -----END PGP SIGNATURE----- From carroll at tjc.com Tue May 16 20:08:05 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 16 May 2006 11:08:05 -0700 (PDT) Subject: [Tutor] Bit-level field extraction In-Reply-To: <4469A358.5020101@tds.net> Message-ID: On Tue, 16 May 2006, Kent Johnson wrote: > You might be interested in Construct, it aims to make it easy to parse > and create structures based on bit fields: > http://pyconstruct.wikispaces.com/ Thanks, I'll have a look at it. From andrew.arobert at gmail.com Tue May 16 20:16:38 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 14:16:38 -0400 Subject: [Tutor] Question on option parser In-Reply-To: <446A0155.5060701@tds.net> References: <4469FE72.2050604@gmail.com> <446A0155.5060701@tds.net> Message-ID: <446A1706.9080305@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Kent, If I understood correctly, you meant something like this? # # Parse command line options and automatically build help/usage # display # if len(sys.argv) == 2: infile= open(sys.argv[1],"rb").read() parser=OptionParser() (options, args) = parser.parse_args(infile) else: parser = OptionParser() parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-t","--to", dest="mto", help="\t\taddress any mail messages will be sent to") (options, args) = parser.parse_args() print options.qmanager If so, the code generates the following deletion error. Traceback (most recent call last): File "C:\Documents and Settings\Andrew Robert\My Documents\receiver.py", line 326, in ? (options, args) = parser.parse_args(infile) File "C:\Python24\lib\optparse.py", line 1275, in parse_args stop = self._process_args(largs, rargs, values) File "C:\Python24\lib\optparse.py", line 1322, in _process_args del rargs[0] TypeError: object doesn't support item deletion Any ideas? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEahcFDvn/4H0LjDwRAkZFAKCGapybjYnhuX9dy1DvMswskawLegCdEbbY o/VaV2WP/ymg3dbwo3TaBi4= =wLEn -----END PGP SIGNATURE----- From carroll at tjc.com Tue May 16 20:17:19 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 16 May 2006 11:17:19 -0700 (PDT) Subject: [Tutor] Bit-level field extraction In-Reply-To: <002001c678f9$ae034ec0$0c01a8c0@XPpro> Message-ID: On Tue, 16 May 2006, Alan Gauld wrote: > Your approach is fine. Personally however I'd just have defined > some constants and done a direct bitwise and - this is the > approach used in the stat module: > > VMASK = 0x14 # 00011000 > VER00 = 0x00 > VER01 = 0x04 > VER10 = 0x10 > VER11 = 0x14 > > version = byte & VMASK > if version == VER00: #do something > elif version == VER01: # do another > etc... Good idea. In this particular case, I actualy need the value, because it's to be used either as a key to a dictionary or a subscript to a list later on; i.e., my if tree would look like this: if version == VER00: ver_num = 0 elif version == VER01: ver_num = 1 elif version == VER02: ver_num = 2 elif version == VER03: ver_num = 3 Actually, the version number doesn't equal the two-bit number; values of 0, 2 and 3 mean versions 2.5, 2 or 1, respectively (1 being reserved), but you get the idea. The key is I need later to be able to use the value itself. But I have a number of other parts of the frame header where the defined constants are a great way to go; thanks. > But I'm just an old assembler programmer in disguise :-) Heh, you and me both. I cut my teeth on IBM System/370 assembler. Last time I had a job where I actually did programming as part of it, it was System/390 machine code. That's right, machine code, not assembler; I'd directly type my hexadecimal programs into low storage at the operator's console. From khp at pflaesterer.de Tue May 16 20:35:08 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue, 16 May 2006 20:35:08 +0200 Subject: [Tutor] Question on option parser In-Reply-To: <4469FE72.2050604@gmail.com> (Andrew Robert's message of "Tue, 16 May 2006 12:31:46 -0400") References: <4469FE72.2050604@gmail.com> Message-ID: On 16 Mai 2006, andrew.arobert at gmail.com wrote: > Is there a way to leverage optionparser so it can accept input from both > command line and a configuration file? > > Current code block is: > > # > # Parse command line options and automatically build > # help/usage display > # > parser = OptionParser() > parser.add_option("-m","--qmanager", dest="qmanager", > help="\t\tQueue Manager to inquire against"), > parser.add_option("-q","--queue", dest="queue", > help="\t\tQueue the message will be sent to"), > parser.add_option("-t","--to", dest="mto", > help="\t\taddress any mail messages will be sent to") > (options, args) = parser.parse_args() parse_args() can take the list to parse as argument; per default it parses sys.argv[1:]. So you could build a list of options from your config file and call parse_args() like that: (options, args) = parser.parse_args(configlst + sys.argv[1:]) Like that options given on the command line would overwrite options from the config file. Another approach could be to define default values for the variables. Let's take your above example. parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-t","--to", dest="mto", help="\t\taddress any mail messages will be sent to") Then you would read the values from the config file and call parser.set_defaults() with the values. parser.set_defaults(qmanager="Foo", queue="Bar", mto="nowhere at invalid") Karl -- Please do *not* send copies of replies to me. I read the list From stan at coll52.freeserve.co.uk Tue May 16 21:13:03 2006 From: stan at coll52.freeserve.co.uk (S W Collier) Date: Tue, 16 May 2006 20:13:03 +0100 Subject: [Tutor] Bit-level field extraction In-Reply-To: <002001c678f9$ae034ec0$0c01a8c0@XPpro> References: <002001c678f9$ae034ec0$0c01a8c0@XPpro> Message-ID: <200605162013.03474.stan@coll52.freeserve.co.uk> On Tuesday 16 May 2006 16:01, Alan Gauld wrote: > Terry, > > Your approach is fine. Personally however I'd just have defined > some constants and done a direct bitwise and - this is the > approach used in the stat module: > > VMASK = 0x14 # 00011000 > VER00 = 0x00 > VER01 = 0x04 > VER10 = 0x10 > VER11 = 0x14 > > version = byte & VMASK > if version == VER00: #do something > elif version == VER01: # do another > Alan Gauld Whoops, a typo I think. VMASK = 0x18 #00011000 or VMASK = 0x14 #00010100 Stan From dyoo at hkn.eecs.berkeley.edu Tue May 16 21:05:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 May 2006 12:05:37 -0700 (PDT) Subject: [Tutor] Running Java process doesn't return to subprocess.call (fwd) Message-ID: ---------- Forwarded message ---------- Date: Tue, 16 May 2006 11:50:32 -0700 (PDT) From: Jerome Jabson To: dyoo at hkn.eecs.berkeley.edu Subject: Re: [Tutor] Running Java process doesn't return to subprocess.call Hi Danny, I actually changed that just before I sent the email to tutor, cause I'd seen a reference on the web about a Java process in Zope hanging. And the fix was to have errfile set to None. It did NOT fix the problem. It actually cause a Java Expection now! :-( The Java program expect nothing from input. So I'm still stumped on why this is hanging. Is there any insight you have on why a Java process would hang like that? I use the same function in other programs and it works just fine. Thanks again for your help! Jerome On Mon, 15 May 2006, Jerome Jabson wrote: > I'm running a Java process from my python script using the subprocess > module. But there seems to be some problem with the return code to > subprocess and the Java program is just hanging waiting for something. Hi Jerome, I see that you're using subprocess.call(): retval = subprocess.call(cmd, 0, None, None,outptr, None) I expected to see some reference to 'errFile' in the call here; otherwise, the java subprocess won't know that you want to dump error output there. Does your Java program expect anything out of standard input as well? Best of wishes! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From archangel at interbaun.com Tue May 16 21:40:08 2006 From: archangel at interbaun.com (Miguel Estrada) Date: Tue, 16 May 2006 13:40:08 -0600 Subject: [Tutor] Division operation Message-ID: <446A2A98.8000204@interbaun.com> Hi there, I'm new to Python and programming in general. This is the function I am writing: def function(): x = int(raw_input("Enter value of x: ")) y = int(raw_input("Enter value of y: ")) z = x / y print "The value of z is", z, "unit of measurement" Now, say, user input: x = 200 y = 1000 The value returned will be '0'. My question: What is the proper way of writing the operation so that if z = x /y, the result would be '0.20' instead of just '0'? TIA. -Miguel From carroll at tjc.com Tue May 16 22:17:52 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 16 May 2006 13:17:52 -0700 (PDT) Subject: [Tutor] Division operation In-Reply-To: <446A2A98.8000204@interbaun.com> Message-ID: On Tue, 16 May 2006, Miguel Estrada wrote: > def function(): > x = int(raw_input("Enter value of x: ")) > y = int(raw_input("Enter value of y: ")) > z = x / y > print "The value of z is", z, "unit of measurement" > > > Now, say, user input: > > x = 200 > y = 1000 > > The value returned will be '0'. > > My question: What is the proper way of writing the operation so that if > z = x /y, the result would be '0.20' instead of just '0'? This is a frustrating design choice in Python, which I believe is on the list of Guido's regrets and will be corrected in Python 3.0. Where both operands are integers, Python division truncates to and integer result, thus: >>> x = 200 >>> y = 1000 >>> z = x/y >>> z 0 But if either operand is a float, you get the results that you'd expect: >>> x = 200.0 >>> y = 1000 >>> z = x/y >>> z 0.20000000000000001 >>> (the "000000..1" is rounding error from the basic impossibility of representing 1/5 in a binary system) You can include the following in your program (I often do) if you want division to operate the way you expect: >>> from __future__ import division >>> from __future__ import division >>> x = 200 >>> y = 1000 >>> z = x/y >>> z 0.20000000000000001 >>> From alan.gauld at freenet.co.uk Tue May 16 23:41:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 16 May 2006 22:41:05 +0100 Subject: [Tutor] Bit-level field extraction References: Message-ID: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> > Heh, you and me both. I cut my teeth on IBM System/370 assembler. > Last > time I had a job where I actually did programming as part of it, it > was > System/390 machine code. That's right, machine code, not assembler; > I'd > directly type my hexadecimal programs into low storage at the > operator's > console. Hah, if you haven't bootstrapped a VAX using the toggle switches on the front panel you ain't a real progammer ;-) Actually one of our local Universities still starts their computer science courses by teaching students how to do that, before moving them onto machine code, assembler, C and finally Java(*). It's like an historical tour of computing/programming. The machine code is done on little hex keypads with pocket calculator style printout rools! Its only when they get to C that they get to use a PC! (*) Actually they get to choose from several languages in their 4th (final) year, including Lisp and Prolog(both), Haskell and PL/SQL... They consistently produce very good graduates, so it seems to work. Alan G From singingxduck at gmail.com Tue May 16 23:45:25 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 16 May 2006 17:45:25 -0400 Subject: [Tutor] How do I create the equivalent of a Java class in Python? In-Reply-To: <002601c67764$8dd661f0$0c01a8c0@XPpro> References: <002601c67764$8dd661f0$0c01a8c0@XPpro> Message-ID: <446A47F5.8030309@gmail.com> Alan Gauld wrote: > > How do I create the equivalent of a Java class in Python? I've been > looking > > at the reference, and it's been confusing to me at least. > > Adapted from my book: > > Java code: > > class Msg{ > private String txt; > public Msg(String s){ > this.txt = s; > } > public void say(){ > if (this.txt == "") > System.out.println("No message"); > else > System.out.println(this.txt); > } > } > > Python code: > > class Msg: > def __init__(self,s): > self.s = s > def say(self): > if self.s: print "No message" > else: print self.s > > Does that help? > There is more on writing classes in the OOP topic of my tutor. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Erm. Shouldn't that be the following? class Msg: def __init__(self,s): self.s = s def say(self): if *not *self.s: print "No message" else: print self.s -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From alan.gauld at btinternet.com Tue May 16 23:47:21 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 May 2006 22:47:21 +0100 Subject: [Tutor] Bit-level field extraction References: <002001c678f9$ae034ec0$0c01a8c0@XPpro> <200605162013.03474.stan@coll52.freeserve.co.uk> Message-ID: >> VMASK = 0x14 # 00011000 > > Whoops, a typo I think. VMASK = 0x18 #00011000 > or VMASK = 0x14 #00010100 A typo is being kind. A mistake in reality, that's what happens when I don't have a Python session handy! :-) Fortunately Terry knew what I meant. Alan G. From alan.gauld at btinternet.com Tue May 16 23:52:39 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 May 2006 22:52:39 +0100 Subject: [Tutor] Division operation References: <446A2A98.8000204@interbaun.com> Message-ID: > You can include the following in your program (I often do) if you > want > division to operate the way you expect: > >>>> from __future__ import division > Or you can do an explicit float conversion inside your function if you don't want the import effect. def f(x,y): returm float(x)/y This issue is discussed in the Simple Sequences topic of my tutor. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From prowlerslim at yahoo.com Wed May 17 00:22:30 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Tue, 16 May 2006 15:22:30 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project Message-ID: <20060516222230.15495.qmail@web52107.mail.yahoo.com> Hello all, I have been studying python tutorials and have a couple beginning python books that I have worked through. I have a very specific project in mind and I want to ask a couple questions. The project in question is this: I am making a Hand History converter for online poker players. This takes the textual record of how a hand played and turns into a more readable format suitable for posting at various websites where people discuss how the hand was played. Id like to start with the converter working for one particular online poker site (every site formats their hand histories somewhat differently) and expand it so that it can recognize the site a hand history came from and format accordingly. So, I am pretty sure that regular expressions will play a big part in the functions in this program. Also, the converter needs to be able to pull dollar amounts out and add them up to keep a running pot size for each round of betting. I guess I am really unsure of how to start. Ive sort of drawn out how I think the program should flow. I know this is sort of an open ended question and I hope it is appropriate for the list. What would really be helpful is if someone was willing to correspond privately since Im sure I will have a flood of questions but I realize you all have lives and so this might not be desireable or doable. But if anyone is willing, it would be really helpful. Ive been lurking for a few days now and this seems like a very friendly and helpful group. Thanks for taking the time to read this and I look forward to reading your replies, should anyone decide to do so. Chris PS I should add that some of these "converters" already exist, I have the perl script for one but the site I currently play on isnt supported and plus I just want to do this. :) --------------------------------- Yahoo! Messenger with Voice. PC-to-Phone calls for ridiculously low rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060516/4e03a716/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed May 17 01:03:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 16 May 2006 16:03:35 -0700 (PDT) Subject: [Tutor] Running Java process doesn't return to subprocess.call (fwd) In-Reply-To: References: Message-ID: > I actually changed that just before I sent the email to tutor, cause I'd > seen a reference on the web about a Java process in Zope hanging. And > the fix was to have errfile set to None. It did NOT fix the problem. It > actually cause a Java Expection now! :-( Hi Jerome, [Please keep tutor at python.org in CC; I'm about to dive into a situation (grad school) where I may not be able to answer Tutor mail for a while. It's best to keep the discussion within the mailing list. That way, other folks can help too, and we avoid a single-point-of failure: me. *grin* As another meta note to the others here on Tutor: since I might be gone for a bit, the current plan is to pass the administrative reins to Kent Johnson.] Do you mind if you show the exception traceback to us on the list? That's a significant change in behavior, and an unexpected one! Let's look the error there more closely. > The Java program expect nothing from input. So I'm still stumped on why > this is hanging. Is there any insight you have on why a Java process > would hang like that? I use the same function in other programs and it > works just fine. Odd. Does this happen to all Java programs you run through Python's subprocess module, or is it exclusive to the program that you are running now? What happens if you do run something silly and simple like: /*** Java code ***/ public class Test { static public void main(String[] args) { System.out.println("Hello world"); } } /****************/ For you, does subprocess also freeze here when it tries to drive this Test class too? I have to admit that I'm very ignorant about what's happening here. *grin* I think we need to isolate the issue better. You mentioned that subprocess-ing other programs seems fine, so one natural question follows: is it Java itself that's doing something funky, or is it something particular to the particular Java program we're driving? Let's do a little more work to find what the real issue is. Best of wishes! From alan.gauld at freenet.co.uk Wed May 17 01:17:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 17 May 2006 00:17:05 +0100 Subject: [Tutor] How do I create the equivalent of a Java class in Python? References: <002601c67764$8dd661f0$0c01a8c0@XPpro> <446A47F5.8030309@gmail.com> Message-ID: <001b01c6793e$d920b350$0c01a8c0@XPpro> > Erm. Shouldn't that be the following? > > class Msg: > def __init__(self,s): > self.s = s > def say(self): > if *not *self.s: print "No message" > else: print self.s Yep, its my week for making mistakes. Although this one was just a typo... My only excuse is that I'm really busy with my project at work just now so not really checking the tutor code... Alan G. From alan.gauld at freenet.co.uk Wed May 17 01:33:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 17 May 2006 00:33:27 +0100 Subject: [Tutor] New programmer, need some help getting started on my first project References: <20060516222230.15495.qmail@web52107.mail.yahoo.com> Message-ID: <004301c67941$2290fc00$0c01a8c0@XPpro> > I am making a Hand History converter for online poker players. > This takes the textual record of how a hand played and turns > into a more readable format suitable for posting at various websites > where people discuss how the hand was played. Id like to start > with the converter working for one particular online poker site > (every site formats their hand histories somewhat differently) > and expand it so that it can recognize the site a hand history > came from and format accordingly. I don't know anything about poker but in general terms this is a text format conversion tool. since you know the source can be in different formats I'd adopt an OOP approach with a generic hand object which can be subclassed for each new format. The methods of the hand object might be something like load() and print(). The load method will be specific to each site and will convert the site format to some standard format defined in the generic hand. The print method then prints to a standard output format and only needs overriding for sites where you need a different output format - which sounds to be rare from your desciption. The generic hand class then allows you to write the resty of the application in a generic way without worrying about site details apart from the point where you instantiate the hands - and even that can be data driven via an external file or environment variable etc.. > So, I am pretty sure that regular expressions will play > a big part in the functions in this program. Possibly but I would defer that decision for as long as possible! > Also, the converter needs to be able to pull dollar amounts > out and add them up to keep a running pot size for each > round of betting. You may need a pot class in the same way as the hand above - but I'm not sure how that would workj since I don't know anything about poker! > really be helpful is if someone was willing to correspond > privately since Im sure I will have a flood of questions It would be more helpful - to you and the rest of the readership - if you keep it public. The kind of questions you will be asking are likely to be the kind any newbie will come across in a real project. By sharing the pain you also share the experience. You also get access to many more heads. > PS I should add that some of these "converters" already exist, > I have the perl script for one but the site I currently play on > isnt supported and plus I just want to do this. :) Converting the Perl into Python shouldn't be too hard when we get to the stage of needing to do that. For now let's start with one site and get it working, while building in enough flexibility for the future sites we know we need to deal with later. In fact maybe we should start at the end and work on the internal data structure needed to print out the final format. Can we define a program that can read the target format in and print oit out in the desired format? It may sound trivial but it gets a lot of the scaffolding in place early. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From andrew.arobert at gmail.com Wed May 17 02:57:15 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 20:57:15 -0400 Subject: [Tutor] Solution found for option parser In-Reply-To: <446A1706.9080305@gmail.com> References: <4469FE72.2050604@gmail.com> <446A0155.5060701@tds.net> <446A1706.9080305@gmail.com> Message-ID: <446A74EB.6000201@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi everyone, Just to be complete, I figured I would share the solution to use option parser for both command line and configuration file option passing. I hope it may be of use to someone in the future. parser = OptionParser() if len(sys.argv) == 2: lines = open(sys.argv[1],"rb").readlines() for line in lines: line=line.strip() if not line: continue short, long, dest, help, default = line.split(";") help = "\t\t" + help # Prepend tabs to help message parser.add_option(short, long, dest=dest, help=help, default=default) else: parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-d","--dest", dest="dest", help="\t\tDestination File Name"), parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="File to be transmitted", metavar="FILE") (options, args) = parser.parse_args() thanks all for the insight -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEanTrDvn/4H0LjDwRAmt0AJ4jf84OXoNdrxzz+A/pdKgiPnhyAwCfZQrG QCuhjN8sbYq+WhzmLToKIZs= =nOFN -----END PGP SIGNATURE----- From prowlerslim at yahoo.com Wed May 17 03:09:30 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Tue, 16 May 2006 18:09:30 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <004301c67941$2290fc00$0c01a8c0@XPpro> Message-ID: <20060517010930.7605.qmail@web52102.mail.yahoo.com> Alan, First off, thanks for the detailed reply, it is much appreciated. On to your message: >I don't know anything about poker but in general terms this is >a text format conversion tool. since you know the source can >be in different formats I'd adopt an OOP approach with a generic >hand object which can be subclassed for each new format. >The methods of the hand object might be something like load() >and print(). The load method will be specific to each site and >will convert the site format to some standard format defined >in the generic hand. The print method then prints to a standard >output format and only needs overriding for sites where you >need a different output format - which sounds to be rare from >your desciption. >The generic hand class then allows you to write the resty >of the application in a generic way without worrying about >site details apart from the point where you instantiate the >hands - and even that can be data driven via an external file >or environment variable etc.. Well, I thought this would be the right approach to take given where I ultimately want to go with this. Im glad that I was thinking about this in the correct fashion. >Possibly but I would defer that decision for as long as possible! Hmm can you elaborate on this? (re: regular expressions) >You may need a pot class in the same way as the hand >above - but I'm not sure how that would workj since I don't >know anything about poker! Quickly on the format of the form of poker that I play most: No Limit Texas Hold'em Each player is dealt 2 cards face down. There are 2 forced bets called the Small Blind and Big Blind. Each player, starting to the left of the blinds can fold, call, or raise any amount. Once the action is complete, 3 cards are dealt face up(these are community cards, and are used in conjunction with the players' hole cards to make their best hand), and the betting action repeats itself, only now the Small Blind acts first. Another card is dealt face up if there 2 or more players left and the betting action occurs again. Once the action is complete then a final card is dealt and the action repeats. The remaining players then showdown their hands and the best 5 card hand wins. So a pot class would have to be able to extract the dollar amounts from each round of betting and then sum them after each betting round. This is important for talking about how hands play out, but I wont talk about why unless you are just interested. >It would be more helpful - to you and the rest of the >readership - if you keep it public. The kind of questions you >will be asking are likely to be the kind any newbie will come >across in a real project. By sharing the pain you also share >the experience. You also get access to many more heads. Thank you. I hoped to discuss it via the list but didnt want to spam the list unnecessarily. >Converting the Perl into Python shouldn't be too hard when >we get to the stage of needing to do that. For now let's start >with one site and get it working, while building in enough >flexibility for the future sites we know we need to deal with later. I just wanted to let you know that I had one in case anyone was interested in working version. Here is an interesting thing. All the converters that I know of are not stand alone apps. They are tied to forms on websites where people input their hands and then take the output to post on various popular internet poker web forums. I can provide links if anyone is interested. I wasnt necesarily wanting to convert the script, that feels a bit like cheating. >In fact maybe we should start at the end and work on the >internal data structure needed to print out the final format. >Can we define a program that can read the target format >in and print oit out in the desired format? It may sound trivial >but it gets a lot of the scaffolding in place early. I was very very happy to read this Alan. I was going to ask you in my original email if I should start with the output and work backwards. It actually gives me a lot of confidence that I seem to be thinking along the right lines here. I will start working on that and provide the list with my work on that. Thanks again Alan. Cheers, Chris --------------------------------- Blab-away for as little as 1?/min. Make PC-to-Phone Calls using Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060516/8a2e50d2/attachment.htm From sarahjm at cc.usu.edu Wed May 17 03:04:37 2006 From: sarahjm at cc.usu.edu (sarahjm at cc.usu.edu) Date: Tue, 16 May 2006 19:04:37 -0600 Subject: [Tutor] python simulations - saving state Message-ID: <1147827877.446a76a51f004@impmail.usu.edu> Hi, I am fairly new to programming in python, but for work I am running a simulation of a distribution center. What I am trying to do now is to save the state of the simulation (i.e. the event list and any other necessary variables) so that it can be "restored" later. I eventually want to be able to save the state of the simulation and restart it as well as being able to save periodically and change the event list for changes in the simulation (i.e. for a distribution center if a truck is running late and will not be arriving on time I would need to modify it's arrive time and see how that would change the execution of the rest of the simulation). I have found I can't pickle _e (the event list) and I was wondering what suggestions you could give or where I could go to get more help on this topic. Thanks, Sarah Moody From clsdaniel at gmail.com Wed May 17 05:28:14 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 16 May 2006 20:28:14 -0700 Subject: [Tutor] python simulations - saving state In-Reply-To: <1147827877.446a76a51f004@impmail.usu.edu> References: <1147827877.446a76a51f004@impmail.usu.edu> Message-ID: <4fae7dfa0605162028v525d9a33p8039900e4c8def8a@mail.gmail.com> Depends, you can pickle the list, but all objects need to be pickleable, maybe you can put up with this requeriment by changing your events to be pickleable?, but i don't know what data you store in a event or what kind of data is it. Regards On 5/16/06, sarahjm at cc.usu.edu wrote: > Hi, > > I am fairly new to programming in python, but for work I am running a simulation > of a distribution center. What I am trying to do now is to save the state of > the simulation (i.e. the event list and any other necessary variables) so that > it can be "restored" later. I eventually want to be able to save the state of > the simulation and restart it as well as being able to save periodically and > change the event list for changes in the simulation (i.e. for a distribution > center if a truck is running late and will not be arriving on time I would need > to modify it's arrive time and see how that would change the execution of the > rest of the simulation). > > I have found I can't pickle _e (the event list) and I was wondering what > suggestions you could give or where I could go to get more help on this topic. > > Thanks, > Sarah Moody > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mumufitt at gmail.com Wed May 17 08:16:39 2006 From: mumufitt at gmail.com (Mu Mu) Date: Wed, 17 May 2006 02:16:39 -0400 Subject: [Tutor] about calling external program in Python Message-ID: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> Dear all, I'm trying to call an executable program in Python. I did the following, but it doesn't work. Any help is appreciated. os.system('C:\Program Files\EPANET2\epanet2d.exe C:\simulation test\Network3_1.inp C:\simulation test\Network3_1.out') Thanks. J. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060517/8d5499f6/attachment.html From wescpy at gmail.com Wed May 17 11:03:40 2006 From: wescpy at gmail.com (w chun) Date: Wed, 17 May 2006 02:03:40 -0700 Subject: [Tutor] about calling external program in Python In-Reply-To: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> Message-ID: <78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com> > I'm trying to call an executable program in Python. I did the following, but > it doesn't work. Any help is appreciated. > > os.system('C:\Program Files\EPANET2\epanet2d.exe > C:\simulation test\Network3_1.inp C:\simulationtest\Network3_1.out') try putting an "r" in front of the string, i.e. os.system(r'C:.....). you mentioned "it doesn't work." what do you mean by that? in other words, what did the Python interpreter do... give an error, nothing, etc.? thanks, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Wed May 17 11:48:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 May 2006 05:48:23 -0400 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060516222230.15495.qmail@web52107.mail.yahoo.com> References: <20060516222230.15495.qmail@web52107.mail.yahoo.com> Message-ID: <446AF167.9040004@tds.net> Chris Delgado wrote: > Hello all, > > I have been studying python tutorials and have a couple beginning python > books that I have worked through. I have a very specific project in mind > and I want to ask a couple questions. The project in question is this: > > I am making a Hand History converter for online poker players. This > takes the textual record of how a hand played and turns into a more > readable format suitable for posting at various websites where people > discuss how the hand was played. Id like to start with the converter > working for one particular online poker site (every site formats their > hand histories somewhat differently) and expand it so that it can > recognize the site a hand history came from and format accordingly. I would pick one input format and work on a program that reads it and generates some kind of events for everything significant that happens. At first the events could be just print statements, later they can reformat the data to the required output format. From your description it sounds like there is no need to create an internal data format that holds all the data for a hand. A simple loop to read an event, parse the event and output it in the new format might be enough. It would help a lot to see some sample data. For a project of this (small) scale I don't do much design ahead of time, I let the design emerge from the code as I solve the problem. I would start by writing the simplest program that could possibly work to convert a single format. When that is working then look at what is needed to add a format. This will probably involve some refactoring, introducing functions or classes that are specific to your problems. When you have two or three formats working you should have a tool set that will make subsequent formats easier. If the data format is complex a parsing library like pyparsing might be helpful. But without seeing some data and trying to parse it there is no way to know. Kent From kent37 at tds.net Wed May 17 12:07:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 May 2006 06:07:06 -0400 Subject: [Tutor] python simulations - saving state In-Reply-To: <1147827877.446a76a51f004@impmail.usu.edu> References: <1147827877.446a76a51f004@impmail.usu.edu> Message-ID: <446AF5CA.4000809@tds.net> sarahjm at cc.usu.edu wrote: > Hi, > > I am fairly new to programming in python, but for work I am running a simulation > of a distribution center. What I am trying to do now is to save the state of > the simulation (i.e. the event list and any other necessary variables) so that > it can be "restored" later. I eventually want to be able to save the state of > the simulation and restart it as well as being able to save periodically and > change the event list for changes in the simulation (i.e. for a distribution > center if a truck is running late and will not be arriving on time I would need > to modify it's arrive time and see how that would change the execution of the > rest of the simulation). > > I have found I can't pickle _e (the event list) and I was wondering what > suggestions you could give or where I could go to get more help on this topic. What error do you get when you try to pickle _e? You might me interested in SimPy, it seems well suited for this kind of simulation: http://simpy.sourceforge.net/ Kent From amonroe at columbus.rr.com Wed May 17 12:30:44 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 17 May 2006 06:30:44 -0400 Subject: [Tutor] about calling external program in Python In-Reply-To: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> Message-ID: <104639962827.20060517063044@columbus.rr.com> > Dear all, > I'm trying to call an executable program in Python. I did the following, but > it doesn't work. Any help is appreciated. > os.system('C:\Program Files\EPANET2\epanet2d.exe C:\simulation > test\Network3_1.inp C:\simulation test\Network3_1.out') My first guess: you need quotes around paths with spaces in the names. Alan From SChitti at manh.com Wed May 17 12:15:50 2006 From: SChitti at manh.com (Suri Chitti) Date: Wed, 17 May 2006 15:45:50 +0530 Subject: [Tutor] about calling external program in Python Message-ID: Does it return any error message?? ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Mu Mu Sent: Wednesday, May 17, 2006 11:47 AM To: Tutor at python.org Subject: [Tutor] about calling external program in Python Dear all, I'm trying to call an executable program in Python. I did the following, but it doesn't work. Any help is appreciated. os.system('C:\Program Files\EPANET2\epanet2d.exe C:\simulation test\Network3_1.inp C:\simulation test\Network3_1.out') Thanks. J. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060517/4a97bf4b/attachment.htm From gabrieldain at gmail.com Wed May 17 15:06:41 2006 From: gabrieldain at gmail.com (Gabriel Dain) Date: Wed, 17 May 2006 23:06:41 +1000 Subject: [Tutor] about calling external program in Python In-Reply-To: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> Message-ID: <8c7713390605170606r6403657ax8b2e0e1c1305c576@mail.gmail.com> > os.system('C:\Program Files\EPANET2\epanet2d.exe > C:\simulation test\Network3_1.inp C:\simulation > test\Network3_1.out') have you tried the following? os.system('"C:\Program Files\EPANET2\epanet2d.exe" "C:\simulation test\Network3_1.inp" "C:\simulation test\Network3_1.out'"') -- Gabriel Dain From ulandreman at msn.com Wed May 17 17:03:43 2006 From: ulandreman at msn.com (URBAN LANDREMAN) Date: Wed, 17 May 2006 10:03:43 -0500 Subject: [Tutor] Sending e-mail msg Message-ID: I'm trying to set up a routine to send customized e-mail messages from records in a database. My first step is trying to send one simple e-mail message. After I get that figured out, I can move on to step 2. Unfortunately, when I try the example code in the tutorials for sending e-mail, I get error messages which I am unsure how to interpret. The code I use is: import smtplib fromaddr = "urban.landreman at co.hennepin.mn.us" toaddrs = "ulandreman at msn.com" # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, toaddrs)) msg = msg + "This is a test message" print "Message = " + msg print "Message length is " + repr(len(msg)) server = smtplib.SMTP('mail.hennepinPublicHealth.org') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() *** The output I get is: Message = From: urban.landreman at co.hennepin.mn.us To: ulandreman at msn.com This is a test message Message length is 89 Traceback (most recent call last): File "J:/SPSS/Python/EMailExample.py", line 14, in -toplevel- server = smtplib.SMTP('mail.hennepinPublicHealth.org') File "C:\Program Files\Python\lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "C:\Program Files\Python\lib\smtplib.py", line 307, in connect (code, msg) = self.getreply() File "C:\Program Files\Python\lib\smtplib.py", line 348, in getreply line = self.file.readline() File "C:\Program Files\Python\lib\socket.py", line 340, in readline data = self._sock.recv(self._rbufsize) error: (10054, 'Connection reset by peer') *** I also tried: server = smtplib.SMTP('localhost') with the same result. I have checked several of the tutorials and FAQ sites and the impression that's given is that this functionality is quite simple, so I assume that I'm just missing one small step. Any suggestion would be much appreciated. Thank you. Urban Landreman From stan at coll52.freeserve.co.uk Wed May 17 18:08:06 2006 From: stan at coll52.freeserve.co.uk (S W Collier) Date: Wed, 17 May 2006 17:08:06 +0100 Subject: [Tutor] Bit-level field extraction In-Reply-To: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> References: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> Message-ID: <200605171708.06512.stan@coll52.freeserve.co.uk> On Tuesday 16 May 2006 22:41, Alan Gauld wrote: > > Heh, you and me both. I cut my teeth on IBM System/370 > > assembler. Last > > time I had a job where I actually did programming as part of it, > > it was > > System/390 machine code. That's right, machine code, not > > assembler; I'd > > directly type my hexadecimal programs into low storage at the > > operator's > > console. > > Hah, if you haven't bootstrapped a VAX using the toggle switches on > the front panel you ain't a real progammer ;-) > > Actually one of our local Universities still starts their computer > science > courses by teaching students how to do that, before moving them > onto machine code, assembler, C and finally Java(*). It's like an > historical tour > of computing/programming. The machine code is done on little hex > keypads with pocket calculator style printout rools! Its only when > they > get to C that they get to use a PC! > > (*) Actually they get to choose from several languages in their 4th > (final) > year, including Lisp and Prolog(both), Haskell and PL/SQL... > They consistently produce very good graduates, so it seems to work. > > Alan G You chaps are making me nostalgic; days of the 8080A/Z80/F8/6800 when I built my first computer. In those days 2K of memory was considered large for a personal computer. Stan. From python at venix.com Wed May 17 18:24:16 2006 From: python at venix.com (Python) Date: Wed, 17 May 2006 12:24:16 -0400 Subject: [Tutor] Sending e-mail msg In-Reply-To: References: Message-ID: <1147883056.5441.87.camel@www.venix.com> On Wed, 2006-05-17 at 10:03 -0500, URBAN LANDREMAN wrote: > I'm trying to set up a routine to send customized e-mail messages from > records in a database. > My first step is trying to send one simple e-mail message. After I get that > figured out, I can move on to step 2. > > Unfortunately, when I try the example code in the tutorials for sending > e-mail, I get error messages which I am unsure how to interpret. > > The code I use is: > import smtplib > > fromaddr = "urban.landreman at co.hennepin.mn.us" > toaddrs = "ulandreman at msn.com" > # Add the From: and To: headers at the start! > msg = ("From: %s\r\nTo: %s\r\n\r\n" > % (fromaddr, toaddrs)) > msg = msg + "This is a test message" > > print "Message = " + msg > print "Message length is " + repr(len(msg)) > > server = smtplib.SMTP('mail.hennepinPublicHealth.org') > server.set_debuglevel(1) > server.sendmail(fromaddr, toaddrs, msg) > server.quit() > *** > > The output I get is: > > Message = From: urban.landreman at co.hennepin.mn.us > > To: ulandreman at msn.com > > > > This is a test message > Message length is 89 > > Traceback (most recent call last): > File "J:/SPSS/Python/EMailExample.py", line 14, in -toplevel- > server = smtplib.SMTP('mail.hennepinPublicHealth.org') > File "C:\Program Files\Python\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Program Files\Python\lib\smtplib.py", line 307, in connect > (code, msg) = self.getreply() > File "C:\Program Files\Python\lib\smtplib.py", line 348, in getreply > line = self.file.readline() > File "C:\Program Files\Python\lib\socket.py", line 340, in readline > data = self._sock.recv(self._rbufsize) > error: (10054, 'Connection reset by peer') 'Connection reset by peer' This occurs when a connection is terminated without going through the normal TCP close procedure. If localhost is giving you the same behavior, you should be able to learn why from your logs. Your code looks OK. I would expect that the issue lies with your network config or firewall(s). That mail server was happy to accept a connection from me, so I doubt if the problem is at the server. >>> import smtplib >>> c = smtplib.SMTP('mail.hennepinPublicHealth.org') >>> dir(c) ['__doc__', '__init__', '__module__', 'close', 'connect', 'data', 'debuglevel', 'docmd', 'does_esmtp', 'ehlo', 'ehlo_resp', 'esmtp_features', 'expn', 'file', 'getreply', 'has_extn', 'helo', 'helo_resp', 'help', 'local_hostname', 'login', 'mail', 'noop', 'putcmd', 'quit', 'rcpt', 'rset', 'send', 'sendmail', 'set_debuglevel', 'sock', 'starttls', 'verify', 'vrfy'] >>> c.close() > > *** > I also tried: > server = smtplib.SMTP('localhost') > > with the same result. > > I have checked several of the tutorials and FAQ sites and the impression > that's given is that this functionality is quite simple, so I assume that > I'm just missing one small step. > > Any suggestion would be much appreciated. > > Thank you. > Urban Landreman > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From etrade.griffiths at dsl.pipex.com Wed May 17 18:51:49 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Wed, 17 May 2006 17:51:49 +0100 Subject: [Tutor] unpacking PyTime Message-ID: <6.1.2.0.2.20060517173803.03afe1f0@pop.dsl.pipex.com> Hi I am using the Win32com library to pick up data from an EXCEL spreadsheet but am having trouble with dates. I want to convert a date read from the XL sheet into a float using this snippet from win32com.client import dispatch import time xlFile="test.xls" xlApp=Dispatch("Excel.Application") xlApp.Workbooks.Open(xlFile) xlSht=xlApp.Worksheets("data") # OK so far but the problem comes now ... curr_date=xlSht.Cells(1,3).Value # returns PyTime Not how to get the date (as either yy,mm,dd or a single number aka XL). The ASPN ActivePython site suggests using x=curr_date.__float__() but Python gives the error "AttributeError: __float__" I also tried x=float(curr_date) but Python gives the error "TypeError: float() argument must be string or a number". All suggestions gratefully received! From mumufitt at gmail.com Wed May 17 19:21:24 2006 From: mumufitt at gmail.com (Mu Mu) Date: Wed, 17 May 2006 13:21:24 -0400 Subject: [Tutor] about calling external program in Python In-Reply-To: <78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com> References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> <78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com> Message-ID: <2b9562040605171021k42b5b2c8v60d4952129d1240e@mail.gmail.com> Dear all, I tried the following: >>> os.system(r'C:\\simulation test\\epanet2d.exe C:\\simulation test\\Network3_1.inp C:\\simulation test\\Network3_1.out') 1 >>> os.system('C:\simulation test\epanet2d.exe C:\simulation test\Network3_1.inp C:\simulation test\Network3_1.out') 1 >>> os.system(r'C:\simulation test\epanet2d.exe C:\simulation test\Network3_1.inp C:\simulation test\Network3_1.out') 1 >>> os.system(r'"C:\simulation test\epanet2d.exe" "C:\simulation test\Network3_1.inp" "C:\simulation test\Network3_1.out"') 1 They all returned '1' in the interactive window and gave no result in the designated output folder. All I saw is a flash of the ms-dos black window and then disappeared. I tried ms-dos command line, it works pretty good. Thanks. J. On 5/17/06, w chun wrote: > > > I'm trying to call an executable program in Python. I did the following, > but > > it doesn't work. Any help is appreciated. > > > > os.system('C:\Program Files\EPANET2\epanet2d.exe > > C:\simulation test\Network3_1.inp C:\simulationtest\Network3_1.out') > > > try putting an "r" in front of the string, i.e. os.system(r'C:.....). > > you mentioned "it doesn't work." what do you mean by that? in other > words, what did the Python interpreter do... give an error, nothing, > etc.? > > thanks, > -wesley > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > 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/20060517/509897b9/attachment.htm From bgailer at alum.rpi.edu Wed May 17 19:29:39 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 17 May 2006 10:29:39 -0700 Subject: [Tutor] Bit-level field extraction In-Reply-To: <200605171708.06512.stan@coll52.freeserve.co.uk> References: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> <200605171708.06512.stan@coll52.freeserve.co.uk> Message-ID: <446B5D83.3030507@alum.rpi.edu> S W Collier wrote: > You chaps are making me nostalgic; days of the 8080A/Z80/F8/6800 when > I built my first computer. In those days 2K of memory was considered > large for a personal computer. > In 1975 Boeing Computer Services proudly announced the addition of 4 megabytes of memory to one of its IBM Mainframes runnuig VM, at a cost over $100,000! At least that reduced the spooling of virtual memory to the card punch/reader. ;-) -- Bob Gailer 510-978-4454 From carroll at tjc.com Wed May 17 19:33:34 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 17 May 2006 10:33:34 -0700 (PDT) Subject: [Tutor] Bit-level field extraction In-Reply-To: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> Message-ID: On Tue, 16 May 2006, Alan Gauld wrote: > Hah, if you haven't bootstrapped a VAX using the toggle switches on > the front panel you ain't a real progammer ;-) Not with a VAX, but I had to do that with a TI-980, long, long ago! And once I had it booted, because the assembler was a pretty primitive two-pass assembler, I had to run my punched cards through twice. But at least I got to use punched cards. I forget what the other system we had in that room was, but I had to use paper tape on that one. > Actually one of our local Universities still starts their computer > science courses by teaching students how to do that, before moving them > onto machine code, assembler, C and finally Java(*). It's like an > historical tour of computing/programming.... They consistently produce > very good graduates, so it seems to work. I wonder if the results are good because it's an effective teaching method, of because it culls out the faint-of-heart right up front! > The machine code is done on little hex keypads with pocket calculator > style printout rools! Its only when they get to C that they get to use a > PC! A couple years ago, I took a course in which I built my own computer. And I mean built. The individual chips (CPU, RAM, resistors, etc.) were off-the-shelf components, but that's it. I soldered every lead and wire-wrapped every wire on that thing, build on a breadboard. It was very primitive: its only input devices were an 8-bit DIP switch and thermometer sensor chip (and a flashable EEPROM to hold the OS/program, if you count that as an input device); and its only output devices a couple of seven-segment LED displays; but it sure taught the hard-core hardware. I didn't actually need it for the subject matter taught; but I'm planning on taking the patent agent's exam, and the US patent and trademark office insisted I shore up my academic credentials with a few additional physics courses (the course was actually about physic laboratory instrumentation). It was quite a bit of fun, though. From bgailer at alum.rpi.edu Wed May 17 20:11:41 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 17 May 2006 11:11:41 -0700 Subject: [Tutor] unpacking PyTime In-Reply-To: <6.1.2.0.2.20060517173803.03afe1f0@pop.dsl.pipex.com> References: <6.1.2.0.2.20060517173803.03afe1f0@pop.dsl.pipex.com> Message-ID: <446B675D.80801@alum.rpi.edu> Etrade Griffiths wrote: > Hi > > I am using the Win32com library to pick up data from an EXCEL spreadsheet > but am having trouble with dates. I want to convert a date read from the > XL sheet into a float using this snippet > > from win32com.client import dispatch > import time > > xlFile="test.xls" > xlApp=Dispatch("Excel.Application") > xlApp.Workbooks.Open(xlFile) > xlSht=xlApp.Worksheets("data") > > # OK so far but the problem comes now ... > > curr_date=xlSht.Cells(1,3).Value # returns PyTime > > Not how to get the date (as either yy,mm,dd or a single number aka > XL). The ASPN ActivePython site suggests using > It appears that the ActivePython docs may be wrong, as the only method I see for a PyTime object is Format. Looking up Format leads to curr_date.Format("%y,%m,%d") to get yy,mm,dd. Or you can, as the ActivePython docs suggest, use int(curr_date) to get an integer value which you can then float. -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Wed May 17 20:38:20 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 May 2006 19:38:20 +0100 Subject: [Tutor] Bit-level field extraction References: <002f01c67931$6f3f84f0$0c01a8c0@XPpro> Message-ID: > But at least I got to use punched cards. I forget what the other > system > we had in that room was, but I had to use paper tape on that one. I've never actually used punch cards. But I have used punch tape. Where a loop really was a loop! :-) We used them to transmit source code from our punch tape writer at high school to the local university mainframe. It ran the programs overnight and they posted back all the output in an envelope which we received 2 days later - the edit-run-debug cycle-time encouraged very rigorous code reviews!! You don't want to wait 3 days to discover a syntax error in line 1. Alan G. From alan.gauld at btinternet.com Wed May 17 20:43:36 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 May 2006 19:43:36 +0100 Subject: [Tutor] about calling external program in Python References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com><78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com> <2b9562040605171021k42b5b2c8v60d4952129d1240e@mail.gmail.com> Message-ID: "Mu Mu" wrote in message news:2b9562040605171021k42b5b2c8v60d4952129d1240e at mail.gmail.com... > I tried the following: > >>> os.system(r'C:\\simulation test\\epanet2d.exe C:\\simulation > test\\Network3_1.inp C:\\simulation test\\Network3_1.out') > 1 Any non zero return value means that an error occurred. The os.system call worked and the OS returned an error, which usually means you got a path wrong or the user running puython doesn't have access rights to the executable. > They all returned '1' in the interactive window and gave no result > in the > designated output folder. All I saw is a flash of the ms-dos black > window > and then disappeared. > > I tried ms-dos command line, it works pretty good. What happens if you try it from the Start->Run dialog? The CMD box may have some environment settings that are missing when Python runs. Alan G. From mumufitt at gmail.com Wed May 17 21:09:35 2006 From: mumufitt at gmail.com (Mu Mu) Date: Wed, 17 May 2006 15:09:35 -0400 Subject: [Tutor] about calling external program in Python In-Reply-To: References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com> <78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com> <2b9562040605171021k42b5b2c8v60d4952129d1240e@mail.gmail.com> Message-ID: <2b9562040605171209i7dcfaf48k1688b611d98a503@mail.gmail.com> I redid the following: import os import sys sys.path.append('C:\Program Files\EPANET2') os.system('epanet2d.exe C:\simulation_test\Network3_1.inp C:\simulation_test\Network3_1.out') and safed this as test.py In the Pythonwin interface to run. I got nothing. Then I added 'C:\Program Files\EPANET2' into the system path. In the cmd line: I typed python c:\test.py. It ran and then gave the output. Don' t know why command line works. but pythonwin interface failed . Thanks. J. On 5/17/06, Alan Gauld wrote: > > "Mu Mu" wrote in message > news:2b9562040605171021k42b5b2c8v60d4952129d1240e at mail.gmail.com... > > I tried the following: > > >>> os.system(r'C:\\simulation test\\epanet2d.exe C:\\simulation > > test\\Network3_1.inp C:\\simulation test\\Network3_1.out') > > 1 > > Any non zero return value means that an error occurred. > The os.system call worked and the OS returned an error, which > usually means you got a path wrong or the user running puython > doesn't have access rights to the executable. > > > They all returned '1' in the interactive window and gave no result > > in the > > designated output folder. All I saw is a flash of the ms-dos black > > window > > and then disappeared. > > > > I tried ms-dos command line, it works pretty good. > > What happens if you try it from the Start->Run dialog? > The CMD box may have some environment settings that are missing > when Python runs. > > Alan G. > > > > _______________________________________________ > 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/20060517/f158bb47/attachment.html From etrade.griffiths at dsl.pipex.com Wed May 17 21:43:05 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Wed, 17 May 2006 20:43:05 +0100 Subject: [Tutor] unpacking PyTime In-Reply-To: <446B675D.80801@alum.rpi.edu> References: <6.1.2.0.2.20060517173803.03afe1f0@pop.dsl.pipex.com> <446B675D.80801@alum.rpi.edu> Message-ID: <6.1.2.0.2.20060517204103.03af3a40@pop.dsl.pipex.com> Bob I was looking at http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/PyTime.html To my untrained eye it looks like there are a number of functions for PyTime objects (eg __int__, __hash__ etc). However, I tried int(curr_date) and it seems to work OK - thanks! At 19:11 17/05/2006, Bob Gailer wrote: >Etrade Griffiths wrote: >>Hi >> >>I am using the Win32com library to pick up data from an EXCEL spreadsheet >>but am having trouble with dates. I want to convert a date read from the >>XL sheet into a float using this snippet >> >>from win32com.client import dispatch >>import time >> >>xlFile="test.xls" >>xlApp=Dispatch("Excel.Application") >>xlApp.Workbooks.Open(xlFile) >>xlSht=xlApp.Worksheets("data") >> >># OK so far but the problem comes now ... >> >>curr_date=xlSht.Cells(1,3).Value # returns PyTime >> >>Not how to get the date (as either yy,mm,dd or a single number aka >>XL). The ASPN ActivePython site suggests using >> >It appears that the ActivePython docs may be wrong, as the only method I >see for a PyTime object is Format. Looking up Format leads to >curr_date.Format("%y,%m,%d") to get yy,mm,dd. > >Or you can, as the ActivePython docs suggest, use int(curr_date) to get an >integer value which you can then float. > >-- >Bob Gailer >510-978-4454 From prowlerslim at yahoo.com Wed May 17 22:38:45 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Wed, 17 May 2006 13:38:45 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446AF167.9040004@tds.net> Message-ID: <20060517203845.46798.qmail@web52111.mail.yahoo.com> Kent, Thanks for the reply. "I would pick one input format and work on a program that reads it and generates some kind of events for everything significant that happens. At first the events could be just print statements, later they can reformat the data to the required output format. From your description it sounds like there is no need to create an internal data format that holds all the data for a hand. A simple loop to read an event, parse the event and output it in the new format might be enough. It would help a lot to see some sample data. For a project of this (small) scale I don't do much design ahead of time, I let the design emerge from the code as I solve the problem. I would start by writing the simplest program that could possibly work to convert a single format. When that is working then look at what is needed to add a format. This will probably involve some refactoring, introducing functions or classes that are specific to your problems. When you have two or three formats working you should have a tool set that will make subsequent formats easier. If the data format is complex a parsing library like pyparsing might be helpful. But without seeing some data and trying to parse it there is no way to know." Here is a sample hand history. Failure To Launch 8161071-72989 Holdem No Limit $0.50/$1 [May 17 03:26:33] : Hand Start. [May 17 03:26:33] : Seat 1 : bnb3 has $92.50 [May 17 03:26:33] : Seat 2 : pineaa has $15.25 [May 17 03:26:33] : Seat 3 : prowlerslim has $107.50 [May 17 03:26:33] : Seat 4 : Marcelluz has $174.74 [May 17 03:26:33] : Seat 5 : texredfsh has $35.25 [May 17 03:26:33] : Seat 6 : aloo has $98.37 [May 17 03:26:33] : aloo is the dealer. [May 17 03:26:34] : bnb3 posted small blind. [May 17 03:26:34] : pineaa posted big blind. [May 17 03:26:34] : Game [72989] started with 6 players. [May 17 03:26:34] : Dealing Hole Cards. [May 17 03:26:34] : Seat 3 : prowlerslim has Ah Kc [May 17 03:26:38] : prowlerslim called $1 and raised $4 [May 17 03:26:41] : Marcelluz folded. [May 17 03:26:44] : texredfsh called $5 [May 17 03:26:46] : aloo called $5 [May 17 03:26:49] : bnb3 folded. [May 17 03:26:52] : pineaa folded. [May 17 03:26:53] : Dealing flop. [May 17 03:26:53] : Board cards [Kd Td 5d] [May 17 03:27:01] : prowlerslim bet $10 [May 17 03:27:04] : texredfsh called $10 [May 17 03:27:06] : aloo folded. [May 17 03:27:07] : Dealing turn. [May 17 03:27:07] : Board cards [Kd Td 5d 3c] [May 17 03:27:14] : prowlerslim bet $21 [May 17 03:27:19] : texredfsh folded. [May 17 03:27:20] : prowlerslim wins $34.75 as the last player standing [May 17 03:27:22] : Hand is over. Im trying to work this out as we speak but not getting too far at the moment. I'll keep plugging along --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060517/74fa1a9c/attachment.htm From alan.gauld at freenet.co.uk Wed May 17 23:05:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 17 May 2006 22:05:06 +0100 Subject: [Tutor] about calling external program in Python References: <2b9562040605162316v6f54abaes8257725b35dea3bf@mail.gmail.com><78b3a9580605170203l491dca2bl30a539ae66e3db02@mail.gmail.com><2b9562040605171021k42b5b2c8v60d4952129d1240e@mail.gmail.com> <2b9562040605171209i7dcfaf48k1688b611d98a503@mail.gmail.com> Message-ID: <002701c679f5$92fe0ff0$0c01a8c0@XPpro> I think you may be confiused about sys.path. ------------------------ import os import sys sys.path.append('C:\Program Files\EPANET2') os.system('epanet2d.exe C:\simulation_test\Network3_1.inp C:\simulation_test\Network3_1.out') ---------------------- sys.path is the path that Python uses to look for python modules. It has nothing to do with the PATH environment variable used by the OS to find executables. > In the Pythonwin interface to run. I got nothing. > Then I added 'C:\Program Files\EPANET2' into the system path. Do you mean the OS system PATH? > In the cmd line: I typed python c:\test.py. It ran and then gave the > output. > Don' t know why command line works. but pythonwin interface failed . If you are doing what I think rthen Pythonwin doesn't see the PATH but The cmd line will use the PATH environment variable to find the executable. Alan G. From kent37 at tds.net Thu May 18 01:13:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 May 2006 19:13:24 -0400 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060517203845.46798.qmail@web52111.mail.yahoo.com> References: <20060517203845.46798.qmail@web52111.mail.yahoo.com> Message-ID: <446BAE14.5090404@tds.net> Chris Delgado wrote: > Here is a sample hand history. > > Failure To Launch 8161071-72989 Holdem No Limit $0.50/$1 > [May 17 03:26:33] : Hand Start. > [May 17 03:26:33] : Seat 1 : bnb3 has $92.50 > [May 17 03:26:33] : Seat 2 : pineaa has $15.25 > [May 17 03:26:33] : Seat 3 : prowlerslim has $107.50 > [May 17 03:26:33] : Seat 4 : Marcelluz has $174.74 > [May 17 03:26:33] : Seat 5 : texredfsh has $35.25 > [May 17 03:26:33] : Seat 6 : aloo has $98.37 > [May 17 03:26:33] : aloo is the dealer. > [May 17 03:26:34] : bnb3 posted small blind. > [May 17 03:26:34] : pineaa posted big blind. > [May 17 03:26:34] : Game ...etc > > Im trying to work this out as we speak but not getting too far at the moment. I'll keep plugging > along OK, just looking at this, I'm guessing that you might want some kind of data to represent the players, maybe something to represent the pot, maybe something to represent the cards on the table. It really depends on what kind of output you want to get from this. Can you post an example of the desired output? I can see sort of an event-driven parser where each line is an input event. You could have a list of pairs of regular expressions and functions. The code would run down the list of regexes, if one matches, call the function passing it the match object. The function parses the specific line and calls an event handler in an output object. By separating the parser from the output handler, you can write a new parser for a different input format and (in theory) use the same output handler. It's easier to show than to explain. Here is a simple example to parse the data above: import re class Handler(object): ''' This class receives parsed events. It creates any needed data structures and writes the desired output format. This class is independent of the source format. This version just prints the events; the real Handler will be more interesting. ''' def start(self): print 'Game started' def assign_seat(self, num, name, amt): print '%s in seat %s has $%.2f' % (name, num, amt) def set_dealer(self, dealer): print 'dealer is %s' % dealer def set_big_blind(self, player): print 'big blind is %s' % player def set_small_blind(self, player): print 'small blind is %s' % player class Parser(object): ''' This class parses the source data. It interprets the data and generates callback events to the output handler. This class doesn't know anything about the output format. ''' def __init__(self, handler): self.handler = handler self.regexes = [ (r'Hand Start', self.start), (r'Seat (\d+) : (\w+) has \$([\d.]+)', self.assign_seat), (r'(\w+) is the dealer', self.set_dealer), (r'(\w+) posted small blind', self.set_small_blind), (r'(\w+) posted big blind', self.set_big_blind), ] def parse(self, lines): for line in lines: for regex, func in self.regexes: match = re.search(regex, line) if match: func(match) def start(self, match): self.handler.start() def assign_seat(self, match): num, name, dollars = match.group(1, 2, 3) num = int(num) dollars = float(dollars) self.handler.assign_seat(num, name, dollars) def set_dealer(self, match): self.handler.set_dealer(match.group(1)) def set_small_blind(self, match): self.handler.set_small_blind(match.group(1)) def set_big_blind(self, match): self.handler.set_big_blind(match.group(1)) # Some test data data = '''Failure To Launch 8161071-72989 Holdem No Limit $0.50/$1 [May 17 03:26:33] : Hand Start. [May 17 03:26:33] : Seat 1 : bnb3 has $92.50 [May 17 03:26:33] : Seat 2 : pineaa has $15.25 [May 17 03:26:33] : Seat 3 : prowlerslim has $107.50 [May 17 03:26:33] : Seat 4 : Marcelluz has $174.74 [May 17 03:26:33] : Seat 5 : texredfsh has $35.25 [May 17 03:26:33] : Seat 6 : aloo has $98.37 [May 17 03:26:33] : aloo is the dealer. [May 17 03:26:34] : bnb3 posted small blind. [May 17 03:26:34] : pineaa posted big blind. [May 17 03:26:34] : Game '''.splitlines() # Make a handler handler = Handler() # Make a parser and feed it the data Parser(handler).parse(data) Kent From mahansen at adelphia.net Thu May 18 02:39:51 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 17 May 2006 18:39:51 -0600 Subject: [Tutor] Tutor FAQ Message-ID: <2104bfe707141a87d49bf8befd5c0b8f@adelphia.net> Here's a small batch of questions/answers for the tutor FAQ. Let me know if you have any corrections or clarifications. I'll post them to the web site in a couple of days. Mike --------------------------------------------------------------------- How much code should I post? Post as much relevent code as you can. However, the consensus seems to be that the more code you post, the less likely you'll get someone to review it. A max of 100 lines is suggested. If you have more code, you might post your code at http://www.rafb.net/paste or a similar site. --------------------------------------------------------------------- How do I dynamically name my objects? How do I name my objects based on user input? Rather than performing voodoo by dynamically creating variables, your best bet is to use a dictionary with the keys being the name of the object or user input and the values being the objects. --------------------------------------------------------------------- Why doesn't my special method add, init, or cmp.. work? Remember to use two underscores before and after the method name __add__, __init__, __cmp__. From prowlerslim at yahoo.com Thu May 18 03:09:26 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Wed, 17 May 2006 18:09:26 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446BAE14.5090404@tds.net> Message-ID: <20060518010926.67625.qmail@web52108.mail.yahoo.com> Kent, >OK, just looking at this, I'm guessing that you might want some kind of >data to represent the players, maybe something to represent the pot, >maybe something to represent the cards on the table. It really depends >on what kind of output you want to get from this. Can you post an >example of the desired output? Here is an example of the type of output I am looking for. First here is the hand history I used(slightly different then the othe format I showed you) ***** Hand History for Game 3736569968 ***** $100 NL Texas Hold'em - Monday, March 13, 22:21:11 ET 2006 Table Table 97262 (No DP) (Real Money) Seat 4 is the button Total number of players : 6 Seat 2: xxxdoinkxxx ( $133.90 ) Seat 3: zinc25 ( $57.08 ) Seat 4: UltimateGW ( $143.50 ) Seat 6: Dewez ( $101.85 ) Seat 1: vulturesrow ( $115.75 ) Seat 5: TableATM ( $69 ) TableATM posts small blind [$0.50]. Dewez is sitting out. vulturesrow posts big blind [$1]. ** Dealing down cards ** Dealt to vulturesrow [ Kd Kc ] Dewez has left the table. xxxdoinkxxx calls [$1]. zinc25 folds. UltimateGW folds. TableATM folds. vulturesrow raises [$3]. xxxdoinkxxx calls [$3]. ** Dealing Flop ** [ 9d, 5c, 3h ] vulturesrow checks. xxxdoinkxxx checks. ** Dealing Turn ** [ 5h ] >You have options at Clementson (No DP) Table!. vulturesrow bets [$6]. xxxdoinkxxx calls [$6]. ** Dealing River ** [ 8s ] >You have options at Clementson (No DP) Table!. NL_DERB has joined the table. vulturesrow bets [$15]. xxxdoinkxxx raises [$30]. vulturesrow calls [$15]. xxxdoinkxxx shows [ Qd, Kh ] a pair of fives. vulturesrow shows [ Kd, Kc ] two pairs, kings and fives. vulturesrow wins $78.50 from the main pot with two pairs, kings and fives. >You have options at Clementson (No DP) Table!. Then I ran through a converter located here: http://www.neildewhurst.com/hand-converter/ Party Poker No Limit Holdem Ring game Blinds: $0.50/$1 6 players [url=http://www.neildewhurst.com/hand-converter]Converter[/url] [b]Stack sizes:[/b] UTG: $133.90 UTG+1: $57.08 CO: $143.50 Button: $69 SB: $101.85 Hero: $115.75 [b]Pre-flop:[/b] ([i]6 players[/i]) Hero is BB with K:diamond: K:club: UTG calls, [i]3 folds[/i], [color:#cc0000]Hero raises to $3[/color], UTG calls. [b]Flop:[/b] 9:diamond: 5:club: 3:heart: ([i]$6.5, 3 players[/i]) Hero checks, UTG checks. [b]Turn:[/b] 5:heart: ([i]$6.5, 3 players[/i]) [color:#cc0000]Hero bets $6[/color], UTG calls. [b]River:[/b] 8:spade: ([i]$18.5, 3 players[/i]) [color:#cc0000]Hero bets $15[/color], [color:#cc0000]UTG raises to $30[/color], Hero calls. [b]Results:[/b] Final pot: $78.5 [color:#ffffff]UTG shows Qd Kh [/color] [color:#ffffff]Hero shows Kd Kc [/color] I wont lie, I found your "simple" example a bit mind blowing, maybe I need to work through some more tutorials lol. Still plugging away, thanks so much for helping this novice out. Cheers, Chris --------------------------------- New Yahoo! Messenger with Voice. Call regular phones from your PC and save big. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060517/627b9677/attachment.htm From kent37 at tds.net Thu May 18 03:41:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 May 2006 21:41:59 -0400 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060518010926.67625.qmail@web52108.mail.yahoo.com> References: <20060518010926.67625.qmail@web52108.mail.yahoo.com> Message-ID: <446BD0E7.2040206@tds.net> Chris Delgado wrote: > Here is an example of the type of output I am looking for. OK, I think you have your work cut out for you :-) I still think my basic approach can work but the output handler is going to have to keep track of a fair amount of stuff as it gets parse events. The good news is you can build it up a line at a time - start with a program that converts the first line correctly, then make it two lines, etc. > I wont lie, I found your "simple" example a bit mind blowing, maybe I > need to work through some more tutorials lol. Still plugging away, > thanks so much for helping this novice out. Yes, it uses a lot of...hmm...at least novice-level concepts - cooperating classes, regular expressions and first-class functions, for a few. You said you have read a couple of books and you seemed at least comfortable with the idea that you might need classes and regular expressions so I didn't explain it much. Feel free to ask questions about the parts you don't understand. I wonder if maybe you need to write some code? You talk about *reading* but you haven't mentioned *writing*. You can't learn to program without writing programs - that would be like learning to write a foreign language by reading books in the language - it helps but it won't get you there! So if you have just been reading, I suggest you try writing a few small programs as warmups. Good luck! Kent From kieran.flanagan at gmail.com Thu May 18 18:15:24 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Thu, 18 May 2006 17:15:24 +0100 Subject: [Tutor] Amara pushbind to retrieve data from Xml Doc Message-ID: Hey I am pretty new to Python ( about a day old ). I am currently writing a small script to just cycle through an XML page and retrieve data if it exists. So for example an extract from the Xml page will have an element tagged entry like so I want this data I can use the following loop to list out all element.name, element.type and element.originalValue like so for subtree in binderytools.pushbind('/screen/panel/list/row/element', source=xmlfile): print subtree.originalValue source=xmlfile is just referencing a variable I have set to point to the actual xml page. How can I change the above loop to cycle through each , check if data exists like above and print this out. Any help would be appreciated. Thanks k -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/aeb9783b/attachment.htm From emmatata at hotmail.com Thu May 18 19:19:00 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Thu, 18 May 2006 13:19:00 -0400 Subject: [Tutor] New Programmer using Python and ArcGIS Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/bd760c40/attachment.html From prowlerslim at yahoo.com Fri May 19 01:19:08 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Thu, 18 May 2006 16:19:08 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446BD0E7.2040206@tds.net> Message-ID: <20060518231908.81014.qmail@web52111.mail.yahoo.com> Kent, Thanks once again. "I wonder if maybe you need to write some code? You talk about *reading* but you haven't mentioned *writing*. You can't learn to program without writing programs - that would be like learning to write a foreign language by reading books in the language - it helps but it won't get you there! So if you have just been reading, I suggest you try writing a few small programs as warmups." I think you are right on the money here. I need to write some more simple stuff. I did work through the books but I wrote very little on my own, just sort of followed along and said "Oh that makes sense". So I decided to go through the practice exercises in the book and then post here with any problems. SO here is my first stab and I keep getting a syntax error in my first if statement. The = sign is highlighted and I cant figure out what is wrong. Im almost embarassed to mail this. # A program that simulates flipping a coin 100 times and the reports the number of heads and tails that were flipped# import random heads = 0 tails = 0 flips = 0 if flips <= 100: coin = random.randrange(2) if coin = 0: heads += elif coin = 1: tails += flips +=1 print "The coin was flipped 100 times and it was heads" + heads + "times and tails" + tails + "times!" raw_input("\n\nPress the Enter key to exit") THanks, Chris --------------------------------- New Yahoo! Messenger with Voice. Call regular phones from your PC and save big. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/411b9c54/attachment.html From prowlerslim at yahoo.com Fri May 19 01:19:49 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Thu, 18 May 2006 16:19:49 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446BD0E7.2040206@tds.net> Message-ID: <20060518231949.81523.qmail@web52114.mail.yahoo.com> Kent, Thanks once again. "I wonder if maybe you need to write some code? You talk about *reading* but you haven't mentioned *writing*. You can't learn to program without writing programs - that would be like learning to write a foreign language by reading books in the language - it helps but it won't get you there! So if you have just been reading, I suggest you try writing a few small programs as warmups." I think you are right on the money here. I need to write some more simple stuff. I did work through the books but I wrote very little on my own, just sort of followed along and said "Oh that makes sense". So I decided to go through the practice exercises in the book and then post here with any problems. SO here is my first stab and I keep getting a syntax error in my first if statement. The = sign is highlighted and I cant figure out what is wrong. Im almost embarassed to mail this. # A program that simulates flipping a coin 100 times and the reports the number of heads and tails that were flipped# import random heads = 0 tails = 0 flips = 0 if flips <= 100: coin = random.randrange(2) if coin = 0: heads += elif coin = 1: tails += flips +=1 print "The coin was flipped 100 times and it was heads" + heads + "times and tails" + tails + "times!" raw_input("\n\nPress the Enter key to exit") THanks, Chris --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/403c5074/attachment.htm From jfabiani at yolo.com Fri May 19 01:45:43 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 18 May 2006 16:45:43 -0700 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060518231949.81523.qmail@web52114.mail.yahoo.com> References: <20060518231949.81523.qmail@web52114.mail.yahoo.com> Message-ID: <200605181645.43733.jfabiani@yolo.com> On Thursday 18 May 2006 16:19, Chris Delgado wrote: > import random > > heads = 0 > tails = 0 > flips = 0 > > if flips <= 100: > > ? ? coin = random.randrange(2) > > ? ? if coin = 0: > ? ? ? ? heads += > ? ? elif coin = 1: > ? ? ? ? tails += > > ? ? flips +=1 > > print "The coin was flipped 100 times and it was heads" + heads + "times > and tails" + tails + "times!" > > raw_input("\n\nPress the Enter key to exit") I think you want '==' and not '='. Look up assignment and equal! John From prowlerslim at yahoo.com Fri May 19 02:44:43 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Thu, 18 May 2006 17:44:43 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <200605181645.43733.jfabiani@yolo.com> Message-ID: <20060519004443.15686.qmail@web52111.mail.yahoo.com> johnf, Yup, I actually thought that might be my mistake but I forgot to actually try it. So I did and revised the code (which I'll post below) and now get a syntax error after my heads += line..yikes . # A program that simulates flipping a coin 100 times and the reports the number of heads and tails that were flipped# import random heads = 0 tails = 0 flips = 0 if flips <= 100: coin = random.randrange(2) if coin == 0: heads += else: tails += flips += 1 print "The coin was flipped 100 times and it was heads" + heads + "times and tails" + tails + "times!" raw_input("\n\nPress the Enter key to exit") johnf wrote: On Thursday 18 May 2006 16:19, Chris Delgado wrote: > import random > > heads = 0 > tails = 0 > flips = 0 > > if flips <= 100: > > coin = random.randrange(2) > > if coin = 0: > heads += > elif coin = 1: > tails += > > flips +=1 > > print "The coin was flipped 100 times and it was heads" + heads + "times > and tails" + tails + "times!" > > raw_input("\n\nPress the Enter key to exit") I think you want '==' and not '='. Look up assignment and equal! John _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Be a chatter box. Enjoy free PC-to-PC calls with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/053b5167/attachment.html From bgailer at alum.rpi.edu Fri May 19 03:08:44 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 18 May 2006 18:08:44 -0700 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060519004443.15686.qmail@web52111.mail.yahoo.com> References: <20060519004443.15686.qmail@web52111.mail.yahoo.com> Message-ID: <446D1A9C.6010102@alum.rpi.edu> Chris Delgado wrote: > johnf, > > Yup, I actually thought that might be my mistake but I forgot to > actually try it. So I did and revised the code (which I'll post below) > and now get a syntax error after my heads += line..yikes . > > # A program that simulates flipping a coin 100 times and the reports > the number of heads and tails that were flipped# > > import random > > heads = 0 > tails = 0 > flips = 0 > > if flips <= 100: > > coin = random.randrange(2) > > if coin == 0: > heads += > else: > tails += > > flips += 1 > > print "The coin was flipped 100 times and it was heads" + heads + > "times and tails" + tails + "times!" > > raw_input("\n\nPress the Enter key to exit") Good - you wrote it. Did you run it? Because there are several things that will lead to "compile errors" and "execution errors". I hope you run it and think about the errors, then if stumped ask us. -- Bob Gailer 510-978-4454 From prowlerslim at yahoo.com Fri May 19 03:26:03 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Thu, 18 May 2006 18:26:03 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446D1A9C.6010102@alum.rpi.edu> Message-ID: <20060519012603.91154.qmail@web52105.mail.yahoo.com> Bob et al, Ok guys, program is all fixed up and runs well. HEre is the final code. Thanks for the help and its on to the next prog. Thanks for the patience and help! Chris # A program that simulates flipping a coin 100 times and the reports the number of heads and tails that were flipped# import random heads = 0 tails = 0 flips = 0 while flips < 100: coin = random.randrange(2) if coin == 0: heads += 1 else: tails += 1 flips += 1 print "The coin was flipped 100 times and it was heads " +str(heads)+ " times and tails " + str(tails) + " times!" raw_input("\n\nPress the Enter key to exit") --------------------------------- Love cheap thrills? Enjoy PC-to-Phone calls to 30+ countries for just 2?/min with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/7bf22832/attachment.htm From bgailer at alum.rpi.edu Fri May 19 04:05:03 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 18 May 2006 19:05:03 -0700 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060519012603.91154.qmail@web52105.mail.yahoo.com> References: <20060519012603.91154.qmail@web52105.mail.yahoo.com> Message-ID: <446D27CF.5000800@alum.rpi.edu> Chris Delgado wrote: > Bob et al, > > Ok guys, program is all fixed up and runs well. HEre is the final > code. Thanks for the help and its on to the next prog. Thanks for the > patience and help! > > Chris > > # A program that simulates flipping a coin 100 times and the reports > the number of heads and tails that were flipped# > > import random > > heads = 0 > tails = 0 > flips = 0 > > while flips < 100: > > coin = random.randrange(2) > > if coin == 0: > heads += 1 > else: > tails += 1 > > flips += 1 > > print "The coin was flipped 100 times and it was heads " +str(heads)+ > " times and tails " + str(tails) + " times!" > > raw_input("\n\nPress the Enter key to exit") Congrats! Now consider some "simplifications": import random heads = 0 for flips in range(1,101): heads += random.randrange(2) print "The coin was flipped %s times and it was heads %s times and tails %s times!" % (flips, heads, flips - heads) raw_input("\n\nPress the Enter key to exit") -- Bob Gailer 510-978-4454 From prowlerslim at yahoo.com Fri May 19 06:35:53 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Thu, 18 May 2006 21:35:53 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <446D27CF.5000800@alum.rpi.edu> Message-ID: <20060519043553.92369.qmail@web52115.mail.yahoo.com> Bob, Thanks for the input. I was trying to stick to the lessons in the chapter whose problems I was working on and so I knew using a for loop might be a bit better, I decided to stick with the stuff from the chapter. I do like the way you simplified using the random function, very clever. I need to start thinking like that. Thanks again, I'll have more questions soon I'm sure! Chris Bob Gailer wrote: Chris Delgado wrote: > Bob et al, > > Ok guys, program is all fixed up and runs well. HEre is the final > code. Thanks for the help and its on to the next prog. Thanks for the > patience and help! > > Chris > > # A program that simulates flipping a coin 100 times and the reports > the number of heads and tails that were flipped# > > import random > > heads = 0 > tails = 0 > flips = 0 > > while flips < 100: > > coin = random.randrange(2) > > if coin == 0: > heads += 1 > else: > tails += 1 > > flips += 1 > > print "The coin was flipped 100 times and it was heads " +str(heads)+ > " times and tails " + str(tails) + " times!" > > raw_input("\n\nPress the Enter key to exit") Congrats! Now consider some "simplifications": import random heads = 0 for flips in range(1,101): heads += random.randrange(2) print "The coin was flipped %s times and it was heads %s times and tails %s times!" % (flips, heads, flips - heads) raw_input("\n\nPress the Enter key to exit") -- Bob Gailer 510-978-4454 --------------------------------- Be a chatter box. Enjoy free PC-to-PC calls with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060518/f00e20b6/attachment.html From kieran.flanagan at gmail.com Fri May 19 11:50:21 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Fri, 19 May 2006 10:50:21 +0100 Subject: [Tutor] httpFetch Usage Message-ID: Hi, Does anyone know where I can get some info on the funtion httpFetch. Its being imported and used in a file I am adding code to and I would like to understand what it does. An example of its usage: response = httpFetch.httpFetch(url, sessionID, someValue) Thanks Kieran -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060519/41c1ebc0/attachment.htm From kent37 at tds.net Fri May 19 12:25:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 May 2006 06:25:29 -0400 Subject: [Tutor] httpFetch Usage In-Reply-To: References: Message-ID: <446D9D19.2070800@tds.net> kieran flanagan wrote: > Hi, > > Does anyone know where I can get some info on the funtion httpFetch. Its > being imported and used in a file I am adding code to and I would like > to understand what it does. An example of its usage: > > response = httpFetch.httpFetch(url, sessionID, someValue) httpFetch is not part of the standard library. Do you know who wrote it or where it came from? If it is written in Python you should have the source code for the module. Try this in the interactive interpreter to locate the file: import httpFetch print httpFetch.__file__ This may print the path to a .pyc file; look in the same directory for the corresponding .py file. You can also try help(httpFetch) help(httpFetch.httpFetch) dir(httpFetch) Kent From kabads at gmail.com Fri May 19 12:46:58 2006 From: kabads at gmail.com (Adam Cripps) Date: Fri, 19 May 2006 11:46:58 +0100 Subject: [Tutor] Lists of lists - different sized lists Message-ID: I'm trying to sort [1] a list of people randomly into groups. My guess is that a list of lists will do the trick here. However, the randrange fails with an empty range. How can I check for this? I thought that my pupils list wouldn't reach zero with the while len(pupils)>0: would keep it above 0. Any help or advice would be appreciated. TIA Adam [1] def groups(pupils, size): toplist = [] tmplist = [] print len(tmplist) while len(pupils)>0: print len(pupils) while len(tmplist)<=size: print "tmplist is ", len (tmplist) #How many pupils are we talking about here? listlength = pupilslength(pupils) rand1 = random.randrange(listlength) tmplist.append(pupils[rand1]) pupils.pop(rand1) toplist.append(tmplist) tmplist = [] for i in toplist: print i print i -- http://www.monkeez.org PGP key: 0x7111B833 From alan.gauld at freenet.co.uk Fri May 19 12:54:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 19 May 2006 11:54:19 +0100 Subject: [Tutor] New programmer, need some help getting started on my first project References: <20060519043553.92369.qmail@web52115.mail.yahoo.com> Message-ID: <005d01c67b32$94cb23c0$0c01a8c0@XPpro> Chris, > I do like the way you simplified using the random function, > I need to start thinking like that. It is quite clever but quite a subtle twist for a beginner to think of. However even in your version there is a pattern you should look out for: >> coin = random.randrange(2) >> if coin == 0: >> heads += 1 >> else: >> tails += 1 If you assign a value to a variable (ie coin) and then only ever use that variable in the test of a simple if/else construct then you can always eliminate the assignment: if random.randrange(2): tails += 1: else: heads += 1 Bob's trick works because you always get 0 or 1 back, but this shortcut works for any two way check, even ranges: if somefunc() > keyvalue: # do greater than action else: # do other action The caveat is where you need to use the test value inside the if/else and then you do need to explicitly make the assignment. >> print "The coin was flipped 100 times and it was heads " >> +str(heads)+ >> " times and tails " + str(tails) + " times!" Also you don't need to use str() in. Python to proint things because print implicitly calls the string conversion for you. >>> print 5,'+',4,'=',5+4 5 + 4 = 9 Note that it also inserts spaces between the valiues. For more control use the string formatting technique that Bob demonstrated. Looking for these common shortcuts or idioms is a big part of gaining experience with any language. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri May 19 14:08:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 May 2006 08:08:29 -0400 Subject: [Tutor] Lists of lists - different sized lists In-Reply-To: References: Message-ID: <446DB53D.5050002@tds.net> Adam Cripps wrote: > I'm trying to sort [1] a list of people randomly into groups. My guess > is that a list of lists will do the trick here. However, the randrange > fails with an empty range. How can I check for this? I thought that my > pupils list wouldn't reach zero with the while len(pupils)>0: would > keep it above 0. You don't show the pupilslength() function so I will assume it is just returning len(pupils). One problem is if len(pupils) < size you will exhaust the pupils list before you fill tmplist. This will happen in the inner loop so the test for len(pupils) > 0 will not be reached. One option would be to test len(pupils) > 0 again in the condition for the inner loop. BTW you can just test 'if pupils:' rather than 'if len(pupils) > 0:' Kent > > Any help or advice would be appreciated. > > TIA > Adam > > [1] > def groups(pupils, size): > toplist = [] > tmplist = [] > print len(tmplist) > while len(pupils)>0: > print len(pupils) > while len(tmplist)<=size: > print "tmplist is ", len (tmplist) > #How many pupils are we talking about here? > listlength = pupilslength(pupils) > rand1 = random.randrange(listlength) > tmplist.append(pupils[rand1]) > pupils.pop(rand1) > toplist.append(tmplist) > tmplist = [] > for i in toplist: > print i > print i From carroll at tjc.com Fri May 19 19:43:33 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 19 May 2006 10:43:33 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: <20060518231949.81523.qmail@web52114.mail.yahoo.com> Message-ID: On Thu, 18 May 2006, Chris Delgado wrote: > Kent, > > So if you have just been reading, I suggest you try writing a few small > programs as warmups." > > I think you are right on the money here. I need to write some more > simple stuff. Chris, I'd also suggest that, once you have a few toy programs (like your coin-tosser) under your belt, you find some *small* task that you actually want to accomplish, and use Python for that. It's both motivating and satisfying to address some real-life need you have, rather than some arbitrary assignment from a book. I think my very first Python program was to do something like take a comma-separated list of MP3 files, with the directory name in a form that includes artist name and album or collection, and format it as a hierarchical list, because I wanted to see it that way. It was more fun to work on a program that actually did something I wanted, and I had a purpose in writing it beyond just learning Python. (Of course, I look back at that code now, and it sure is ugly; but it worked!) From bgailer at alum.rpi.edu Fri May 19 20:23:12 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 19 May 2006 11:23:12 -0700 Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: References: Message-ID: <446E0D10.8090805@alum.rpi.edu> Terry Carroll wrote: > On Thu, 18 May 2006, Chris Delgado wrote: > > >> Kent, >> >> So if you have just been reading, I suggest you try writing a few small >> programs as warmups." >> >> I think you are right on the money here. I need to write some more >> simple stuff. >> > > Chris, I'd also suggest that, once you have a few toy programs (like your > coin-tosser) under your belt, you find some *small* task that you actually > want to accomplish, and use Python for that. > > It's both motivating and satisfying to address some real-life need you > have, rather than some arbitrary assignment from a book. > > I think my very first Python program was to do something like take a > comma-separated list of MP3 files, with the directory name in a form that > includes artist name and album or collection, and format it as a > hierarchical list, because I wanted to see it that way. > > It was more fun to work on a program that actually did something I wanted, > and I had a purpose in writing it beyond just learning Python. My first "real" program was an interface to an Oracle application that included generating anonymous PL/SQL blocks, passing them to Oracle, retrieving results, launching and monitoring Oracle background processes. A rather daunting task, but it was fun, relatively easy in Python, and certainly helped me get into Python. The hardest part was wading thru Oracle tech support, and dealing with error messages such as "invalid type or number of parameters" in a call that involved many parameters. :'( -- Bob Gailer 510-978-4454 From nosracb at yahoo.com Fri May 19 22:03:35 2006 From: nosracb at yahoo.com (Bill Carson) Date: Fri, 19 May 2006 13:03:35 -0700 (PDT) Subject: [Tutor] Fwd: How do you create built-in objects (dicts, lists, etc) without specifying {}, [], etc... Message-ID: <20060519200335.7925.qmail@web38112.mail.mud.yahoo.com> Note: forwarded message attached. __________________________________________________ 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/20060519/1e3181e9/attachment.html -------------- next part -------------- An embedded message was scrubbed... From: Bill Carson Subject: How do you create built-in objects (dicts, lists, etc) without specifying {}, [], etc... Date: Fri, 19 May 2006 13:00:49 -0700 (PDT) Size: 2397 Url: http://mail.python.org/pipermail/tutor/attachments/20060519/1e3181e9/attachment.mht From kent37 at tds.net Fri May 19 23:06:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 May 2006 17:06:19 -0400 Subject: [Tutor] Fwd: How do you create built-in objects (dicts, lists, etc) without specifying {}, [], etc... In-Reply-To: <20060519200335.7925.qmail@web38112.mail.mud.yahoo.com> References: <20060519200335.7925.qmail@web38112.mail.mud.yahoo.com> Message-ID: <446E334B.3010202@tds.net> Bill Carson wrote: > Do you know how to create instances of dictionaries, lists, integers, > longs, etc without having to specify it in code... > > Instead of specifying: > a={"bla":1} > or ... > a=[1,2,3] > > Is there another way?? I'm not really sure what you are looking for here. You can use the type names to create new objects: a = dict(bla=1) or a = dict() a['bla'] = 1 a = list() a.append(1) a.append(2) a.append(3) > The "new" module does not appear to create built-in types, or am I wrong. > I've read something about "type objects", but I don't know how to > instantiate them outside of specifying them as python syntax embedded in > code (see examples above). If you could do what you want, what would it look like? (In other words, make up some syntax and show us.) Why do you want to do this? Kent From SNelson at midway.com Fri May 19 23:29:31 2006 From: SNelson at midway.com (Nelson, Scott) Date: Fri, 19 May 2006 16:29:31 -0500 Subject: [Tutor] Getting current class method name Message-ID: <64F7B8E2954C73499806C1E59A848C1D09BD30C6@CHICAGO-EX1.chicago.midway.com> Ok, I'm looking to create a quick debug function that prints out the current function that is running (to help in debugging what functions are being run). I know that I can use a debugger to get a stack trace (and I do), but I'm still curious about this problem. Here's what I've got so far: def Foo(): PrintCurFunc() class cBase: def Run(self): PrintCurFunc(self) class cChild(cBase): pass import traceback def PrintCurFunc(obj = None): stack = traceback.extract_stack() scriptName, lineNum, funcName, lineOfCode = stack[-2] if obj: print '%s.%s()' % (obj.__class__.__name__, funcName) else: print '%s()' % funcName def main(): Foo() b = cBase() c = cChild() b.Run() c.Run() x = cTwo() x.Run() if __name__ == '__main__': main() The output I get is: Foo() cBase.Run() cChild.Run() cTwo.Run() cTwo.Run() Now, PrintCurFunc() above gets me the output I want in the fist two cases (Foo() and cBase.Run()). But, in the case of c.Run(), I would still like to see it output cBase.Run(), since that is the method that is being run. Yes, cChild being derived from cBase does have an inherited Run method, but I would like my output to display "where the code physically lives" so that for debugging I can basically get a stack trace to see what is executed when. It might be more clear in this example: class cOne: def Run(self): PrintCurFunc(self) class cTwo(cOne): def Run(self): PrintCurFunc(self) cOne.Run(self) x = cTwo() x.Run() gets me the output of: cTwo.Run() cTwo.Run() when I would prefer it output: cTwo.Run() cOne.Run() ...which reflects the call stack more clearly. Now, I've looked into the traceback module but was only able to find the name of the function. Passing self into PrintCurFunc was my attempt at getting at the class name. But, as you see, it obviously returns the object's class name and not the class name the function was defined on. I also looked at this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 but it only gives me a function name and not the class name as well. Any thoughts? I'm a bit new to Python's reflection features... Thanks tons! -Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060519/f1b71853/attachment.html From emmatata at hotmail.com Sat May 20 01:48:11 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Fri, 19 May 2006 19:48:11 -0400 Subject: [Tutor] Please help!! Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060519/4bcad361/attachment.html From h.finucane at gmail.com Sat May 20 02:42:25 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Fri, 19 May 2006 17:42:25 -0700 Subject: [Tutor] Tkinter pass-by-reference query Message-ID: While attempting to add images to a canvas programmatically, I wrote the following: for i in os.listdir('./icons/terrain'): self.terrainScreen["height"] = str(int(self.terrainScreen["height"])+50) debug(self.terrainScreen["height"]+" height of terrainScreen",5) img = PhotoImage(file='./icons/terrain/'+i) self.terrainScreen.create_image(int(self.terrainScreen["height"])-50,(int(self.terrainScreen["height"])-50), image=img,tag=None) I couldn't figure out why it didn't work, until I went in and played with Tkinter in the python shell, and I came to the conclusion that the reason nothing was displayed on the canvas was that images are passed by reference. In other words, unless there is a permanent `img' variable, the data disappears. For example (replace w\ your own gifs): >>> from Tkinter import * >>> root = Tk() >>> terrain = Canvas(root,width=50,height=50) >>> img = PhotoImage(file='MapEditor/icons/terrain/desert.gif') >>> terrain.create_image(0,0,image=img) 1 >>> terrain.pack() Works beautifully, eh? >>> img = PhotoImage(file='MapEditor/icons/terrain/water.gif') Doh! Now it disappears! >>> terrain.create_image(0,50,image=img) 2 Working, but there is only one image >>> terrain.create_image(0,0,image=PhotoImage('MapEditor/icons/terrain/grass.gif')) 3 Nothing gets displayed. So there is my problem, and what is, I'm fairly certain, the cause of the problem. Unfortunately, I really have no idea what the proper solution should be. I'd like to populate the canvas programmatically, but my brain seems to be choking on possible solutions. Suggestions? Can I force variables to be passed by value? -- --H.F. My penguin is bigger than yours, mister... From h.finucane at gmail.com Sat May 20 02:46:28 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Fri, 19 May 2006 17:46:28 -0700 Subject: [Tutor] Please help!! In-Reply-To: References: Message-ID: On 5/19/06, MATATA EMMANUEL wrote: > > > > Hi there, Hi! > > I'm tasked to write a Paython script which is supposed to hit a web site and > download a shapefile from that web site. Cool. Look at urllib in your python documentation. > I don't have any clue and Me neither :) > would like your help. I use 9.x if this matter. 9.x what? Python has yet to release 2.6, if I'm not mistaken. > > Thank you. > > Matt. Good luck. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- --H.F. My penguin is bigger than yours, mister... From bernd at prager.ws Sat May 20 02:33:26 2006 From: bernd at prager.ws (Bernd Prager) Date: Fri, 19 May 2006 20:33:26 -0400 Subject: [Tutor] Please help!! In-Reply-To: References: Message-ID: <446E63D6.6020400@prager.ws> Hey Matata, >From the website http://www.boddie.org.uk/python/HTML.html: import urllib # Get a file-like object for the Python Web site's home page. f = urllib.urlopen("http://www.python.org") # Read from the object, storing the page's contents in 's'. s = f.read() f.close() Hope this helps, -- Bernd MATATA EMMANUEL wrote: > > Hi there, > > I'm tasked to write a Paython script which is supposed to hit a web > site and download a shapefile from that web site. I don't have any > clue and would like your help. I use 9.x if this matter. > > Thank you. > > Matt. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From prowlerslim at yahoo.com Sat May 20 03:45:44 2006 From: prowlerslim at yahoo.com (Chris Delgado) Date: Fri, 19 May 2006 18:45:44 -0700 (PDT) Subject: [Tutor] New programmer, need some help getting started on my first project In-Reply-To: Message-ID: <20060520014544.81152.qmail@web52101.mail.yahoo.com> Terry, Thank you for the suggestions. I am going to stick with these little toy programs as you aptly put them to make sure I have a good grasp on the basics. I completely agree with you that I need to do something that I want to solve a problem with and in fact, thats whats motivated me to find and join this list. Unfortunately, it woudl appear I attempted to bit off more than I could chew. Part of the problem with writing to solve things is that there is just about something for everything out there right now! I did recently convert my old laptop over to Linux so hopefully as I mess around with that I will find some things that I can focus my attentions on. Thanks for taking the time to respond. Cheers, Chris Terry Carroll wrote: On Thu, 18 May 2006, Chris Delgado wrote: > Kent, > > So if you have just been reading, I suggest you try writing a few small > programs as warmups." > > I think you are right on the money here. I need to write some more > simple stuff. Chris, I'd also suggest that, once you have a few toy programs (like your coin-tosser) under your belt, you find some *small* task that you actually want to accomplish, and use Python for that. It's both motivating and satisfying to address some real-life need you have, rather than some arbitrary assignment from a book. I think my very first Python program was to do something like take a comma-separated list of MP3 files, with the directory name in a form that includes artist name and album or collection, and format it as a hierarchical list, because I wanted to see it that way. It was more fun to work on a program that actually did something I wanted, and I had a purpose in writing it beyond just learning Python. (Of course, I look back at that code now, and it sure is ugly; but it worked!) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Be a chatter box. Enjoy free PC-to-PC calls with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060519/616ab467/attachment.htm From kent37 at tds.net Sat May 20 06:01:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 May 2006 00:01:43 -0400 Subject: [Tutor] Tkinter pass-by-reference query In-Reply-To: References: Message-ID: <446E94A7.1010709@tds.net> Henry Finucane wrote: > While attempting to add images to a canvas programmatically, I wrote > the following: > for i in os.listdir('./icons/terrain'): > self.terrainScreen["height"] = str(int(self.terrainScreen["height"])+50) > debug(self.terrainScreen["height"]+" height of terrainScreen",5) > img = PhotoImage(file='./icons/terrain/'+i) > self.terrainScreen.create_image(int(self.terrainScreen["height"])-50,(int(self.terrainScreen["height"])-50), > image=img,tag=None) > > I couldn't figure out why it didn't work, until I went in and played > with Tkinter in the python shell, and I came to the conclusion that > the reason nothing was displayed on the canvas was that images are > passed by reference. In other words, unless there is a permanent `img' > variable, the data disappears. For some reason Tkinter doesn't keep a reference to the image you pass it. So when your reference goes out of scope, the image is garbage-collected and can no longer be displayed. The solution, as you have found, is to keep a reference to the image somewhere. It can be in a variable, or you could make a list of images. Kent From alan.gauld at freenet.co.uk Sat May 20 14:12:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 20 May 2006 13:12:23 +0100 Subject: [Tutor] Tkinter pass-by-reference query References: Message-ID: <001f01c67c06$a6d62d60$0202fea9@XPpro> > While attempting to add images to a canvas programmatically, I wrote > the following: > for i in os.listdir('./icons/terrain'): > ... img = PhotoImage(file='./icons/terrain/'+i) > self.terrainScreen.create_image(int(self.terrainScreen["height"])-50, > > (int(self.terrainScreen["height"])-50), > image=img,tag=None) > with Tkinter in the python shell, and I came to the conclusion that > the reason nothing was displayed on the canvas was that images are > passed by reference. Everything in Python is passed by reference. The issue here is that one the reference goes out of scope the image object gets garbage collected! > In other words, unless there is a permanent `img' variable, the data > disappears. >For example (replace w\ your own gifs): >>> from Tkinter import * >>> root = Tk() >>> terrain = Canvas(root,width=50,height=50) >>> img = PhotoImage(file='MapEditor/icons/terrain/desert.gif') >>> terrain.create_image(0,0,image=img) >Works beautifully, eh? >>> img = PhotoImage(file='MapEditor/icons/terrain/water.gif') > Doh! Now it disappears! You've crated a new image object but you need to pass that to the canvas, or more easily... Try configuring the file property of the image: img.configure(file='MapEditor/icons/terrain/water.gif') That changes the file used by the image object that is being displayed. The image object is a placeholder within your GUI for displaying graphics. You only need one object because you are onmly displaying one image (at a time) in the GUI. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat May 20 14:15:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 20 May 2006 13:15:41 +0100 Subject: [Tutor] Please help!! References: Message-ID: <002b01c67c07$1d13ccd0$0202fea9@XPpro> > I'm tasked to write a Paython script which is supposed to hit > a web site and download a shapefile from that web site. The urllib module should do that for you but... > I don't have any clue and would like your help. What do you know? Do you understand HTML? and specifically how to create and read img tags? Do you know any Python? Do you know any other programming language? > I use 9.x if this matter. Version 9.x of what? Operating System - on a Mac perhaps? If so it shouldn't matter since Python's urllib works OK on the older versions. We really need a liittle more background to help further. HTH, Alan G. From h.finucane at gmail.com Sat May 20 17:04:05 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Sat, 20 May 2006 08:04:05 -0700 Subject: [Tutor] Tkinter pass-by-reference query In-Reply-To: <001f01c67c06$a6d62d60$0202fea9@XPpro> References: <001f01c67c06$a6d62d60$0202fea9@XPpro> Message-ID: Thanks for your help, I've gotten it to work. On 5/20/06, Alan Gauld wrote: > > While attempting to add images to a canvas programmatically, I wrote > > the following: > > for i in os.listdir('./icons/terrain'): > > ... img = PhotoImage(file='./icons/terrain/'+i) > > self.terrainScreen.create_image(int(self.terrainScreen["height"])-50, > > > > (int(self.terrainScreen["height"])-50), > > image=img,tag=None) > > > with Tkinter in the python shell, and I came to the conclusion that > > the reason nothing was displayed on the canvas was that images are > > passed by reference. > > Everything in Python is passed by reference. The issue here is that > one the reference goes out of scope the image object gets garbage > collected! > > > In other words, unless there is a permanent `img' variable, the data > > disappears. > > >For example (replace w\ your own gifs): > >>> from Tkinter import * > >>> root = Tk() > >>> terrain = Canvas(root,width=50,height=50) > >>> img = PhotoImage(file='MapEditor/icons/terrain/desert.gif') > >>> terrain.create_image(0,0,image=img) > > >Works beautifully, eh? > > >>> img = PhotoImage(file='MapEditor/icons/terrain/water.gif') > > > Doh! Now it disappears! > > You've crated a new image object but you need to pass that to > the canvas, or more easily... > Try configuring the file property of the image: > > img.configure(file='MapEditor/icons/terrain/water.gif') > > That changes the file used by the image object that is being > displayed. > > The image object is a placeholder within your GUI for displaying > graphics. You only need one object because you are onmly displaying > one image (at a time) in the GUI. > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > -- --H.F. My penguin is bigger than yours, mister... From alan.gauld at freenet.co.uk Sat May 20 18:58:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 20 May 2006 17:58:20 +0100 Subject: [Tutor] Please help!! References: Message-ID: <000301c67c2e$99133330$0202fea9@XPpro> [CCing back to list] > I know HTML even if I haven't used it for sometimes. I Also know > couple other programming languages (Visual basic, some C++). > I just taken a Python course of writting Python scripts for ArcGIS > so that if you sent me a script, I will be able to understand it. OK, now we know the background we know where to pitch the reply. I don't have a script that will do exactly what you want but someone else posted a snippet showing how to use urllib. If you need to parse the html that you read from urllib then you might find BeautifulSoup worth a look. http://www.crummy.com/software/BeautifulSoup/ It makes extracting elements from html fairly painless. But if its easy to find a simple search of the string for the img tag may suffice. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > From: "Alan Gauld" > To: "MATATA EMMANUEL" , > Subject: Re: [Tutor] Please help!! > Date: Sat, 20 May 2006 13:15:41 +0100 > >>I'm tasked to write a Paython script which is supposed to hit a > web >>site and download a shapefile from that web site. > > > >The urllib module should do that for you but... > > > >>I don't have any clue and would like your help. > > > >What do you know? > >Do you understand HTML? and specifically how to create and read > img >tags? > > > >Do you know any Python? Do you know any other programming > language? > > > >>I use 9.x if this matter. > > > >Version 9.x of what? > >Operating System - on a Mac perhaps? > >If so it shouldn't matter since Python's urllib works OK on the > >older versions. > > > >We really need a liittle more background to help further. > > > >HTH, > > > >Alan G. > > > From emmatata at hotmail.com Sat May 20 19:36:23 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Sat, 20 May 2006 13:36:23 -0400 Subject: [Tutor] Please help!! In-Reply-To: <000301c67c2e$99133330$0202fea9@XPpro> Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060520/b45a5d8e/attachment.html From alan.gauld at freenet.co.uk Sat May 20 20:39:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 20 May 2006 19:39:25 +0100 Subject: [Tutor] Please help!! References: Message-ID: <000301c67c3c$b83ee750$0202fea9@XPpro> > Man! I was thinking that it was simple. This is a little bit hard > but will try to make sense of it as I can. OK, the way this list operates is that you try to solve it yourself. When it doesn't work you tell us what you tried to do and what went wrong. We then try to point you in the right direction. > Thank you for your assistance. I'm glad you're up there to assist. The tutor list are all here waiting to help. We are like any good teacher, we don't just give answers out will-nilly but we do try to steer you to the solution so that you understand it for the future. If you do have a problem post the code that causes the problem and also paste in any error messages you get - the whoile error not just the last line. Have a go, let us see what is sticking you, we are here to help, Alan G From andrew.arobert at gmail.com Sat May 20 23:43:43 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 20 May 2006 17:43:43 -0400 Subject: [Tutor] File encoding strategy question Message-ID: <446F8D8F.60603@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi everyone, I am in the process of creating a file transmit/receiver program using MQSeries. The way it works is through creation of an XML message. Elements within the XML message contain things such as file name, size, and the file contents. The file contents are encoded, currently using Base64, for support of both binary and text data. This works great but there is a small rub to the problem. I would like to be able to view the contents of the file if it is text while still maintaining the ability to transmit binary data. Does anyone know of an encoding format that would make this possible? The viewing of the file contents does not need to be perfect, merely enough that a particular in-transit file could be identified. Thoughts on this would be greatly appreciated. - -- Thank you, Andy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEb42PDvn/4H0LjDwRAq7DAKC4o5NwKOx9vDYB71C0hcoRiyDIuQCgrQVE 4s4r2BnmgAR728PuZow6vHU= =RT23 -----END PGP SIGNATURE----- From isha at MIT.EDU Sun May 21 03:21:06 2006 From: isha at MIT.EDU (Ishwinder Kaur Banga) Date: Sat, 20 May 2006 21:21:06 -0400 Subject: [Tutor] question about ic.py on Mac OS X Message-ID: MAC OS version 10.4.6 Python Version 2.4.1 Problem is that the url is valid but the python icglue tells me that it is not found Please help Error -------------------- Traceback (most recent call last): File "dialect.py", line 166, in ? test("http://diveintopython.org/odbchelper_list.html") File "dialect.py", line 163, in test webbrowser.open_new(outfile) File "/usr/local/lib/python2.4/webbrowser.py", line 46, in open_new get().open(url, 1) File "/usr/local/lib/python2.4/webbrowser.py", line 315, in open ic.launchurl(url) File "/usr/local/lib/python2.4/plat-mac/ic.py", line 235, in launchurl return _dft_ic.launchurl(url, hint) File "/usr/local/lib/python2.4/plat-mac/ic.py", line 202, in launchurl self.ic.ICLaunchURL(hint, url, 0, len(url)) MacOS.Error: (-673, 'no URL found') ------------------- From kent37 at tds.net Sun May 21 15:27:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 May 2006 09:27:53 -0400 Subject: [Tutor] Please help!! In-Reply-To: References: Message-ID: <44706AD9.1060807@tds.net> MATATA EMMANUEL wrote: > Alan, > > Man! I was thinking that it was simple. This is a little bit hard but > will try to make sense of it as I can. How would you fetch the shapefile with your browser? Is there a url to download the file? It's pretty simple to fetch a web page or other resource from a URL and save it to a local file. urllib.urlretrieve() will do it. If you have to authenticate (login) to the web site it gets a little more complex. urllib2 is similar to urllib but it has more options and supports authentication. There is a tutorial for urllib2 here: http://www.voidspace.org.uk/python/articles/urllib2.shtml Kent > > Thank you for your assistance. I'm glad you're up there to assist. > > Matt > > > > > > ------------------------------------------------------------------------ > From: /"Alan Gauld" / > To: /"MATATA EMMANUEL" / > CC: // > Subject: /Re: [Tutor] Please help!!/ > Date: /Sat, 20 May 2006 17:58:20 +0100/ > >[CCing back to list] > > > >>I know HTML even if I haven't used it for sometimes. I Also know > >>couple other programming languages (Visual basic, some C++). > >>I just taken a Python course of writting Python scripts for ArcGIS > >>so that if you sent me a script, I will be able to understand it. > > > >OK, now we know the background we know where to pitch the reply. > >I don't have a script that will do exactly what you want but someone > >else posted a snippet showing how to use urllib. > > > >If you need to parse the html that you read from urllib then you > >might > >find BeautifulSoup worth a look. > > > >http://www.crummy.com/software/BeautifulSoup/ > > > >It makes extracting elements from html fairly painless. > > > >But if its easy to find a simple search of the string for the img > >tag > >may suffice. > > > >HTH, > > > >Alan Gauld > >Author of the Learn to Program web site > >http://www.freenetpages.co.uk/hp/alan.gauld > > > >> > >> From: "Alan Gauld" > >> To: "MATATA EMMANUEL" , > >> Subject: Re: [Tutor] Please help!! > >> Date: Sat, 20 May 2006 13:15:41 +0100 > >> >>I'm tasked to write a Paython script which is supposed to hit a > >>web >>site and download a shapefile from that web site. > >> > > >> >The urllib module should do that for you but... > >> > > >> >>I don't have any clue and would like your help. > >> > > >> >What do you know? > >> >Do you understand HTML? and specifically how to create and read > >>img >tags? > >> > > >> >Do you know any Python? Do you know any other programming > >>language? > >> > > >> >>I use 9.x if this matter. > >> > > >> >Version 9.x of what? > >> >Operating System - on a Mac perhaps? > >> >If so it shouldn't matter since Python's urllib works OK on the > >> >older versions. > >> > > >> >We really need a liittle more background to help further. > >> > > >> >HTH, > >> > > >> >Alan G. > >> > > >> > > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Mon May 22 05:06:45 2006 From: carroll at tjc.com (Terry Carroll) Date: Sun, 21 May 2006 20:06:45 -0700 (PDT) Subject: [Tutor] OT: any good newsgroup or other forum for MP3 internals discussions? Message-ID: I apologize for this off-topic question -- the only real connection to Python is that I'm using Python as my programming language. I'm writing a program to analyze an MP3 file's contents. I need to find a newsgroup or other forum to ask some questions about file format internals. Nothing's jumping out at me, looking through the list of usenet newsgroups. I've found dozens of sites with relevant specifications, but am looking at one or two rogue files where either I'm misunderstanding the specs, or the file is nonconformant (but some MP3 programs can read them, so I'm betting it's me). Any suggestions? From emmatata at hotmail.com Mon May 22 15:58:04 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 09:58:04 -0400 Subject: [Tutor] User input Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/afb6820e/attachment.html From ewald.ertl at hartter.com Mon May 22 16:17:42 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 22 May 2006 16:17:42 +0200 Subject: [Tutor] User input In-Reply-To: References: Message-ID: <4471C806.2060503@hartter.com> MATATA EMMANUEL wrote: > Hi there, > > Can anyone tell me how I'm having trouble executing this piece of code: > > mpg = raw_input (" Enter your mileage:") > distance = raw_input ("Enter your distance:") > galon_price = raw_input ("Enter you cost per gallon:") > make = "Honda" > model = "Accord" > ## > print make, model, "mileage is", mpg, "miles per gallon" > print "Total trip cost is US$", distance / (mpg * gallon_price) > > I get this error when I run it: > > print "Total trip cost is US$", distance / (mpg * gallon_price) > TypeError: unsupported operand type(s) for * > The type which raw_input() returns is a string, so '120'*'5' multiplies two strings. Perhaps you can convert your input to a type you need. ( e.g. float ), but you have to check for a ValueError-Exception if the conversion fails. HTH Ewald From kpvincent at yahoo.com Mon May 22 16:19:12 2006 From: kpvincent at yahoo.com (Kelly Vincent) Date: Mon, 22 May 2006 15:19:12 +0100 (BST) Subject: [Tutor] User input In-Reply-To: Message-ID: <20060522141912.1908.qmail@web53402.mail.yahoo.com> raw_input reads in the value as a string, so you need to convert it at some point to a number. You can either do this at the point where you read the value in, or when you do the calculation/print. To convert it at the input stage (probably the most logical), add float() such as mpg = float(raw_input (" Enter your mileage:")) instead of mpg = raw_input (" Enter your mileage:") Or you can do it in the print statement: print "Total trip cost is US$", float(distance) / (float(mpg) * float(galon_price)) HTH --- MATATA EMMANUEL wrote: --------------------------------- Hi there, Can anyone tell me how I'm having trouble executing this piece of code: mpg = raw_input (" Enter your mileage:") distance = raw_input ("Enter your distance:") galon_price = raw_input ("Enter you cost per gallon:") make = "Honda" model = "Accord" ## print make, model, "mileage is", mpg, "miles per gallon" print "Total trip cost is US$", distance / (mpg * gallon_price) I get this error when I run it: print "Total trip cost is US$", distance / (mpg * gallon_price) TypeError: unsupported operand type(s) for * Matt > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ulandreman at msn.com Mon May 22 16:43:47 2006 From: ulandreman at msn.com (URBAN LANDREMAN) Date: Mon, 22 May 2006 09:43:47 -0500 Subject: [Tutor] User input In-Reply-To: Message-ID: You had a typo with the variable 'gallon_price' and your formula for the total cost was incorrect. Adding float() for the raw_input helps. This code gets you closer: mpg = float(raw_input ("Enter your mileage:")) distance = float(raw_input ("Enter your distance:")) gallon_price = float(raw_input ("Enter you cost per gallon:")) make = "Honda" model = "Accord" ## print make, model, "mileage is", mpg, "miles per gallon" print "Total trip cost is US$" , distance * gallon_price/mpg Others who are more experienced may have suggestions for more elegant code. Urban Landreman >From: "MATATA EMMANUEL" >To: Tutor at python.org >Subject: [Tutor] User input >Date: Mon, 22 May 2006 09:58:04 -0400 >MIME-Version: 1.0 >X-Originating-IP: [199.90.217.113] >X-Originating-Email: [emmatata at hotmail.com] >X-Sender: emmatata at hotmail.com >Received: from bay0-mc9-f10.bay0.hotmail.com ([65.54.245.18]) by >bay0-imc2-s36.bay0.hotmail.com with Microsoft SMTPSVC(6.0.3790.1830); Mon, >22 May 2006 07:01:58 -0700 >Received: from smtp-vbr15.xs4all.nl ([194.109.24.35]) by >bay0-mc9-f10.bay0.hotmail.com with Microsoft SMTPSVC(6.0.3790.1830); Mon, >22 May 2006 07:01:48 -0700 >Received: from bag.python.org (bag.python.org [194.109.207.14])by >smtp-vbr15.xs4all.nl (8.13.6/8.13.6) with ESMTP id k4MDwC09055356;Mon, 22 >May 2006 15:58:12 +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 803111E4016;Mon, 22 May 2006 15:58:11 +0200 (CEST) >Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) >with ESMTP id A42201E4007for ; Mon, 22 May 2006 15:58:09 >+0200 (CEST) >Received: from bag (HELO bag.python.org) (127.0.0.1)by bag.python.org with >SMTP; 22 May 2006 15:58:09 +0200 >Received: from hotmail.com (bay107-f11.bay107.hotmail.com [64.4.51.21])by >bag.python.org (Postfix) with ESMTPfor ; Mon, 22 May 2006 >15:58:08 +0200 (CEST) >Received: from mail pickup service by hotmail.com with Microsoft >SMTPSVC;Mon, 22 May 2006 06:58:07 -0700 >Received: from 64.4.51.220 by by107fd.bay107.hotmail.msn.com with HTTP;Mon, >22 May 2006 13:58:04 GMT >X-Message-Info: LsUYwwHHNt1YS4l5TKo3dHnFdM1dcnJLvFKeEzvkf14= >X-Original-To: Tutor at python.org >Delivered-To: tutor at bag.python.org >X-Spam-Status: OK 0.075 >X-OriginalArrivalTime: 22 May 2006 13:58:07.0284 >(UTC)FILETIME=[C0B69740:01C67DA7] >X-BeenThere: tutor at python.org >X-Mailman-Version: 2.1.7 >Precedence: list >List-Id: Discussion for learning programming with Python >List-Unsubscribe: >, >List-Archive: >List-Post: >List-Help: >List-Subscribe: >, >Errors-To: tutor-bounces at python.org >X-Virus-Scanned: by XS4ALL Virus Scanner >Return-Path: tutor-bounces at python.org > > > >Hi there, > >Can anyone tell me how I'm having trouble executing this piece of code: > >mpg = raw_input (" Enter your mileage:") >distance = raw_input ("Enter your distance:") >galon_price = raw_input ("Enter you cost per gallon:") >make = "Honda" >model = "Accord" >## >print make, model, "mileage is", mpg, "miles per gallon" >print "Total trip cost is US$", distance / (mpg * gallon_price) > > >I get this error when I run it: > >print "Total trip cost is US$", distance / (mpg * gallon_price) >TypeError: unsupported operand type(s) for * > > > >Matt > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From emmatata at hotmail.com Mon May 22 16:43:56 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 10:43:56 -0400 Subject: [Tutor] User input In-Reply-To: <20060522141912.1908.qmail@web53402.mail.yahoo.com> Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/9552a4e5/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon May 22 17:28:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 May 2006 08:28:33 -0700 (PDT) Subject: [Tutor] User input In-Reply-To: References: Message-ID: > The second version works. > > print "Total trip cost is US$", float(distance) / > (float(mpg) * float(galon_price)) Hi Matt, Although this works, we'll probably want to do the type conversions as early as possible. We can write a function input_float() that wraps up the float(raw_input()) stuff: ################################### def input_float(prompt): return float(raw_input(prompt)) ################################### If we have this as a helper function, then we don't have to worry about sprinkling float() conversions all over the place. From andrew.arobert at gmail.com Mon May 22 19:31:36 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 13:31:36 -0400 Subject: [Tutor] Problem with a class Message-ID: <4471F578.90003@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, I am getting an odd traceback when using a class. The class I am using is class TriggerMessage: def __init__(self,data): """ Unpacks the passed binary data based on the MQTCM2 format dictated in the MQ Application Programming Reference """ self.data=data self.structid=None self.version=None self.qname=None self.procname=None self.trigdata=None self.appltype=None self.applid=None self.envdata=None self.userdata=None Self.qmgr=None def decode(self): format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) self.structid, self.version, self.qname, self.processname, \ self.triggerdata, self.appltype, self.applid, \ self.envdata, self.userdata, self.qmgr \ = struct.unpack(format,self.data) When I try to reference the class with the following statement: test = TriggerMessage.decode(data) I get the following traceback Traceback (most recent call last): File "m:\mq\mq\scripts\receiver.py", line 238, in ? test = TriggerMessage.decode(data) TypeError: unbound method decode() must be called by TriggerMessage instance as first argument (got str instance instead) Does this make any sense? The variable data passed to the class is valid and is used elsewhere correctly. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEcfV4Dvn/4H0LjDwRAo9XAJ4viu2SxR50Mgl4DWucJs0+l84r+gCgkcMy xs+li5sUfKpz1fgAPw5PhuE= =9IHp -----END PGP SIGNATURE----- From carroll at tjc.com Mon May 22 19:38:22 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 22 May 2006 10:38:22 -0700 (PDT) Subject: [Tutor] Problem with a class In-Reply-To: <4471F578.90003@gmail.com> Message-ID: On Mon, 22 May 2006, Andrew Robert wrote: > class TriggerMessage: > > def __init__(self,data): This suggests that it's to be invoked along the lines of: foo = TriggerMessage(data) > def decode(self): And this as: bar = foo.decode() > test = TriggerMessage.decode(data) I think you wanted something like: test1 = TriggerMessage(data) test2 = test1.decode() From emmatata at hotmail.com Mon May 22 20:03:09 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 14:03:09 -0400 Subject: [Tutor] Download file from the web and store it locally. Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/c41728a7/attachment.html From english_summer_rain01 at yahoo.com Mon May 22 20:17:20 2006 From: english_summer_rain01 at yahoo.com (Joe F) Date: Mon, 22 May 2006 11:17:20 -0700 (PDT) Subject: [Tutor] help...newbie Message-ID: <20060522181721.41802.qmail@web39211.mail.mud.yahoo.com> Hello, I am pretty sure I am sending this to the right email address. But anyway I need help. I started learning python, and I wanna know how to make a simple program, that displays text and when the user presses enter more text is displayed. And so and so until the end. Thank you, joe. --------------------------------- Love cheap thrills? Enjoy PC-to-Phone calls to 30+ countries for just 2?/min with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/a403dd2e/attachment.htm From andrew.arobert at gmail.com Mon May 22 20:28:10 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 14:28:10 -0400 Subject: [Tutor] problem with class - get message that self is not defined Message-ID: <447202BA.80506@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, When I try to use the class listed below, I get the statement that self is not defined. test=TriggerMessage(data) var = test.decode(self.qname) I would have thought that self would have carried forward when I grabbed an instance of TriggerMessage. Any ideas on this? The class in question is: class TriggerMessage(object): def __init__(self,data): """ Unpacks the passed binary data based on the MQTCM2 format dictated in the MQ Application Programming Reference """ self.data=data self.structid=None self.version=None self.qname=None self.procname=None self.trigdata=None self.appltype=None self.applid=None self.envdata=None self.userdata=None self.qmgr=None def decode(self): import struct format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) self.data=data self.structid, self.version, self.qname, self.processname, \ self.triggerdata, self.appltype, self.applid, \ self.envdata, self.userdata, self.qmgr \ = struct.unpack(format,self.data) - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEcgK6Dvn/4H0LjDwRArwJAKCVdcpLC7IcUzDaMN+L/hVFv8CToQCaA6hP 0KteYe8olY5/72+uktGRCco= =ToBq -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Mon May 22 20:29:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 May 2006 11:29:50 -0700 (PDT) Subject: [Tutor] Download file from the web and store it locally. In-Reply-To: References: Message-ID: On Mon, 22 May 2006, MATATA EMMANUEL wrote: > import urllib > import sys > # Get a file-like object from the web and store it locally. > url = "http://www.co.rowan.nc.us/enviroservs/downloads.htm" > f = urllib.urlopen(url) > # connect to the remote > try: > remote = urllib.urlopen(url) > except: > print "Connot open URL" > sys.exit() Don't do this kind of exception handling: it hides information about the exception. If something bad happens, we want to see something other than "Cannot open URL". So instead, let the exception fall through: ########################################################### url = "http://www.co.rowan.nc.us/enviroservs/downloads.htm" f = urllib.urlopen(url) remote = urllib.urlopen(url) ########################################################### Or at the very least, modify the exception handler to print out more informative error messages other than "An error happened". We can use the 'traceback' module in the Standard Library to get us more informative error messages. While you're writing simple programs, I'd recommend avoiding exception handlers, just because if something bad happens, we need to preserve all the debugging information we can get. > # Read from the object, storing the page's contents in 's' --> want to > download parcels.zip. > s = f.read(Parcels.zip) What is parcels.zip? I don't understand what this is trying to do yet. At this point, 'f' is a file whose contents contains the stuff in http://www.co.rowan.nc.us/enviroservs/downloads.htm I get the feeling you're thinking like a web browser, in the sense that you need to first visit the page before downloading the file. If so, that's not it. *grin* If the file you're trying to download has a URL like: http://www.co.rowan.nc.us/enviroservs/Parcels.zip then there is no reason to have Python visit the downloads.htm page first: you can go ahead and grab Parcels.zip first, unless the content provider has done something weird to their web server. One other comment: ###### m = urllib.urlretrieve ###### This won't fire off. In Python, functions that take no arguments still need parens to be called. From hugonz-lists at h-lab.net Mon May 22 20:39:35 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 22 May 2006 13:39:35 -0500 Subject: [Tutor] OT: any good newsgroup or other forum for MP3 internals discussions? In-Reply-To: References: Message-ID: <44720567.4070209@h-lab.net> Terry Carroll wrote: > I apologize for this off-topic question -- the only real connection to > Python is that I'm using Python as my programming language. > > I'm writing a program to analyze an MP3 file's contents. I need to > find a newsgroup or other forum to ask some questions about file > format internals. Nothing's jumping out at me, looking through the > list of usenet newsgroups. > > I've found dozens of sites with relevant specifications, but am looking at > one or two rogue files where either I'm misunderstanding the specs, or the > file is nonconformant (but some MP3 programs can read them, so I'm betting > it's me). Are you using any kind of prefabricated Python module for this? Maybe their implementation of MP3 tagging is enlightening to you. Remember that ID3 in MP3 was a dirty hack at the beginning, so it is likely that may files are nonconformant or that many different programs simply follow their gut, as there was no specification. Hugo From emmatata at hotmail.com Mon May 22 20:52:50 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 14:52:50 -0400 Subject: [Tutor] Download file from the web and store it locally. In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/4ac9edb9/attachment.html From python at venix.com Mon May 22 20:56:52 2006 From: python at venix.com (Python) Date: Mon, 22 May 2006 14:56:52 -0400 Subject: [Tutor] problem with class - get message that self is not defined In-Reply-To: <447202BA.80506@gmail.com> References: <447202BA.80506@gmail.com> Message-ID: <1148324212.5441.503.camel@www.venix.com> On Mon, 2006-05-22 at 14:28 -0400, Andrew Robert wrote: > When I try to use the class listed below, I get the statement that > self > is not defined. > > test=TriggerMessage(data) > var = test.decode(self.qname) ^^^^ Perhaps var = test.decode() would do what you want. It is not clear why you are trying to use a "qname" argument when decode's only argument is self. test.decode will bind self to the test object. Alan Gauld's web site has a useful discussion of OOP programming. http://www.freenetpages.co.uk/hp/alan.gauld -- Lloyd Kvam Venix Corp From alan.gauld at freenet.co.uk Mon May 22 21:24:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 22 May 2006 20:24:34 +0100 Subject: [Tutor] help...newbie References: <20060522181721.41802.qmail@web39211.mail.mud.yahoo.com> Message-ID: <003a01c67dd5$5c3c9ca0$0202fea9@XPpro> Hi Joe, > Hello, I am pretty sure I am sending this to the right email > address. Looks like it :-) > But anyway I need help. I started learning python, How are you learning? Have you found a tutorial yet? If you already know how to program in another language the official tutorial on the python web site is quite good. If you are a complete beginner then the python web site has a page of suggested tutoriuals, including mine. > and I wanna know how to make a simple program, that > displays text and when the user presses enter more text > is displayed. And so and so until the end. Thank you, joe. Any particular text? Or just random letters? Do you mean a paging program like more on Unix? (or type in DOS) Thats a fairly easy project and most of the tutorials should help you write that. nHave a go and if you get stuck tell us what you tried, what went wrong (including any error messages) and we'll try to help out. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon May 22 21:30:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 22 May 2006 20:30:47 +0100 Subject: [Tutor] Download file from the web and store it locally. References: Message-ID: <003e01c67dd6$39d854f0$0202fea9@XPpro> > I need help on this script. I'm trying to download zip file from the > web and store it to my local drive: It is printing info, but doesn't > download any thing. Looks like you are a wee bit confused on what you are trying to do. > import urllib > import sys > # Get a file-like object from the web and store it locally. > url = "http://www.co.rowan.nc.us/enviroservs/downloads.htm" > f = urllib.urlopen(url) Here you open a link to the url > # connect to the remote > try: > remote = urllib.urlopen(url) and here you open another to the same url - do you need 2? > # Read from the object, storing the page's contents in 's' --> want > to download parcels.zip. > s = f.read(Parcels.zip) But now you are trying to read from the url, but you pass a variable name (Parcels.zip) which is probably not recognised? If it was a filename it would have quotres around it. But read() doesn't take filenames so thatsd not right either. read() will read the p[age contents of your url back as a string. If the page has a link to Parcels.zip you will have to find it and extract the url for the file - you will probably find it esier to use your browser to do this, with View->source if necessary Then use the actual url to the zip file instead of the html file above. Assuming I've understood what you are trying to do correctly. HTH, Alan G. From python at venix.com Mon May 22 21:41:12 2006 From: python at venix.com (Python) Date: Mon, 22 May 2006 15:41:12 -0400 Subject: [Tutor] problem with class - get message that self is not defined In-Reply-To: <44720C28.9010901@gmail.com> References: <447202BA.80506@gmail.com> <1148324212.5441.503.camel@www.venix.com> <44720C28.9010901@gmail.com> Message-ID: <1148326872.5441.529.camel@www.venix.com> (usually best to click reply-All so that the reply goes to the list) On Mon, 2006-05-22 at 15:08 -0400, Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Well.. inside the class is the decode function. The decode method depends on "data" which is referenced as a global. Perhaps data should be passed into decode as a second argument. My edited version: def decode(self, data): ^^^^^^ import struct format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) #self.data=data # not needed ^ ^^^^^^^^^^^^^^ self.structid, self.version, self.qname, self.processname, \ self.triggerdata, self.appltype, self.applid, \ self.envdata, self.userdata, self.qmgr \ = struct.unpack(format,data) ^^^^^ (removed self.) > > In that function, several variables are defined from a struct unpack. I am suggesting that the data to be unpacked gets passed into the decode method as an argument: test.decode(data) I changed the struct.unpack call to use the data argument. Some additional suggestions: size is never used. perhaps you want: assert size = import struct could be moved to the top of the script and imported once Hopefully this helps. > > What I need is to get those values out. > > How to do that, I am not exactly clear. > > > Andy > > > Python wrote: > > On Mon, 2006-05-22 at 14:28 -0400, Andrew Robert wrote: > >> When I try to use the class listed below, I get the statement that > >> self > >> is not defined. > >> > >> test=TriggerMessage(data) > >> var = test.decode(self.qname) > > ^^^^ > > Perhaps > > var = test.decode() > > > > would do what you want. > > > > It is not clear why you are trying to use a "qname" argument when > > decode's only argument is self. test.decode will bind self to the test > > object. > > > > Alan Gauld's web site has a useful discussion of OOP programming. > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > - -- > Thank you, > Andrew Robert > Systems Architect > Information Technologies > MFS Investment Management > Phone: 617-954-5882 > > E-mail: arobert at mfs.com > Linux User Number: #201204 > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.3 (MingW32) > > iD8DBQFEcgwoDvn/4H0LjDwRAsUuAJ94rHJbBQVxgHyLYlmi1pAhJzkE1QCfR1xK > sZlx+dHtvaZOOwRpC8tuN6o= > =2Nsp > -----END PGP SIGNATURE----- -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Mon May 22 22:05:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 May 2006 13:05:13 -0700 (PDT) Subject: [Tutor] Download file from the web and store it locally. In-Reply-To: References: Message-ID: On Mon, 22 May 2006, MATATA EMMANUEL wrote: > I just made some changes, but I still can't get my file saved on my local > drive: Ok. Up to what part of the program works? Don't just say it doesn't work: can you try isolating what parts are working as expected, and what parts aren't working as expected? Can you at least point at what you see wrong? I do see something weird here, but I want to make sure you can see it too. I guess I'm trying to say: don't use us on Tutor as a simple program or syntax checker. *grin* You should try figuring things out to the best of your abilities too, so that you can learn how to get better. From emmatata at hotmail.com Mon May 22 22:06:27 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 16:06:27 -0400 Subject: [Tutor] Download file from the web and store it locally. In-Reply-To: <003e01c67dd6$39d854f0$0202fea9@XPpro> Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/1bb9ae1f/attachment.htm From emmatata at hotmail.com Mon May 22 22:33:20 2006 From: emmatata at hotmail.com (MATATA EMMANUEL) Date: Mon, 22 May 2006 16:33:20 -0400 Subject: [Tutor] Download file from the web and store it locally. In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/7e20672f/attachment.html From alan.gauld at freenet.co.uk Mon May 22 23:24:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 22 May 2006 22:24:37 +0100 Subject: [Tutor] Download file from the web and store it locally. References: Message-ID: <004601c67de6$212b1720$0202fea9@XPpro> > I have changed the code as following but it still printing the > contains as something I don't know what it is instead of saving > locally! You need to step back a bit and get a better understanding of variables and functions and how to use them. You are trying to run before you can walk. > import urllib > import sys > > # Get a file-like object from the web and store it locally. > > url = > "http://www.co.rowan.nc.us/enviroservs/planning_data/countyline.zip" > > > # connect to the remote > try: > remote = urllib.urlopen(url) > except: > print "Connot open URL" > sys.exit() At this stage you have a connection to the zip file. > # Read from the object, storing the page's contents in 's'. > s = f.read() But here you are trying to read from f which doesn't exist! > m = "D\\Temp\\file" And here you assign a filename to m (except the filename is invalid because it doesn't have a colon after the D) > print remote.info() Now this should print some info about your connection > m = urllib.urlretrieve Now you replace the filename with a function from the urllib module. > print "Content:" > print s > print "Download Done" You print out the contents of s which probanly are invalid since f didn't exist. > f.close() And you close f which still doesn't exist. You need to sit down and work through which variables you need and which functions of urllib you need. I suspect you only need to use urllib.urlretrieve() and your total code should only be 3 or 4 lines long. Alan G. From alan.gauld at freenet.co.uk Mon May 22 23:56:32 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 22 May 2006 22:56:32 +0100 Subject: [Tutor] help...newbie References: <20060522193443.42756.qmail@web39204.mail.mud.yahoo.com> Message-ID: <005601c67dea$96a4cd80$0202fea9@XPpro> > Hey Alan, I have indeed found a tutorial. "A Byte Of Python" Yes, that should be fine for you. > So far it's really good. I'm down around functions, and is this far > enough? I'm not sure which order it covers things but somewhere soon you should find the stuff about reading text from files and you should already know about how to read input from a user and write output to the screen. The next step is to try actually writing the program and see how it goes. It probably won;t work first time, but try to woprk out why and fix it. If you get stuck send a note to the tutor list and someone will help out. > So is that enough to use the python tutorial? A C background would be fine, but since you already have a Byte of Python then stick with it... Alan G. > Alan Gauld wrote: Hi Joe, > >> Hello, I am pretty sure I am sending this to the right email >> address. > > Looks like it :-) > >> But anyway I need help. I started learning python, > > How are you learning? Have you found a tutorial yet? > If you already know how to program in another language > the official tutorial on the python web site is quite good. > > If you are a complete beginner then the python web site has > a page of suggested tutoriuals, including mine. > >> and I wanna know how to make a simple program, that >> displays text and when the user presses enter more text >> is displayed. And so and so until the end. Thank you, joe. > > Any particular text? Or just random letters? > Do you mean a paging program like more on Unix? (or type in DOS) > Thats a fairly easy project and most of the tutorials should help > you write that. nHave a go and if you get stuck tell us what you > tried, what went wrong (including any error messages) and we'll > try to help out. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > --------------------------------- > Be a chatter box. Enjoy free PC-to-PC calls with Yahoo! Messenger > with Voice. From alan.gauld at freenet.co.uk Tue May 23 00:07:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 22 May 2006 23:07:27 +0100 Subject: [Tutor] problem with class - get message that self is not defined References: <447202BA.80506@gmail.com> Message-ID: <007401c67dec$1d52fe50$0202fea9@XPpro> > When I try to use the class listed below, I get the statement that > self > is not defined. > > test=TriggerMessage(data) > var = test.decode(self.qname) > > I would have thought that self would have carried forward when I > grabbed > an instance of TriggerMessage. self is a special varianble that is only defined inside of a method of an object. It refers to the object itself (hence the name!) Thus you cannot pass self.qname into a method unless you are already inside another object's method. You can read about this in more edetail in the OOP topic of my tutor but I'll try to illustrate here: class C: def method(self,x): self.var = x def g(self, anObj): anObj.f(self.var) class D: def f(self, val): print val c = C() c.method(42) creates an object called c and executes its method with a value of 42. This executes the function C.method(c,42) where self takes the values c and x 42 The end result is that object c has a data member called var with the value 42 d = D() c.g(d) creates a new object d calls the g method of c passing object d as argument executes the function C.g(c,d) where self takes on the value c and anObj takes on d C.g() then calls d.f(self.var) which executes D.f(d,c.var) that is, the self in D.f() is d and the self in C.g() = c I hope that makes sense. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From flickita at gmail.com Mon May 22 23:22:17 2006 From: flickita at gmail.com (Cecilia Alm) Date: Mon, 22 May 2006 16:22:17 -0500 Subject: [Tutor] IDLE: configuration Message-ID: <7a4620dc0605221422v7f76d703m3dae9f46b761eed@mail.gmail.com> Hi, How can I set tab as default indendation for the file editor window in IDLE? I tried to change this in "Configuration Window" and "Apply", but still get 4 spaces. What does work is setting indentation to "8" and then enabling toggle tabs when I open a new window. Thanks, Cecilia -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/00041b94/attachment.htm From marshall.jiang at gmail.com Tue May 23 03:09:01 2006 From: marshall.jiang at gmail.com (Shuai Jiang) Date: Mon, 22 May 2006 21:09:01 -0400 Subject: [Tutor] Calendar Module Message-ID: Hello, I just got Python In a Nutshell and decided to play around with the time section. While playing with the calendar module, I encountered a problem: >>> import calendar >>> calendar.calendar(2006) ' 2006\n\n January February March\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3 4 5\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26\n23 24 25 26 27 28 29 27 28 27 28 29 30 31\n30 31\n\n April May June\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 7 1 2 3 4\n 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n\n July August September\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 1 2 3\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n31\n\n October November December\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n30 31\n' >>> I can't seem to figure out how to make it look prettier Thanks in advance Marshall Jiang -- Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. Rick Cook, The Wizardry Compiled -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060522/e2b5194c/attachment-0001.html From john at fouhy.net Tue May 23 03:19:58 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 23 May 2006 13:19:58 +1200 Subject: [Tutor] Calendar Module In-Reply-To: References: Message-ID: <5e58f2e40605221819j60368871g84cc1db35a824b28@mail.gmail.com> On 23/05/06, Shuai Jiang wrote: > Hello, > I just got Python In a Nutshell and decided to play around with the time > section. While playing with the calendar module, I encountered a problem: > > >>> import calendar > >>> calendar.calendar (2006) > ' 2006\n\n January > February March\nMo Tu We Th Fr Sa Su > Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 > 1 2 3 4 5 1 2 3 4 5\n 2 3 4 5 6 7 8 6 7 [...] > I can't seem to figure out how to make it look prettier > Thanks in advance See those '\n' characters? They mean "start a new line" in some contexts (such as text output and graphical editors). You can make python interpret them by asking it to print the output. For example: >>> s = 'Hello\n World!\n---------\n ------- \n ----- \n' >>> s 'Hello\n World!\n---------\n ------- \n ----- \n' >>> print s Hello World! --------- ------- ----- >>> Or, you could try typing "print calendar.calendar(2006)" into your console :-) -- John. From hokkakada at khmeros.info Tue May 23 05:12:30 2006 From: hokkakada at khmeros.info (kakada) Date: Tue, 23 May 2006 10:12:30 +0700 Subject: [Tutor] StringIO Message-ID: <44727D9E.3000301@khmeros.info> Hello list, I want to use the module StringIO as read and write strings as files, I looked into document but cannot understand. Could anyone give me a simple example? something like: from StringIO import * fin = StringIO("abc") ..... How can I used fin? Thanks, da From jenw at nb.sympatico.ca Tue May 23 03:14:36 2006 From: jenw at nb.sympatico.ca (jenw at nb.sympatico.ca) Date: Mon, 22 May 2006 21:14:36 -0400 Subject: [Tutor] (no subject) Message-ID: <20060523011436.IKIH25660.simmts6-srv.bellnexxia.net@smtp8.sympatico.ca> I am looking for Matthew White. How can I reach him. Jen From dyoo at hkn.eecs.berkeley.edu Tue May 23 05:45:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 May 2006 20:45:46 -0700 (PDT) Subject: [Tutor] StringIO In-Reply-To: <44727D9E.3000301@khmeros.info> References: <44727D9E.3000301@khmeros.info> Message-ID: > I want to use the module StringIO as read and write strings as files, I > looked into document but cannot understand. Could anyone give me a > simple example? > > something like: > from StringIO import * > fin = StringIO("abc") > ..... > How can I used fin? 'fin' is a file-like object at this point, so you can do things like: fin.read(1) to get a single byte. The list of things we can do with file-like objects is here: http://www.python.org/doc/lib/bltin-file-objects.html Does this help? Good luck! From dyoo at hkn.eecs.berkeley.edu Tue May 23 05:54:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 22 May 2006 20:54:13 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: <20060523011436.IKIH25660.simmts6-srv.bellnexxia.net@smtp8.sympatico.ca> References: <20060523011436.IKIH25660.simmts6-srv.bellnexxia.net@smtp8.sympatico.ca> Message-ID: On Mon, 22 May 2006, jenw at nb.sympatico.ca wrote: > I am looking for Matthew White. How can I reach him. Hi Jennifer, We probably can not help you much with this. It would help very much if you could somehow explain why you posted this question here on Tutor. It is not obvious how this is related to Python, learning, or programming. This doesn't mean that your question is irrelevant altogether, but only that we don't have much expertise to track this person down for you from the whole entire world. At a whim, I did a google search for "matthew white python". There is a Matthew White that has been answering on Python-Tutor. See: http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/3115167 I really don't know if this is who you are referring to, but this is the best I can do with my assumptions. Next time, please provide more context here. Good luck to you. From hokkakada at khmeros.info Tue May 23 06:27:42 2006 From: hokkakada at khmeros.info (kakada) Date: Tue, 23 May 2006 11:27:42 +0700 Subject: [Tutor] StringIO In-Reply-To: References: <44727D9E.3000301@khmeros.info> Message-ID: <44728F3E.7080609@khmeros.info> Danny Yoo wrote: >> I want to use the module StringIO as read and write strings as files, >> I looked into document but cannot understand. Could anyone give me a >> simple example? >> >> something like: >> from StringIO import * >> fin = StringIO("abc") >> ..... >> How can I used fin? > > 'fin' is a file-like object at this point, so you can do things like: > > fin.read(1) > > to get a single byte. The list of things we can do with file-like > objects is here: > > http://www.python.org/doc/lib/bltin-file-objects.html > > > Does this help? Good luck! Actually, what I want is creating a kind of file that is just located in memory not file system. I want to have a filename for my convert(inputFileName, outputFileName) How can I get filename? doing: fin.name() is impossible! All above, I want to test it in unittest. > > From alan.gauld at freenet.co.uk Tue May 23 06:35:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 23 May 2006 05:35:53 +0100 Subject: [Tutor] Calendar Module References: Message-ID: <004301c67e22$6053cb90$0c01a8c0@XPpro> use print! print calendart.calendar(2006) Alan G. ----- Original Message ----- From: "Shuai Jiang" To: Sent: Tuesday, May 23, 2006 2:09 AM Subject: [Tutor] Calendar Module Hello, I just got Python In a Nutshell and decided to play around with the time section. While playing with the calendar module, I encountered a problem: >>> import calendar >>> calendar.calendar(2006) ' 2006\n\n January February March\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3 4 5\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26\n23 24 25 26 27 28 29 27 28 27 28 29 30 31\n30 31\n\n April May June\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 7 1 2 3 4\n 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n\n July August September\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 1 2 3 4 5 6 1 2 3\n 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n31\n\n October November December\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n30 31\n' >>> I can't seem to figure out how to make it look prettier Thanks in advance Marshall Jiang -- Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. Rick Cook, The Wizardry Compiled From kent37 at tds.net Tue May 23 11:59:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 May 2006 05:59:11 -0400 Subject: [Tutor] StringIO In-Reply-To: <44728F3E.7080609@khmeros.info> References: <44727D9E.3000301@khmeros.info> <44728F3E.7080609@khmeros.info> Message-ID: <4472DCEF.8000406@tds.net> kakada wrote: > Actually, what I want is creating a kind of file that is just located in > memory not file system. > I want to have a filename for my convert(inputFileName, outputFileName) > How can I get filename? > doing: > fin.name() is impossible! Rewrite convert so it takes file-like objects as arguments rather than file names. Then you can pass StringIO objects for input and output in your unittests. Alternately you might want to write convert so it can take *either* a file name or an open file as an argument. Here is a snippet from a function that does that (ElementTree.parse()): def parse(self, source, parser=None): if not hasattr(source, "read"): source = open(source, "rb") > All above, I want to test it in unittest. Good idea! Kent From amonroe at columbus.rr.com Tue May 23 15:23:12 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 23 May 2006 09:23:12 -0400 Subject: [Tutor] I'm drawing a blank on a simple (?) regex Message-ID: <681168710667.20060523092312@columbus.rr.com> I'm searching through SQL logs and want to find lines that have WHERE-less (unbounded) queries. I can't come up with a regex to say: SELECT.*FROM.*(the word WHERE must not exist anywhere in the remainder of the line) Am I forgetting something simple or would this take two passes? Alan From kent37 at tds.net Tue May 23 18:02:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 May 2006 12:02:48 -0400 Subject: [Tutor] I'm drawing a blank on a simple (?) regex In-Reply-To: <681168710667.20060523092312@columbus.rr.com> References: <681168710667.20060523092312@columbus.rr.com> Message-ID: <44733228.2050502@tds.net> R. Alan Monroe wrote: > I'm searching through SQL logs and want to find lines that have > WHERE-less (unbounded) queries. I can't come up with a regex to say: > > SELECT.*FROM.*(the word WHERE must not exist anywhere in the remainder > of the line) > > Am I forgetting something simple or would this take two passes? Try using a negative look-ahead: SELECT.*FROM(?!.*WHERE) Kent From carroll at tjc.com Tue May 23 19:22:19 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 23 May 2006 10:22:19 -0700 (PDT) Subject: [Tutor] OT: any good newsgroup or other forum for MP3 internals discussions? In-Reply-To: <44720567.4070209@h-lab.net> Message-ID: On Mon, 22 May 2006, [ISO-8859-1] Hugo González Monteverde wrote: > Are you using any kind of prefabricated Python module for this? Maybe > their implementation of MP3 tagging is enlightening to you. I started to; I started using the mp3.py module found here: http://www.dotfunk.com/projects/mp3 , but there were a lot of files that it fails on (giving incorrect results or throwing an exception), and the files are playable and give readable ID3 tags in multiple MP3 apps (e.g., Magnus Brading's Mp3/Tag Studio and WinAmp). So I decided to try to write my own. My first cut was to try to modify that module, but it's a little bit idiosyncratic, and at least one part of it (apparently in a part that's not actually reached, or maybe whose result is not used) is incorrect. I thought it would be kind of fun to write my own, too; I'm just running into issues where a header does not seem (I say "seem," because I'm very aware the problem might be my interpretation) to conform to the specs, but which are handled just fine by other utilities I check against it. > Remember that ID3 in MP3 was a dirty hack at the beginning, so it is > likely that may files are nonconformant or that many different programs > simply follow their gut, as there was no specification. ID3V2 seems to be very clearly specified, though; and ID3V1 is simple enough that i isn't a problem. But some of my questions will be going to the MP3 frame data itself, even apart from the ID3 stuff. But yesterday, while looking again for a newsgroup where my discussion would be on-topic, I saw numerous mentions of a Python package called eye3D, and tracked it down to http://eyed3.nicfit.net/ . I'll see if that meets my needs. Thanks, Hugo. From amonroe at columbus.rr.com Tue May 23 19:21:45 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 23 May 2006 13:21:45 -0400 Subject: [Tutor] I'm drawing a blank on a simple (?) regex In-Reply-To: <44733228.2050502@tds.net> References: <681168710667.20060523092312@columbus.rr.com> <44733228.2050502@tds.net> Message-ID: <691183024228.20060523132145@columbus.rr.com> > R. Alan Monroe wrote: >> I'm searching through SQL logs and want to find lines that have >> WHERE-less (unbounded) queries. I can't come up with a regex to say: >> >> SELECT.*FROM.*(the word WHERE must not exist anywhere in the remainder >> of the line) >> >> Am I forgetting something simple or would this take two passes? > Try using a negative look-ahead: > SELECT.*FROM(?!.*WHERE) Brilliant - works in python redemo, and grep too w/ -P switch. Alan From bgailer at alum.rpi.edu Tue May 23 21:59:04 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 23 May 2006 12:59:04 -0700 Subject: [Tutor] problem with class - get message that self is not defined In-Reply-To: <007401c67dec$1d52fe50$0202fea9@XPpro> References: <447202BA.80506@gmail.com> <007401c67dec$1d52fe50$0202fea9@XPpro> Message-ID: <44736988.8020601@alum.rpi.edu> Alan Gauld wrote: >> When I try to use the class listed below, I get the statement that >> self >> is not defined. >> >> test=TriggerMessage(data) >> var = test.decode(self.qname) >> >> I would have thought that self would have carried forward when I >> grabbed >> an instance of TriggerMessage. >> > > self is a special varianble "special variable" could be confusing. Python has no "special variables". "self" is used by convention. One could use "this" as an alternative, or any other variable. When defining a method in a class one writes def abc(self, a,b,c) OR def abc(this, a,b,c). Then one refers to "self" or "this" within the method to refer to the instance calling the method. -- Bob Gailer 510-978-4454 Broadband Phone Service for local and long distance $19.95/mo plus 1 mo Free From alan.gauld at freenet.co.uk Tue May 23 23:17:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 23 May 2006 22:17:22 +0100 Subject: [Tutor] problem with class - get message that self is not defined References: <447202BA.80506@gmail.com> <007401c67dec$1d52fe50$0202fea9@XPpro> <44736988.8020601@alum.rpi.edu> Message-ID: <000301c67eae$48140a40$0c01a8c0@XPpro> >> self is a special varianble > "special variable" could be confusing. Python has no "special > variables". "self" is used by convention. Good point. The name self is not special it is its role that is special. thus class C: def m(s,p): print p c = C() c.m(42) Thus we define method m to have two parameters s and p but when we call m we only pass in one argument. Python then takes this and turns it into C.m(c,42) The specialness of 'self' is that although we specify it, and can access it, in the method definition we do not specify it in the message to the class that invokes the method. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From vagemulo at yahoo.es Wed May 24 09:31:06 2006 From: vagemulo at yahoo.es (rio) Date: Wed, 24 May 2006 08:31:06 +0100 (BST) Subject: [Tutor] "words", tags, "nonwords" in xml/text files Message-ID: <20060524073106.89410.qmail@web26606.mail.ukl.yahoo.com> I'm developing an application to do interlineal (an extreme type of literal) translations of natural language texts and xml. Here's an example of a text: '''Para eso son los amigos. Para celebrar las gracias del otro.''' and the expected translation with all of the original tags, whitespace, etc intact: '''For that are the friends. For toCelebrate the graces ofThe other.

''' I was unable to find (in htmlparser, string or unicode) a way to define words as a series of letters (including non-ascii char sets) outside of an xml tag and whitespace/punctuation, so I wrote the code below to create a list of the words, nonwords, and xml tags in a text. My intuition tells me that its an awful lot of code to do a simple thing, but it's the best I could come up with. I forsee several problems: -it currently requires that the entire string (or file) be processed into memory. if i should want to process a large file line by line, a tab which spans more than one line would be ignored. (that's assuming i would not be able to store state information in the function, which is something i've not yet learned how to do) -html comments may not be supported. (i'm not really sure about this) -it may be very slow as it indexes instead of iterating over the string. what can i do to overcome these issues? Am I reinventing the wheel? Should I be using re? thanks, brian ******************************** # -*- coding: utf-8 -*- # html2list.py def split(alltext, charset='??????????????'): #in= string; out= list of words, nonwords, html tags. '''builds a list of the words, tags, and nonwords in a text.''' length = len(alltext) str2list = [] url = [] word = [] nonword = [] i = 0 if alltext[i] == '<': url.append(alltext[i]) elif alltext[i].isalpha() or alltext[i] in charset: word.append(alltext[i]) else: nonword.append(alltext[i]) i += 1 while i < length: if url: if alltext[i] == '>': #end url: url.append(alltext[i]) str2list.append("".join(url)) url = [] i += 1 if alltext[i].isalpha() or alltext[i] in charset: #start word word.append(alltext[i]) else: #start nonword nonword.append(alltext[i]) else: url.append(alltext[i]) elif word: if alltext[i].isalpha() or alltext[i] in charset: #continue word word.append(alltext[i]) elif alltext[i] == '<': #start url str2list.append("".join(word)) word = [] url.append(alltext[i]) else: #start nonword str2list.append("".join(word)) word = [] nonword.append(alltext[i]) elif nonword: if alltext[i].isalpha() or alltext[i] in charset: #start word str2list.append("".join(nonword)) nonword = [] word.append(alltext[i]) elif alltext[i] == '<': #start url str2list.append("".join(nonword)) nonword = [] url.append(alltext[i]) else: #continue nonword nonword.append(alltext[i]) else: print 'error', i += 1 if nonword: str2list.append("".join(nonword)) if url: str2list.append("".join(url)) if word: str2list.append("".join(word)) return str2list ## example: text = '''El aguardiente de ca?a le quem? la garganta y devolvi? la botella con una mueca. ?No se me ponga feo, doctor. Esto mata los bichos de las tripas ?dijo Antonio Jos? Bol?var, pero no pudo seguir hablando.''' print split(text) ___________________________________________________________ Try the all-new Yahoo! Mail. "The New Version is radically easier to use" ? The Wall Street Journal http://uk.docs.yahoo.com/nowyoucan.html From kent37 at tds.net Wed May 24 11:53:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 May 2006 05:53:21 -0400 Subject: [Tutor] "words", tags, "nonwords" in xml/text files In-Reply-To: <20060524073106.89410.qmail@web26606.mail.ukl.yahoo.com> References: <20060524073106.89410.qmail@web26606.mail.ukl.yahoo.com> Message-ID: <44742D11.10805@tds.net> rio wrote: > I'm developing an application to do interlineal (an extreme type of > literal) translations of natural language texts and xml. Here's an example > of a text: > > '''Para eso son los amigos. Para celebrar las gracias del otro.''' > > and the expected translation with all of the original tags, whitespace, > etc intact: > > '''For that are the friends. For toCelebrate the graces ofThe > other.

''' > > I was unable to find (in htmlparser, string or unicode) a way to define > words as a series of letters (including non-ascii char sets) outside of an > xml tag and whitespace/punctuation, so I wrote the code below to create a > list of the words, nonwords, and xml tags in a text. My intuition tells > me that its an awful lot of code to do a simple thing, but it's the best I > could come up with. I forsee several problems: > > -it currently requires that the entire string (or file) be processed into > memory. if i should want to process a large file line by line, a tab which > spans more than one line would be ignored. (that's assuming i would not be > able to store state information in the function, which is something i've > not yet learned how to do) > -html comments may not be supported. (i'm not really sure about this) > -it may be very slow as it indexes instead of iterating over the string. > > what can i do to overcome these issues? Am I reinventing the wheel? Should > I be using re? You should probably be using sgmllib. Here is an example that is pretty close to what you are doing: http://diveintopython.org/html_processing/index.html Kent From s_david_rose at hotmail.com Wed May 24 18:19:36 2006 From: s_david_rose at hotmail.com (S. D. Rose) Date: Wed, 24 May 2006 12:19:36 -0400 Subject: [Tutor] Download file from the web and store it locally. References: Message-ID: Matt- Have you tried running this line-by-line in IDLE? I've done a script almost exactly the same as what you're doing ( I downloaded a .jpg file from a web-server ), and when I was trying to learn what commands did what, I quickly changed from trying to write a 'program' to running lines individually in IDLE so I could print out the results of each command, and to see exactly what lines 'work', which have syntax errors and which have logic errors. People often want a compiler which spits out executables, but I realized it's nice to be able to type a few lines of an algorithm into the interpreter and see the results, so I can see if I get the results I expect, then copy that and paste it into my 'program'. -Dave Now, for wxPython (a windowing superset of python), my routine was: ---SNIP--- WebImage = urllib2.urlopen("%s/jpg/fullsize.jpg" %netCamAddress) rawJpg = WebImage.read() photostream = cStringIO.StringIO(rawJpg) photoJpg = wx.ImageFromStream(photostream) photoBmp = wxBitmapFromImage(photoJpg) liveVideo.SetBitmap(photoBmp) ---SNIP--- "Give a man a fish; you have fed him for today. Teach a man to fish; and you have fed him for a lifetime. Show a man what a fish looks like so he doesn't try to eat a tire he fishes out of the pond." So, let me show you what a "fish" looks like. I expect the first two lines are of use to you, where the bottom-four lines are specific to wxPython. Realize what is happening with the string in the first line? I'm replacing part of the web-address with the contents of the variable netCamAddress. Can you figure out how that is working? hint- you can try printing "%s/jpg/fullsize.jpg" %netCamAddress directly in IDLE after setting netCamAddress to a string value to see what the result is, so you know what urllib2 is opening .... After line two is executed, the contents of rawJpg is the .jpg file I downloaded. Do you know what to do next? Maybe open a file in binary mode, and write rawJpg' to the file then close it? Also, do you realize I'm using a different library for urlopen than you used? Do you know which one, and how to import it? Lastly, there are a couple ways you can specify your file in python. "D:\\Temp\\file" but I like using raw strings. r"d:\directory\file.ext" (I hate double-slashing. It's so visually messy, it makes it easy to miss things like commas I think...) http://docs.python.org/tut/node9.html#SECTION009200000000000000000 Maybe sections 7.2 and 7.2.1 are relevent to the rest of your goals? -Dave From andrew.arobert at gmail.com Wed May 24 18:30:02 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 12:30:02 -0400 Subject: [Tutor] Question on regular expressions Message-ID: <44748A0A.4010602@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, I have two Perl expressions If windows: perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt If posix perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge' somefile.txt The [^\w\s] is a negated expression stating that any character a-zA-Z0-9_, space or tab is ignored. The () captures whatever matches and throws it into the $1 for processing by the sprintf In this case, %%%2X which is a three character hex value. How would you convert this to a python equivalent using the re or similar module? I've begun reading about using re expressions at http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation. Any help you can provide would be greatly appreciated. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdIoKDvn/4H0LjDwRAi24AKDFmRohKFfp13z/M9c8O1LQElGzMgCglcRw 3ERK7FxWejsuFcnDSNdOYjM= =28Lx -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Wed May 24 19:18:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 May 2006 10:18:31 -0700 (PDT) Subject: [Tutor] Question on regular expressions In-Reply-To: <44748A0A.4010602@gmail.com> References: <44748A0A.4010602@gmail.com> Message-ID: > perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt Hi Andrew, Give me a second. I'm trying to understand the command line switches: (Looking in 'perl --help'...) -p assume loop like -n but print line also, like sed -l[octal] enable line ending processing, specifies line terminator -e program one line of program (several -e's allowed, omit programfile) and the regular expression modifiers there --- 'g' and 'e' --- mean ... (reading 'perldoc perlop'...) g Match globally, i.e., find all occurrences. e Evaluate the right side as an expression. Ok, I have a better idea of what's going on here now. This takes a file, and translates every non-whitespace character into a hex string. That's a dense one-liner. > How would you convert this to a python equivalent using the re or > similar module? The substitution on the right hand side in the Perl code actually is evaluated rather than literally substituted. To get the same effect from Python, we pass a function off as the substituting value to re.sub(). For example, we can translate every word-like character by shifting it one place ('a' -> 'b', 'b' -> 'c', etc...) ############################################### >>> import re >>> def rot1(ch): ... return chr((ord(ch) + 1) % 256) ... >>> def rot1_on_match(match): ... return rot1(match.group(0)) ... >>> re.sub(r'\w', rot1_on_match, "hello world") 'ifmmp xpsme' ############################################### > I've begun reading about using re expressions at > http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation. The part in: http://www.amk.ca/python/howto/regex/regex.html#SECTION000620000000000000000 that talks about a "replacement function" is relevant to what you're asking. We need to provide a replacement function to simulate the right-hand-side "evaluation" that's happening in the Perl code. Good luck! From andrew.arobert at gmail.com Thu May 25 00:11:31 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 18:11:31 -0400 Subject: [Tutor] Hex conversion strangeness Message-ID: <4474DA13.9090407@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, I am trying to understand conversion of a value to hex. Could you please confirm that what I am doing is right? Get the hex value of ! and store it in a a=hex(ord('!')) print a 0X21 I see examples including this kind of a statement but I am not sure why. int(a,16) 33 If the 0X21 is the actual hex value, then why convert to integer? Is this the ASCII table reference to the hex value? - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdNoTDvn/4H0LjDwRAp6yAKC5wI55jX5BJeu89ahj55hA7i8eAQCgu2Op rVbo0kgQ9GQv8N0TB34StlY= =pe50 -----END PGP SIGNATURE----- From simplebob at gmail.com Thu May 25 00:18:46 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Wed, 24 May 2006 18:18:46 -0400 Subject: [Tutor] cisco router + telnetlib Message-ID: <6d87ecf40605241518m293145d9s8c8859ffae576dae@mail.gmail.com> Hello List, I am rather new to programming and I was wondering y'all think the best way to configure a cisco router using python would be. currently I am using telnetlib. my problem is, I get an error after connecting to the router. here is the error I get when I use IDLE: Enter IP: 205.180.0.3 Warning: Problem with getpass. Passwords may be echoed. Router Password: cisco Warning: Problem with getpass. Passwords may be echoed. Router Secret: class Enter Router hostname: RouterBob Traceback (most recent call last): File "C:\Documents and Settings\bob\My Documents\Administration\Scripts\cisco_config.py", line 20, in ? tn.write("hostname " + hostName + "\n") File "C:\Python24\lib\telnetlib.py", line 292, in write self.sock.sendall(buffer) File "", line 1, in sendall error: (10053, 'Software caused connection abort') >>> I have also attached the script that I use. could you please point me in the right direction. thank you in advance, -- Daniel McQuay boxster.homelinux.org Dead Possum Productions 814.825.0847 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060524/79b69995/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: cisco_config.py Url: http://mail.python.org/pipermail/tutor/attachments/20060524/79b69995/attachment.asc From john at fouhy.net Thu May 25 00:29:21 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 25 May 2006 10:29:21 +1200 Subject: [Tutor] Hex conversion strangeness In-Reply-To: <4474DA13.9090407@gmail.com> References: <4474DA13.9090407@gmail.com> Message-ID: <5e58f2e40605241529l38ae3572qd197b5ec189892e9@mail.gmail.com> On 25/05/06, Andrew Robert wrote: > If the 0X21 is the actual hex value, then why convert to integer? > > Is this the ASCII table reference to the hex value? Hi Andrew, There is a difference between a number and the representation of that number. For example, there is a number that, in base 10, I can represent as "33". In base 8, that number is represented as "41". In base 2, it would be "100001". If I were, say, an ancient Mayan, it might look quite different indeed (http://en.wikipedia.org/wiki/Maya_numerals). But in all cases, the number is the same. So, in python, the hex() and oct() functions will give you the hexadecimal and octal representations of an integer. Notice that they return strings, not numbers. If you want to convert from a string to an integer, you can use the int() function with a second parameter. That's what's happening when you type int('21', 16) or int('0x21', 16). You're converting the string to an integer, which happens to be represented internally by a bitstring. Because you're working at the interactive prompt, python automatically displays the result of every expression you type. In this case, the result of int('0x21', 16) is an integer, and python displays integers in base 10 by default --- hence, you see 33. By the way, you can enter integers in base 8 or base 16, if you want: >>> 0x21, 041 (33, 33) >>> 0x21 is 041 is 33 True HTH! -- John. From python at venix.com Thu May 25 00:54:07 2006 From: python at venix.com (Python) Date: Wed, 24 May 2006 18:54:07 -0400 Subject: [Tutor] cisco router + telnetlib In-Reply-To: <6d87ecf40605241518m293145d9s8c8859ffae576dae@mail.gmail.com> References: <6d87ecf40605241518m293145d9s8c8859ffae576dae@mail.gmail.com> Message-ID: <1148511247.5441.682.camel@www.venix.com> On Wed, 2006-05-24 at 18:18 -0400, Daniel McQuay wrote: > Hello List, > > I am rather new to programming and I was wondering y'all think the > best way to configure a cisco router using python would be. currently > I am using telnetlib. my problem is, I get an error after connecting > to the router. here is the error I get when I use IDLE: > http://mail.python.org/pipermail/tutor/2006-March/045547.html This is part of an earlier thread about configuring routers using a script. I'd recommend using tcpwatch to debug the connection. The router may have sent an error message before closing the connection. Remember that the router software was designed for human interaction. tcpwatch will allow you to see both sides of the conversation. You'll see in the earlier thread that I'd also recommend using tftp to send most of the commands and limit the interactive telnet script to: logging on running tftp logging off > Enter IP: 205.180.0.3 > Warning: Problem with getpass. Passwords may be echoed. > Router Password: cisco > Warning: Problem with getpass. Passwords may be echoed. > Router Secret: class > Enter Router hostname: RouterBob > Traceback (most recent call last): > File "C:\Documents and Settings\bob\My Documents\Administration > \Scripts\cisco_config.py", line 20, in ? > tn.write("hostname " + hostName + "\n") > File "C:\Python24\lib\telnetlib.py", line 292, in write > self.sock.sendall(buffer) > File "", line 1, in sendall > error: (10053, 'Software caused connection abort') > >>> > > I have also attached the script that I use. could you please point me > in the right direction. > > thank you in advance, > > > -- > Daniel McQuay > boxster.homelinux.org > Dead Possum Productions > 814.825.0847 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From khp at pflaesterer.de Thu May 25 00:45:51 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Thu, 25 May 2006 00:45:51 +0200 Subject: [Tutor] Question on regular expressions In-Reply-To: <44748A0A.4010602@gmail.com> (Andrew Robert's message of "Wed, 24 May 2006 12:30:02 -0400") References: <44748A0A.4010602@gmail.com> Message-ID: On 24 Mai 2006, andrew.arobert at gmail.com wrote: > I have two Perl expressions > > > If windows: > > perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt > > If posix > > perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge' somefile.txt > > > > The [^\w\s] is a negated expression stating that any character > a-zA-Z0-9_, space or tab is ignored. > > The () captures whatever matches and throws it into the $1 for > processing by the sprintf > > In this case, %%%2X which is a three character hex value. > > How would you convert this to a python equivalent using the re or > similar module? python -c "import re, sys;print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), sys.stdin.read())," < somefile It's not as short as the Perl version (and might have problems with big files). Python does not have such useful command line switches like -p (but you doesn't use Python so much for one liners as Perl) but it does the same ; at least in this special case (Python lacks something like the -l switch). With bash it's a bit easier. (maybe there's also a way with cmd.com to write multiple lines)? $ python -c "import re,sys for line in sys.stdin: print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)," < somefile Karl -- Please do *not* send copies of replies to me. I read the list From cspears2002 at yahoo.com Thu May 25 01:34:53 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 24 May 2006 16:34:53 -0700 (PDT) Subject: [Tutor] class Writer Message-ID: <20060524233453.80196.qmail@web51605.mail.yahoo.com> I've been working my way through an online tutorial and came across the following sample script: import sys class Writer: def __init__(self, filename): self.filename = filename def write(self, msg): f = file(self.filename, 'a') f.write(msg) f.close() sys.stdout = Writer('tmp.log') print 'Log message #1' print 'Log message #2' print 'Log message #3' The script created the tmp.log file with the following lines: Log message #1 Log message #2 Log message #3 I understand that the class is taking the strings from stdout (supplied by the print statements) and writing them to a text file. Does the user need to explicitly call the write function? For example: sys.stdout = Writer('tmp.log').write(whatever the message is) From andrew.arobert at gmail.com Thu May 25 01:51:12 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 19:51:12 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: References: <44748A0A.4010602@gmail.com> Message-ID: <4474F170.7060806@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Wow!!.. That awesome! My goal was not to make it a one-liner per-se.. I was simply trying to show the functionality I was trying to duplicate. Boiling your one-liner down into a multi-line piece of code, I did: #!c:\python24\python import re,sys a = open(r'e:\pycode\csums.txt','rb').readlines() for line in a: print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) Breaking down the command, you appear to be calling an un-named function to act against any characters trapped by the regular expression. Not familiar with lamda :). The un-named function does in-place transformation of the character to the established hex value. Does this sound right? If I then saved the altered output to a file and wanted to transform it back to its original form, I would do the following in perl. perl -ple 's/(?:%([0-9A-F]{2}))/chr hex $1/eg' somefiletxt How would you reverse the process from a python point of view? Karl Pfl?sterer wrote: > python -c "import re, sys;print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), sys.stdin.read())," < somefile > > It's not as short as the Perl version (and might have problems with big > files). Python does not have such useful command line switches like -p > (but you doesn't use Python so much for one liners as Perl) but it does > the same ; at least in this special case (Python lacks something like the > -l switch). > > With bash it's a bit easier. (maybe there's also a way with cmd.com to > write multiple lines)? > > $ python -c "import re,sys > for line in sys.stdin: print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)," < somefile > > > Karl - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdPFwDvn/4H0LjDwRAuzuAKCOPja9Js1ueP2GoT+B0hoFubDEegCguzfT QL87gmKUx6znmGQxXqg6V+A= =7MT2 -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Thu May 25 02:49:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 May 2006 17:49:09 -0700 (PDT) Subject: [Tutor] Question on regular expressions (fwd) Message-ID: [forwarding to tutor, although it looks like Andrew's making some good headway from other messages] ---------- Forwarded message ---------- Date: Wed, 24 May 2006 14:59:43 -0400 From: Andrew Robert To: Danny Yoo Subject: Re: [Tutor] Question on regular expressions -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey Danny, Your code put me right on track. - From that point, I crafted the following code. What is confusing is how to take the captured character and transform it into a 3 digit hex value. Do you know how that might be accomplished? #!/usr/bin/python import re # Evaluate captured character as hex def ret_hex(ch): return chr((ord(ch) + 1 ) % 256 ) # Evaluate the value of whatever was matched def eval_match(match): return ret_hex(match.group(0)) # open file file = open(r'm:\mq\mq\scripts\sigh.txt','r') # Read each line, pass any matches on line to function for # line in file.readlines(): for line in file: a=re.sub('[^\w\s]',eval_match, line) print a - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdK0fDvn/4H0LjDwRAuipAKDFqOeQQkJ+WkaI+veIgC8oEn9/CQCfUfNO xb7AT8W04B/F684i+Lw6kxw= =5mPe -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Thu May 25 03:02:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 May 2006 18:02:19 -0700 (PDT) Subject: [Tutor] class Writer In-Reply-To: <20060524233453.80196.qmail@web51605.mail.yahoo.com> References: <20060524233453.80196.qmail@web51605.mail.yahoo.com> Message-ID: On Wed, 24 May 2006, Christopher Spears wrote: > I've been working my way through an online tutorial and came across the > following sample script: > > import sys > > class Writer: > def __init__(self, filename): > self.filename = filename > def write(self, msg): > f = file(self.filename, 'a') > f.write(msg) > f.close() Just as a side note: the 'logging' module in the Standard Library would probably be the way to handle things like this. http://www.python.org/doc/lib/module-logging.html > I understand that the class is taking the strings from stdout (supplied > by the print statements) and writing them to a text file. Not exactly. Something more subtle is happening. Every call to the print statement causes Python to do something like: print foo ====> sys.stdout.write(str(foo) + "\n") At least, to a first approximation, that's what 'print' does. We can try it out by, from a clean interpreter, doing: ###### import sys sys.stdout.write("hello") sys.stdout.write("world") ###### We should see "helloworld" because we have not told sys.stdout to write a newline to separate the two words. Going back to the code that you show: sys.stdout = Writer('tmp.log') is explicitely reassigning the standard output file to something else entirely. Future print statements talk to the Writer instance as if it were standard output. Does this distinction clear things up? From andre.roberge at gmail.com Thu May 25 03:14:59 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 24 May 2006 22:14:59 -0300 Subject: [Tutor] help requested: port not free, under Windows XP Message-ID: <7528bcdd0605241814q1c66a6eegae4f5c93d7be5f10@mail.gmail.com> [message re-sent; original seemed not to have been received, according to the archives. Apologies if this is not the case.] Hi all- ===Preliminaries=== I wrote a new app (Crunchy Frog) which is meant to transform "boring" traditional python tutorial into truly interactive experiences. It is still at an alpha stage but is promising imo; for those interested, you can find it at: https://sourceforge.net/project/showfiles.php?group_id=125834 It currently requires both CherryPy and Elementtree as additional packages. Starting the app launch your favourite browser (or open a new tab/window). This is done through the instruction: cherrypy.server.start_with_callback(webbrowser.open, (' http://localhost:8080',), ) ===Now the question=== Someone on edu-sig tried to get it working on her computer running Windows XP home edition (just like mine, where it works fine!). However, she gets an error message about " port 8080 not free on local host." This is after she made sure nothing else internet-related was working. [This kind of message can happen if another instance of Crunchy Frog is already running, which she made sure wasn't.] I am stumped.... I am thinking it might be a firewall issue (I have ZoneAlarm installed myself), but I am really not sure.... I thought there were enough smart and friendly people here that I could find an answer ;-) Thanks in advance for any help, pointers, etc. Of course, you can reply directly on the edu-sig list if you want! Andr? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060524/ec665d14/attachment.html From kent37 at tds.net Thu May 25 03:16:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 May 2006 21:16:38 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4474F170.7060806@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> Message-ID: <44750576.6090105@tds.net> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Wow!!.. > > That awesome! > > > My goal was not to make it a one-liner per-se.. > > I was simply trying to show the functionality I was trying to duplicate. > > Boiling your one-liner down into a multi-line piece of code, I did: > > #!c:\python24\python > > import re,sys > > a = open(r'e:\pycode\csums.txt','rb').readlines() > > for line in a: You probably want to open the file in text mode, not binary. You don't have to read all the lines of the file, you can iterate reading one line at a time. Combining these two changes, the above two lines consolidate to for line in open(r'e:\pycode\csums.txt'): > print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) > > > Breaking down the command, you appear to be calling an un-named function > to act against any characters trapped by the regular expression. > > Not familiar with lamda :). It is a way to make an anonymous function, occasionally abused to write Python one-liners. You could just as well spell it out: def hexify(match): return ''%%%2X' % ord(match.group()) print re.sub(r'([^\w\s])', hexify, line) > > The un-named function does in-place transformation of the character to > the established hex value. > > > Does this sound right? Yes. Kent From cspears2002 at yahoo.com Thu May 25 03:30:31 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 24 May 2006 18:30:31 -0700 (PDT) Subject: [Tutor] _next Message-ID: <20060525013031.73375.qmail@web51606.mail.yahoo.com> How does this script work? #!/usr/bin/python class IteratorExample: def __init__(self, s): self.s = s self.next = self._next().next self.exhausted = 0 def _next(self): if not self.exhausted: flag = 0 for x in self.s: if flag: flag = 0 yield x else: flag = 1 self.exhausted = 1 def __iter__(self): return self._next() def main(): a = IteratorExample('edcba') for x in a: print x print '=' * 30 a = IteratorExample('abcde') print a.next() print a.next() print a.next() print a.next() print a.next() print a.next() if __name__ == '__main__': main() Here is the output: d b ============================== b d Traceback (most recent call last): File "./python_101_iterator_class.py", line 35, in ? main() File "./python_101_iterator_class.py", line 29, in main print a.next() StopIteration I think a lot of my confusion comes from not understanding what _next is. I got this script from an online tutorial at python.org. Is there a better way to write the script, so I can actually understand it? "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From kent37 at tds.net Thu May 25 04:31:32 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 May 2006 22:31:32 -0400 Subject: [Tutor] _next In-Reply-To: <20060525013031.73375.qmail@web51606.mail.yahoo.com> References: <20060525013031.73375.qmail@web51606.mail.yahoo.com> Message-ID: <44751704.3010509@tds.net> Christopher Spears wrote: > How does this script work? > > #!/usr/bin/python > > class IteratorExample: > def __init__(self, s): > self.s = s > self.next = self._next().next > self.exhausted = 0 > def _next(self): > if not self.exhausted: > flag = 0 > for x in self.s: > if flag: > flag = 0 > yield x > else: > flag = 1 > self.exhausted = 1 > def __iter__(self): > return self._next() > > def main(): > a = IteratorExample('edcba') > for x in a: > print x > print '=' * 30 > a = IteratorExample('abcde') > print a.next() > print a.next() > print a.next() > print a.next() > print a.next() > print a.next() > > if __name__ == '__main__': > main() > > > Here is the output: > > d > b > ============================== > b > d > Traceback (most recent call last): > File "./python_101_iterator_class.py", line 35, in ? > main() > File "./python_101_iterator_class.py", line 29, in > main > print a.next() > StopIteration > > I think a lot of my confusion comes from not > understanding what _next is. I got this script from > an online tutorial at python.org. Is there a better > way to write the script, so I can actually understand it? _next() is a generator - a function which, when called, returns an iterator. Each time the yield statement is reached, the iterator returns a new value. When the generator returns, the iteration ends. Generators are a very convenient way to package up iteration and state. Here is a simple example of a generator that counts to 2: In [1]: def count2(): ...: yield 1 ...: yield 2 ...: ...: You can iterate over the generator in a for loop: In [2]: for i in count2(): ...: print i ...: ...: 1 2 If you prefer you can explicitly call the next() method, which is a common method of all iterators: In [3]: c=count2() In [4]: c.next() Out[4]: 1 In [5]: c.next() Out[5]: 2 When the iterator is exhausted, it raises StopIteration. Again, this is standard behaviour for all iterators: In [6]: c.next() ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? StopIteration Your example seems like a complicated way to wrap an iterable in an iterator which returns every other element. Maybe I am missing something, but I would write it like this: In [7]: def skipper(seq): ...: it = iter(seq) # make sure we have an iterator ...: while True: ...: it.next() # skip a value ...: yield it.next() # return a value ...: ...: In [8]: for a in skipper('edcba'): ...: print a ...: ...: d b In [9]: a = skipper('edcba') In [10]: a.next() Out[10]: 'd' In [11]: a.next() Out[11]: 'b' In [12]: a.next() ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? File "", line 5, in skipper StopIteration You can read more about the iterator protocol and generators here: http://www.python.org/doc/2.2.3/whatsnew/node4.html http://www.python.org/doc/2.2.3/whatsnew/node5.html Read the referenced PEPs for all the juicy details. Hmm, a little Googling finds the tutorial you mention here: http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004460000000000000000 IMO this is a very confused example. You can write class-based iterators and you can write generator-based iterators, but combining them both to achieve such a simple result makes no sense to me. Kent From amonroe at columbus.rr.com Thu May 25 05:11:12 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 24 May 2006 23:11:12 -0400 Subject: [Tutor] help requested: port not free, under Windows XP In-Reply-To: <7528bcdd0605241814q1c66a6eegae4f5c93d7be5f10@mail.gmail.com> References: <7528bcdd0605241814q1c66a6eegae4f5c93d7be5f10@mail.gmail.com> Message-ID: <761304790639.20060524231112@columbus.rr.com> > Someone on edu-sig tried to get it working on her computer running Windows > XP home edition (just like mine, where it works fine!). However, she gets an > error message about > " port 8080 not free on local host." This is after she made sure nothing > else internet-related was working. [This kind of message can happen if > another instance of Crunchy Frog is already running, which she made sure > wasn't.] > I am stumped.... Try netstat -o (shows the owning pid for each network port) Alan From alan.gauld at freenet.co.uk Thu May 25 06:13:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 25 May 2006 05:13:17 +0100 Subject: [Tutor] class Writer References: <20060524233453.80196.qmail@web51605.mail.yahoo.com> Message-ID: <002f01c67fb1$8d0b8840$0c01a8c0@XPpro> > I understand that the class is taking the strings from > stdout (supplied by the print statements) and writing > them to a text file. Does the user need to explicitly > call the write function? For example: > > sys.stdout = Writer('tmp.log').write(whatever the > message is) No, that's what print does. The Writer is replacing the stdout file-like object with your Writer file-like object. print just uses whatever file-like object is connected to stdout. Alan G. From alan.gauld at freenet.co.uk Thu May 25 06:17:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 25 May 2006 05:17:23 +0100 Subject: [Tutor] Question on regular expressions References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> Message-ID: <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> > a = open(r'e:\pycode\csums.txt','rb').readlines() > > for line in a: > print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), > line) Or just for line in open(r'e:\pycode\csums.txt','rb'): print..... > Breaking down the command, you appear to be calling an un-named > function > to act against any characters trapped by the regular expression. > > Not familiar with lamda :). You ae absolutely right. It creates an un-named(or anonymous function). :-) > The un-named function does in-place transformation of the character > to > the established hex value. Its actually the call to re.sub() that makes in in place. > How would you reverse the process from a python point of view? Just write a reverse function for the lamda... Alan G. From alan.gauld at freenet.co.uk Thu May 25 06:19:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 25 May 2006 05:19:58 +0100 Subject: [Tutor] Question on regular expressions (fwd) References: Message-ID: <003701c67fb2$7bf9c2f0$0c01a8c0@XPpro> > Your code put me right on track. > > - From that point, I crafted the following code. > > What is confusing is how to take the captured character and > transform it > into a 3 digit hex value. In general I prefer to use string formatting to convert into hex format. print "%3X% % myValue you can play around with the length specifier, left/right formatting etc etc. Think sprintf in C... Alan G. From andre.roberge at gmail.com Wed May 24 23:53:34 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 24 May 2006 18:53:34 -0300 Subject: [Tutor] help requested: port not free, under Windows XP Message-ID: <7528bcdd0605241453r51056c07q225dc1db24f6ba50@mail.gmail.com> Hi all- ===Preliminaries=== I wrote a new app (Crunchy Frog) which is meant to transform "boring" traditional python tutorial into truly interactive experiences. It is still at an alpha stage but is promising imo; for those interested, you can find it at: https://sourceforge.net/project/showfiles.php?group_id=125834 It currently requires both CherryPy and Elementtree as additional packages. Starting the app launch your favourite browser (or open a new tab/window). This is done through the instruction: cherrypy.server.start_with_callback(webbrowser.open, (' http://localhost:8080',), ) ===Now the question=== Someone on edu-sig tried to get it working on her computer running Windows XP home edition (just like mine, where it works fine!). However, she gets an error message about " port 8080 not free on local host." This is after she made sure nothing else internet-related was working. [This kind of message can happen if another instance of Crunchy Frog is already running, which she made sure wasn't.] I am stumped.... I am thinking it might be a firewall issue (I have ZoneAlarm installed myself), but I am really not sure.... I thought there were enough smart and friendly people here that I could find an answer ;-) Thanks in advance for any help, pointers, etc. Of course, you can reply directly on the edu-sig list if you want! Andr? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060524/9cc6a582/attachment.html From rschroev_nospam_ml at fastmail.fm Thu May 25 10:16:43 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 25 May 2006 10:16:43 +0200 Subject: [Tutor] _next In-Reply-To: <20060525013031.73375.qmail@web51606.mail.yahoo.com> References: <20060525013031.73375.qmail@web51606.mail.yahoo.com> Message-ID: Christopher Spears schreef: > How does this script work? > > #!/usr/bin/python > > class IteratorExample: > def __init__(self, s): > self.s = s > self.next = self._next().next > self.exhausted = 0 > def _next(self): > if not self.exhausted: > flag = 0 > for x in self.s: > if flag: > flag = 0 > yield x > else: > flag = 1 > self.exhausted = 1 > def __iter__(self): > return self._next() I always use generator functions like this to achieve the same effect: def IteratorExample(): flag = 0 for x in s: if flag: flag = 0 yield x else: flag = 1 Much less boilerplate and behind-the-scenes bookkeeping, so it's easier to type and understand. Result is the same: >>> a = IteratorExample('edcba') >>> for x in a: print x d b >>> a = IteratorExample('edcba') >>> print a.next() d >>> print a.next() b >>> print a.next() Traceback (most recent call last): File "", line 1, in -toplevel- print a.next() StopIteration -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rschroev_nospam_ml at fastmail.fm Thu May 25 12:55:28 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 25 May 2006 12:55:28 +0200 Subject: [Tutor] _next In-Reply-To: <20060525013031.73375.qmail@web51606.mail.yahoo.com> References: <20060525013031.73375.qmail@web51606.mail.yahoo.com> Message-ID: Christopher Spears schreef: > How does this script work? > > #!/usr/bin/python > > class IteratorExample: > def __init__(self, s): > self.s = s > self.next = self._next().next > self.exhausted = 0 > def _next(self): > if not self.exhausted: > flag = 0 > for x in self.s: > if flag: > flag = 0 > yield x > else: > flag = 1 > self.exhausted = 1 > def __iter__(self): > return self._next() > > def main(): > a = IteratorExample('edcba') > for x in a: > print x Maybe I should try to explain what's happening instead of only offering an alternative. It's somewhat complicated by the fact that this is a very convoluted example IMO. To be able to use an object in a for loop like that, it needs an __iter__() method. That method is called behind the scenes when the for loop is started, and it should return an iterator object. An iterator object is an object with a next() method that returns the next element each time it's called, and raises StopIteration if there are no more elements. Useless but simple example: class Count: def __init__(self): self.max = 10 self.index = 0 def __iter__(self): return self def next(self): self.index += 1 if self.index > self.max: raise StopIteration return self.index Objects instantiated from this class can be iterated over because of the __iter__() method. In this case, that method returns the object itself; therefore the object itself serves as the iterator object. It does this with its next() method, which simply returns the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and then raises StopIteration. A special kind of iterator object can be made with a generator function. That looks like a normal function, but uses yield instead of return. Each time its next element is requested, it runs until it encounters a yield statement. At that point, it passes the value specified in the yield statement to its caller and then freezes. When the next element is requested, it resumes operation directly after the yield statement where it was frozen until it encounters the next yield statement. And so on, until the function ends or executes the return statement or raises StopIteration. Again, a simple example: def backwards(s): for x in s[::-1]: yield x for x in backwards('edcba'): print x a b c d e Now, in your example the two are mixed. To make matters somewhat less complicated, I commented some lines that are totally useless; you should ignore them: class IteratorExample: def __init__(self, s): self.s = s #self.next = self._next().next #self.exhausted = 0 def _next(self): #if not self.exhausted: flag = 0 for x in self.s: if flag: flag = 0 yield x else: flag = 1 #self.exhausted = 1 def __iter__(self): return self._next() The _next() method is a generator function as I described above, which creates an iterator object when called. The __iter__() method just calls that generator function and returns the result to its caller. HTH -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From andrew.arobert at gmail.com Thu May 25 14:13:28 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 08:13:28 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> Message-ID: <44759F68.8050109@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone I did a comparison of the output between the perl and python methodology. They do basically the same thing but the perl form seems to be more "true" The python method inserts extra blank lines after each hex value line. For example: Original text: def handler(signal, frame): """ Trap signal interrupts if they occur """ Converted In Perl: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Converted In Python: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Does anyone know why this might be? Is the print statement inserting a artificial new line character? If so, how cam I remove that? The python code I am using is: import re,sys for line i open(r'e:\pycode\sigh.txt','rb'): print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) The file is being opened in rb mode because eventually binary files would be opened via this method as well. Alan Gauld wrote: >> a = open(r'e:\pycode\csums.txt','rb').readlines() >> >> for line in a: >> print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) > > Or just > > for line in open(r'e:\pycode\csums.txt','rb'): > print..... > >> Breaking down the command, you appear to be calling an un-named function >> to act against any characters trapped by the regular expression. >> >> Not familiar with lamda :). > > You ae absolutely right. > It creates an un-named(or anonymous function). :-) > >> The un-named function does in-place transformation of the character to >> the established hex value. > > Its actually the call to re.sub() that makes in in place. > >> How would you reverse the process from a python point of view? > > Just write a reverse function for the lamda... > > Alan G. > > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdZ9oDvn/4H0LjDwRAo89AJwJ64+wpfOnboxw4/+w8PhmZBzgwACfYH7C VPW5VPyqSWhAUgkoOBorjJM= =bOj0 -----END PGP SIGNATURE----- From kent37 at tds.net Thu May 25 14:22:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 May 2006 08:22:52 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <44759F68.8050109@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> Message-ID: <4475A19C.5000802@tds.net> Andrew Robert wrote: > The python method inserts extra blank lines after each hex value line. > Does anyone know why this might be? > > Is the print statement inserting a artificial new line character? Yes, this is a feature of print, it always inserts a newline. To avoid this, use sys.stdout.write() instead of print: for line i open(r'e:\pycode\sigh.txt','rb'): line = re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) sys.stdout.write(line) Kent > > If so, how cam I remove that? > > > The python code I am using is: > > > > import re,sys > > for line i open(r'e:\pycode\sigh.txt','rb'): > print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) From andre.roberge at gmail.com Thu May 25 14:34:03 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 25 May 2006 09:34:03 -0300 Subject: [Tutor] help requested: port not free, under Windows XP In-Reply-To: <44751EB6.3060704@mitechie.com> References: <7528bcdd0605241814q1c66a6eegae4f5c93d7be5f10@mail.gmail.com> <44751EB6.3060704@mitechie.com> Message-ID: <7528bcdd0605250534t1098da97nfb83c5b3cedb22f6@mail.gmail.com> On 5/25/06, Richard Harding wrote: > > Andre Roberge wrote: > > ===Now the question=== > > Someone on edu-sig tried to get it working on her computer running > > Windows XP home edition (just like mine, where it works fine!). > > However, she gets an error message about > > " port 8080 not free on local host." This is after she made sure > > nothing else internet-related was working. [This kind of message can > > happen if another instance of Crunchy Frog is already running, which > > she made sure wasn't.] > > > > > smart and friendly people here that I could find an answer ;-) > Ideas: > > 1) Built in XP firewall, what SP is she at vs what you might have? > 2) 8080 is a common port for proxy servers and alternate web configs so > my first suggestion would be to change the app to not use a port that is > so commonly used for something else. > 3) In the end I would just try to port scan the machine and see if it is > listening on port 8080 and then you're stuck trying to find out why. > There are several ports scanners for windows you can download a trial > of. I personally just use nmap. Thank you Rick (and Alan) for your suggestions which I forwarded to Catherine, would-be-user of Crunchy Frog. Apparently Catherine was using port 8080 as a proxy server; changing it made everything work. This also tells me that I should use a different number as a default. I'll now go back to just being a reader of this list, with some rare attempts at answering questions. Andr? Rick > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060525/9cd25fd6/attachment.html From andrew.arobert at gmail.com Thu May 25 14:45:54 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 08:45:54 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475A19C.5000802@tds.net> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> Message-ID: <4475A702.3010005@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Great! Taking this a little further along, I wrote the converted file to a new file using: import re,sys output = open(r'e:\pycode\out_test.txt','wb') for line in open(r'e:\pycode\sigh.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)) output.close() Not elegant but its strictly for test :) Last part and we can call it a day. How would you modify the lambda statement to covert a the hex value back to its original value? Do I need to incorporate base64.16basedecode somehow? The original perl code to covert back to normal is: `perl -ple 's/(?:%([0-9A-F]{2}))/chr hex $1/eg' somefiletxt Kent Johnson wrote: > Yes, this is a feature of print, it always inserts a newline. To avoid > this, use sys.stdout.write() instead of print: > for line i open(r'e:\pycode\sigh.txt','rb'): > line = re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) > sys.stdout.write(line) > > Kent > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdacCDvn/4H0LjDwRAkTWAJ4/KS6WnAgUraPZLmyPCQ45izq5tQCgl7sR nkZbIauRcdlavA89ZhnDSuM= =YZPS -----END PGP SIGNATURE----- From kieran.flanagan at gmail.com Thu May 25 15:02:54 2006 From: kieran.flanagan at gmail.com (kieran flanagan) Date: Thu, 25 May 2006 14:02:54 +0100 Subject: [Tutor] Pexpect logging out from a remote terminal Message-ID: Hey I have a script that logs into a remote terminal over ssh and executes a script i.e. 1. Script logs into remote terminal over ssh 2. Executes another script that resides on the remote terminal, with the command 'child.sendline(cmdString)', where cmdString is a reference to the local script being run. So I would like run the command 'child.sendline(cmdString)' in the background, grab the output from the local script being run on the remote terminal, redirect it into a logfile and I will have another function that monitors when this is complete and then proceeds. I have looked over numerous examples in my python cookbook but cannot see anything that I could adapt to this. Any suggestions on what I could do or where I could find some helpful info. Thanks K -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060525/d69e5ca6/attachment.html From kent37 at tds.net Thu May 25 15:03:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 May 2006 09:03:57 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475A702.3010005@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> Message-ID: <4475AB3D.9080404@tds.net> Andrew Robert wrote: > Taking this a little further along, I wrote the converted file to a new > file using: > > > import re,sys > > output = open(r'e:\pycode\out_test.txt','wb') > > for line in open(r'e:\pycode\sigh.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' % > ord(s.group()), line)) > > output.close() > > > Not elegant but its strictly for test :) > > > Last part and we can call it a day. > > How would you modify the lambda statement to covert a the hex value back > to its original value? Use int(s, 16) to convert a base 16 string to an integer, and chr() to convert the int to a string. So something like this: lambda s: chr(int(s.group(), 16))) Kent From rschroev_nospam_ml at fastmail.fm Thu May 25 15:16:18 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 25 May 2006 15:16:18 +0200 Subject: [Tutor] help requested: port not free, under Windows XP In-Reply-To: <7528bcdd0605250534t1098da97nfb83c5b3cedb22f6@mail.gmail.com> References: <7528bcdd0605241814q1c66a6eegae4f5c93d7be5f10@mail.gmail.com> <44751EB6.3060704@mitechie.com> <7528bcdd0605250534t1098da97nfb83c5b3cedb22f6@mail.gmail.com> Message-ID: Andre Roberge schreef: > Thank you Rick (and Alan) for your suggestions which I forwarded to > Catherine, would-be-user of Crunchy Frog. Apparently Catherine was > using port 8080 as a proxy server; changing it made everything work. > This also tells me that I should use a different number as a default. You might want to avoid any of the numbers in http://www.iana.org/assignments/port-numbers or http://www.freebsd.org/cgi/cvsweb.cgi/src/etc/services?rev=1.102.8.1&content-type=text/x-cvsweb-markup, as they are already registered for other uses. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From andrew.arobert at gmail.com Thu May 25 15:37:47 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 09:37:47 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475AB3D.9080404@tds.net> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> Message-ID: <4475B32B.6060606@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, I tried: output = open(r'e:\pycode\new_test.txt','wb') for line in open(r'e:\pycode\out_test.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) % ord(s.group()), line)) This generated the traceback: File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8 output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) % ord(s.group()), line)) ^ SyntaxError: invalid syntax By any chance, do you see where the syntax issue is? Kent Johnson wrote: > Andrew Robert wrote: > Use int(s, 16) to convert a base 16 string to an integer, and chr() to > convert the int to a string. So something like this: > lambda s: chr(int(s.group(), 16))) > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbMrDvn/4H0LjDwRAi09AKC1I6XIcXiqYmpk4hpcbnkwux1NawCgt/zp xySHXPrh5JncZphAcVRtbtI= =xtr9 -----END PGP SIGNATURE----- From kent37 at tds.net Thu May 25 15:56:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 May 2006 09:56:02 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475B32B.6060606@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> Message-ID: <4475B772.4050009@tds.net> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi all, > > I tried: > > > output = open(r'e:\pycode\new_test.txt','wb') > > for line in open(r'e:\pycode\out_test.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > > This generated the traceback: > > File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8 > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > ^ > SyntaxError: invalid syntax > > > By any chance, do you see where the syntax issue is? Take out " % ord(s.group())" - the result of chr() is the actual string you want, not a format string. The syntax error is caused by mismatched parentheses. Kent From dyoo at hkn.eecs.berkeley.edu Thu May 25 16:01:59 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 May 2006 07:01:59 -0700 (PDT) Subject: [Tutor] Question on regular expressions In-Reply-To: <4475B32B.6060606@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> Message-ID: > for line in open(r'e:\pycode\out_test.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) Let's add some whitespace. output.write(re.sub(r'([^\w\s])', lambda s: chr( int(s.group(), 16) ) ) % ord(s.group()), line)) I do see at least one too many parens here, so that's something you should look at. But I'd also recommend writing a helper function here. Just because you can do this in one line doesn't mean you have to. *grin* It might be useful to change the lambda back to a helper function. From andrew.arobert at gmail.com Thu May 25 16:08:22 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 10:08:22 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475B772.4050009@tds.net> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> <4475B772.4050009@tds.net> Message-ID: <4475BA56.2010500@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 When I alter the code to: import re,sys output = open(r'e:\pycode\new_test.txt','wb') for line in open(r'e:\pycode\out_test.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) , line) output.close() I get the trace: Traceback (most recent call last): File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8, in ? output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) , line) TypeError: sub() takes at least 3 arguments (2 given) It appears that the code is not recognizing the line. I checked the parentheses and they appear to be properly enclosed. Any ideas? Kent Johnson wrote: > Take out " % ord(s.group())" - the result of chr() is the actual string > you want, not a format string. > > The syntax error is caused by mismatched parentheses. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbpWDvn/4H0LjDwRAhEmAJ9WSfKitH1VgsTD5kTLI4cWP5YZRwCgs0mz Y9jl5l6Q/VZe6NmUaibZGa4= =nezG -----END PGP SIGNATURE----- From andrew.arobert at gmail.com Thu May 25 16:12:53 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 10:12:53 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> Message-ID: <4475BB65.7040702@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 lol.. Glutton for punishment I guess. I tried removing the last parentheses but I then get an error that two arguments are passed when three are expected. Danny Yoo wrote: > > >> for line in open(r'e:\pycode\out_test.txt','rb') : >> output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), >> 16))) % ord(s.group()), line)) > > > Let's add some whitespace. > > output.write(re.sub(r'([^\w\s])', > lambda s: chr( > int(s.group(), 16) > ) > ) % ord(s.group()), line)) > > I do see at least one too many parens here, so that's something you > should look at. > > But I'd also recommend writing a helper function here. Just because you > can do this in one line doesn't mean you have to. *grin* It might be > useful to change the lambda back to a helper function. > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbtlDvn/4H0LjDwRAqg+AJ0SZY/T3kCpG+3qWX3F3yRSt73P7ACdFsZQ LnBhWh95EfuHA+eMkz6gkF4= =C0oN -----END PGP SIGNATURE----- From kent37 at tds.net Thu May 25 16:38:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 May 2006 10:38:39 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475BA56.2010500@gmail.com> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> <4475B772.4050009@tds.net> <4475BA56.2010500@gmail.com> Message-ID: <4475C16F.8030104@tds.net> Andrew Robert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > When I alter the code to: > > import re,sys > > output = open(r'e:\pycode\new_test.txt','wb') > > for line in open(r'e:\pycode\out_test.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) > , line) > > output.close() > > I get the trace: > > Traceback (most recent call last): > File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8, in ? > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) , line) > TypeError: sub() takes at least 3 arguments (2 given) > > It appears that the code is not recognizing the line. > > I checked the parentheses and they appear to be properly enclosed. > > Any ideas? You have an argument in the wrong place. Stop trying to do everything in one line! Put the lambda in a def'd function. Put the re.sub on it's own line. You are tripping over unnecessary complexity. I'm not going to fix it any more. Kent From andrew.arobert at gmail.com Thu May 25 17:49:25 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 11:49:25 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475C16F.8030104@tds.net> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> <4475B772.4050009@tds.net> <4475BA56.2010500@gmail.com> <4475C16F.8030104@tds.net> Message-ID: <4475D205.9000508@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Kent, Sorry for causing so much trouble. I am not married to either a single or multi-line solution one way or another. Just a solution that works. Based on something by Danny Yoo provided, I had started with something like: import re,base64 # Evaluate captured character as hex def ret_hex(value): return base64.b16encode(value) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def eval_match(match): return ret_ascii(match.group(0)) out=open(r'e:\pycode\sigh.new2','wb') # Read each line, pass any matches on line to function for # line in file.readlines(): for line in open(r'e:\pycode\sigh.new','rb'): print (re.sub('[^\w\s]',eval_match, line)) The char to hex pass works but omits the leading x. The hex to char pass does not appear to work at all. No error is generated. It just appears to be ignored. Kent Johnson wrote: > Andrew Robert wrote: > > You have an argument in the wrong place. Stop trying to do everything in > one line! Put the lambda in a def'd function. Put the re.sub on it's own > line. You are tripping over unnecessary complexity. I'm not going to fix > it any more. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: arobert at mfs.com Linux User Number: #201204 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEddHSDvn/4H0LjDwRAibnAJ4/6/IiPtz7k+jIa01kRe1X25UNkACfaq24 bbqKqyOZyLpCRBEHbrO7H7A= =8+rq -----END PGP SIGNATURE----- From ebbaalm at uiuc.edu Thu May 25 19:58:54 2006 From: ebbaalm at uiuc.edu (Ebba Cecilia Ovesdotter Alm) Date: Thu, 25 May 2006 12:58:54 -0500 Subject: [Tutor] Q on path information Message-ID: <8bf8cdc9.be11827a.826b700@expms2.cites.uiuc.edu> I have 2 questions I'm curious about (BTW, I use the default python installation as delivered with Linux SuSe 10.0) (1) How can I print the path to the python I'm using and where it imports built-in modules? python.sys returns (i probably want 64bit, so this seems ok): /usr/lib/python24.zip /usr/lib64/python2.4 /usr/lib64/python2.4/plat-linux2 /usr/lib64/python2.4/lib-tk /usr/lib64/python2.4/lib-dynload /usr/lib64/python2.4/site-packages /usr/lib64/python2.4/site-packages/Numeric /usr/lib64/python2.4/site-packages/PIL But, "which python" in the shell returns /usr/bin/python And "whereis python" returns python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/include/python /usr/include/python2.4 /usr/share/man/man1/python.1.gz Does this mean I am using the python executable in "/usr/bin/python/" but it then looks for built-in modules in "/usr/lib64/python2.4/"? (2) A clarification question: PYTHONPATH is not needed as long as one just imports built-in modules (such as re or sys) or own modules from the same directory as the importing script, right? For example, running "python foo.py" on the command line, where foo.py imports a module "foo2.py" from the same directory, the current directory is inferred automatically, right? Thanks! E. Cecilia Ovesdotter Alm Graduate student/Dept. of Linguistics, UIUC http://www.linguistics.uiuc.edu/ebbaalm/ Office: 2013 Beckman Phone: (217) 721-7387 From andrew.arobert at gmail.com Thu May 25 20:14:40 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 14:14:40 -0400 Subject: [Tutor] Question on regular expressions In-Reply-To: <4475C16F.8030104@tds.net> References: <44748A0A.4010602@gmail.com> <4474F170.7060806@gmail.com> <003301c67fb2$1fcfdbe0$0c01a8c0@XPpro> <44759F68.8050109@gmail.com> <4475A19C.5000802@tds.net> <4475A702.3010005@gmail.com> <4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com> <4475B772.4050009@tds.net> <4475BA56.2010500@gmail.com> <4475C16F.8030104@tds.net> Message-ID: <4475F410.9020003@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Everyone, Thanks for all of your patience on this. I finally got it to work. Here is the completed test code showing what is going on. Not cleaned up yet but it works for proof-of-concept purposes. #!/usr/bin/python import re,base64 # Evaluate captured character as hex def ret_hex(value): return '%'+base64.b16encode(value) # Evaluate the value of whatever was matched def enc_hex_match(match): return ret_hex(match.group(0)) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def enc_ascii_match(match): arg=match.group() #remove the artifically inserted % sign arg=arg[1:] # decode the result return ret_ascii(arg) def file_encoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new','wb') for line in open(r'e:\pycode\sigh.txt','rb'): output.write( (re.sub('[^\w\s]',enc_hex_match, line)) ) output.close() def file_decoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new2','wb') for line in open(r'e:\pycode\sigh.new','rb'): output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line)) output.close() file_encoder() file_decoder() -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdfQQDvn/4H0LjDwRAnbIAJ0cD9fdtIqtpfksP07n02Er9YMPiwCfTSsC pCVDgnQ8pbZS40BuA8gNNBQ= =mPoG -----END PGP SIGNATURE----- From ulandreman at msn.com Thu May 25 21:20:20 2006 From: ulandreman at msn.com (URBAN LANDREMAN) Date: Thu, 25 May 2006 14:20:20 -0500 Subject: [Tutor] Unable to import xxx.pyd Message-ID: I'm debugging a program where I'm trying to import a file named xxx.pyd. I test the logic interactively with IDLE and see that it makes a difference on which directory the file xxx.pyd is located. That is, I can get it to work when xxx.pyd is on the path. However, when I run the program in batch #!/usr/local/bin/python import cgitb; cgitb.enable() print "Content-type: text/html" print print "

"
import sys
print sys.path
import xxx

I get the error message: No module named xxx, even though I know that the 
file xxx.pyd is on the path.  If I put a file xxx.py in the same folder, the 
system finds that file.

The file xxx.pyd has security numeric value 755, so the system should be 
able to find it.

I'm baffled.

Any suggestions of what my be causing the system to not find xxx.pyd?

Thanks.


Urban Landreman



From doug.shawhan at gmail.com  Thu May 25 21:34:24 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Thu, 25 May 2006 14:34:24 -0500
Subject: [Tutor] partial string matching in list comprehension?
Message-ID: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>

I have a series of lists to compare with a list of exclusionary terms.



junkList =["interchange",  "ifferen", "thru"]

The comparison lists have one or more elements, which may or may not contain
the junkList elements somewhere within:

l = ["My skull hurts", "Drive the thruway", "Interchangability is not my
forte"]

... output would be

["My skull hurts"]

I have used list comprehension to match complete elements, how can I do a
partial match?

def removeJunk(reply, junkList):
        return [x for x in reply if x not in junkList]

It would be so much prettier than searching through each list element for
each term - I tend to get lost in a maze of twisty corridors, all alike.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060525/bd676bd7/attachment.htm 

From carroll at tjc.com  Thu May 25 21:52:19 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 25 May 2006 12:52:19 -0700 (PDT)
Subject: [Tutor] Question on regular expressions (fwd)
In-Reply-To: <003701c67fb2$7bf9c2f0$0c01a8c0@XPpro>
Message-ID: 

On Thu, 25 May 2006, Alan Gauld wrote:

> In general I prefer to use string formatting to convert into hex 
> format.

I'm a big fan of hexlify:

>>> from binascii import hexlify
>>> s="abc-123"
>>> hexlify(s)
'6162632d313233'




From carroll at tjc.com  Thu May 25 21:57:36 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 25 May 2006 12:57:36 -0700 (PDT)
Subject: [Tutor] Question on regular expressions
In-Reply-To: <4475A19C.5000802@tds.net>
Message-ID: 

On Thu, 25 May 2006, Kent Johnson wrote:

> Yes, this is a feature of print, it always inserts a newline.

Well, you can get rid of the newline by ending with a comma, but it still 
will insert spaces:

>>> for ch in "abc":
...  print ch
...
a
b
c
>>> for ch in "abc":
...  print ch,
...
a b c
>>>

I recall a way to get around that, too, but don't remember what it was.  
Your suggestion:

>  To avoid this, use sys.stdout.write() instead of print:

Is the cleanest way to go, rather than arm-wrestling with "print".



From alan.gauld at freenet.co.uk  Thu May 25 22:54:59 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 25 May 2006 21:54:59 +0100
Subject: [Tutor] Question on regular expressions
References: <44748A0A.4010602@gmail.com>		<4474F170.7060806@gmail.com>	<003301c67fb2$1fcfdbe0$0c01a8c0@XPpro>	<44759F68.8050109@gmail.com>	<4475A19C.5000802@tds.net><4475A702.3010005@gmail.com>
	<4475AB3D.9080404@tds.net> <4475B32B.6060606@gmail.com>
Message-ID: <003a01c6803d$7ce153a0$0c01a8c0@XPpro>

> for line in open(r'e:\pycode\out_test.txt','rb') :
>    output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
> 16))) % ord(s.group()), line))
>
> This generated the traceback:
>
> File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8
>    output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
> 16))) % ord(s.group()), line))
>
>                         ^
> SyntaxError: invalid syntax
>
>
> By any chance, do you see where the syntax issue is?

Andrew, This is a good place to use the Python interactive prompt.
Try the various bits in the interpreter to find out what causes the 
error.
To be honest I'd break that single line into at least 2 if not 3 lines
anyway purely from a debug and maintenance point of view.
You are in real danger of turning Python into perl here! :-)

As to your error:

output.write(
          re.sub(
                r'([^\w\s])',
                lambda s: chr(int(s.group(),16))
                    ) % ord(s.group()),
                  line))

the parens dont seem to match up... Or am I miscounting?

Alan G



From alan.gauld at freenet.co.uk  Thu May 25 23:39:21 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 25 May 2006 22:39:21 +0100
Subject: [Tutor] Q on path information
References: <8bf8cdc9.be11827a.826b700@expms2.cites.uiuc.edu>
Message-ID: <004c01c68043$af7655d0$0c01a8c0@XPpro>


> And "whereis python" returns 
> python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4
> /usr/include/python /usr/include/python2.4
> /usr/share/man/man1/python.1.gz
> 
> Does this mean I am using the python executable in
> "/usr/bin/python/" but it then looks for built-in modules in 
> "/usr/lib64/python2.4/"?

I'm no Suse expert but its common in Unix to have a standard 
name for a program which is a link to the latest version.

Thus I guess that /usr/bin/python is a link to whatever 
the current version is, in this case /usr/bin/python2.4.
When you upgrade the installer simply replaces the link 
to point to the new version, so you only have to type 
python to find it.

> (2) A clarification question: PYTHONPATH is not needed as long
> as one just imports built-in modules (such as re or sys) or
> own modules from the same directory as the importing script,
> right? For example, running "python foo.py" on the command
> line, where foo.py imports a module "foo2.py" from the same
> directory, the current directory is inferred automatically, right?

I think sio, it seems to be how windoze does it...
But I usually have PYTHONPATH set up so I can't be quite sure.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From bgailer at alum.rpi.edu  Fri May 26 00:16:33 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 25 May 2006 15:16:33 -0700
Subject: [Tutor] partial string matching in list comprehension?
In-Reply-To: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
References: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
Message-ID: <44762CC1.9050604@alum.rpi.edu>

doug shawhan wrote:
> I have a series of lists to compare with a list of exclusionary terms.
>
>
>
> junkList =["interchange",  "ifferen", "thru"]
>
> The comparison lists have one or more elements, which may or may not 
> contain the junkList elements somewhere within:
>
> l = ["My skull hurts", "Drive the thruway", "Interchangability is not 
> my forte"]
>
> ... output would be
>
> ["My skull hurts"]
>
> I have used list comprehension to match complete elements, how can I 
> do a partial match?
>
> def removeJunk(reply, junkList):
>         return [x for x in reply if x not in junkList]
>
> It would be so much prettier than searching through each list element 
> for each term - I tend to get lost in a maze of twisty corridors, all 
> alike.
Just say the magic word PLUGH! Be sure to pick up the batteries while 
you're in there.

How about re?

import re

Build the search pattern:
pattern = "|".join(junkList)

Compile it:
junkListPattern = re.compile(pattern)

def removeJunk(reply, junkListPattern):
        return [x for x in reply if not junkListPattern.search(x)]

*just with your  hands*

-- 
Bob Gailer
510-978-4454


From kent37 at tds.net  Fri May 26 03:00:16 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 25 May 2006 21:00:16 -0400
Subject: [Tutor] partial string matching in list comprehension?
In-Reply-To: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
References: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
Message-ID: <44765320.9070209@tds.net>

doug shawhan wrote:
> I have a series of lists to compare with a list of exclusionary terms.
> 
> junkList =["interchange",  "ifferen", "thru"]
> 
> The comparison lists have one or more elements, which may or may not 
> contain the junkList elements somewhere within:
> 
> l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
> forte"]
> 
> ... output would be
> 
> ["My skull hurts"]
> 
> I have used list comprehension to match complete elements, how can I do 
> a partial match?

One way is to use a helper function to do the test:

In [1]: junkList =["interchange",  "ifferen", "thru"]

In [2]: lst = ["My skull hurts", "Drive the thruway", "Interchangability
is not my forte"]

In [3]: def hasJunk(s):
     ...:     for junk in junkList:
     ...:         if junk in s:
     ...:             return True
     ...:     return False
     ...:

In [4]: [ s for s in lst if not hasJunk(s) ]
Out[4]: ['My skull hurts', 'Interchangability is not my forte']

Hmm, I guess spelling counts :-)
also you might want to make this case-insensitive by taking s.lower() in
hasJunk().

Another way is to make a regular expression that matches all the junk:

In [7]: import re

Escape the junk in case it has any re-special chars:
In [9]: allJunk = '|'.join(re.escape(junk) for junk in junkList)

In [10]: allJunk
Out[10]: 'interchange|ifferen|thru'

You could compile with re.IGNORECASE to make case-insensitive matches.
Spelling still counts though ;)

In [11]: junkRe = re.compile(allJunk)

In [13]: [ s for s in lst if not junkRe.search(s) ]
Out[13]: ['My skull hurts', 'Interchangability is not my forte']

My guess is the re version will be faster, at least if you don't count
the compile, but only testing will tell for sure:

In [14]: import timeit

In [18]: timeit.Timer(setup='from __main__ import hasJunk,lst', stmt='[
s for s in lst if not hasJunk(s) ]').timeit()
Out[18]: 11.921303685244915

In [19]: timeit.Timer(setup='from __main__ import junkRe,lst', stmt='[ s
for s in lst if not junkRe.search(s) ]').timeit()
Out[19]: 8.3083201915327223

So for this data using re is a little faster. Test with real data to be
sure!

Kent



From simplebob at gmail.com  Fri May 26 06:24:30 2006
From: simplebob at gmail.com (Daniel McQuay)
Date: Fri, 26 May 2006 00:24:30 -0400
Subject: [Tutor]  crontab or python mistake
Message-ID: <6d87ecf40605252124sa4518dtf37f076617287ead@mail.gmail.com>

hello list,

i am having a problem getting crontab to execute a python script. the script
works because i can execute it by using: python boxster_school_smtp.py from
a command line. i put a line in crontab that look like this: i know this is
not a linux mailing list but any help would be appreciated.


*/5     *       *       *       *       root    /usr/local/bin/python
/root/scripts/boxster_school_smtp.py


now like i said the python script works by using: python my_script.py from
the command line but when i use it in crontab i get some error. here is the
error that cron gives:


Traceback (most recent call last):
  File "/root/scripts/boxster_school_smtp.py", line 19, in ?
    mssg = open('mssg.txt', 'r').read()
IOError: [Errno 2] No such file or directory: ' emmssg.txt'


the emmssg.txt file is in the /root/script directory so i don't know why it
cant find it.

thanks again,

-- 
Daniel McQuay
simplebob at gmail.com
boxster.homelinux.org
814.825.0847
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060526/33b1cc4d/attachment-0001.html 
-------------- next part --------------
import smtplib
import os

emmssg = "/root/scripts/emmssg.txt"
smtpserver = 'mail.erieit.edu'
AUTHREQUIRED = 1 
smtpuser = 'dmcquay' 
smtppass = '******'  

#For testing purposes only!
RECIPIENTS = ['dmcquay at erieit.edu']

#This will be used after testing
#RECIPIENTS = ['slindsay at erieit.edu','dmccann at erieit.edu','mwebster at erieit.edu',
#              'arundstedler at erieit.edu','caustin-alford at erieit.edu',
#             'dmcquay at erieit.edu']

SENDER = 'dmcquay at erieit.edu'
emmssg = open('emmssg.txt').read()

session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
    session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, emmssg)

if smtpresult:
    errstr = ""
    for recip in smtpresult.keys():
        errstr = """Could not delivery mail to: %s

Server said: %s
%s

%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
    raise smtplib.SMTPException, errstr




From yi at yiqiang.net  Fri May 26 06:44:57 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Thu, 25 May 2006 21:44:57 -0700
Subject: [Tutor] crontab or python mistake
In-Reply-To: <6d87ecf40605252124sa4518dtf37f076617287ead@mail.gmail.com>
References: <6d87ecf40605252124sa4518dtf37f076617287ead@mail.gmail.com>
Message-ID: <447687C9.1050002@yiqiang.net>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Daniel McQuay wrote, On 05/25/2006 09:24 PM:
> Traceback (most recent call last):
>  File "/root/scripts/boxster_school_smtp.py", line 19, in ?
>    mssg = open('mssg.txt', 'r').read()
> IOError: [Errno 2] No such file or directory: ' emmssg.txt'
> 
Right, but I don't think the CWD for cron is in /root.  Try giving it an
absolute path.

- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

iD8DBQFEdofJtXlIMrUVVksRAhZOAJ9Gr8RPjS37u7IEaLdZMJjawvxMDgCghTCm
ub7rd1v+rrEAt2vTIpnwk4A=
=xhDj
-----END PGP SIGNATURE-----

From alan.gauld at freenet.co.uk  Fri May 26 09:32:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 26 May 2006 08:32:42 +0100
Subject: [Tutor] crontab or python mistake
References: <6d87ecf40605252124sa4518dtf37f076617287ead@mail.gmail.com>
Message-ID: <002e01c68096$939038b0$0c01a8c0@XPpro>


> IOError: [Errno 2] No such file or directory: ' emmssg.txt'

>
> the emmssg.txt file is in the /root/script directory so i 
> don't know why it cant find it.

The file may be there but crontab isn't. It runs the program 
as root and root's home directory is /.

For this kind of thing you need to either pass in the 
data directory as an argument or wrap the python script 
in a shell script that sets an environment variable to 
where your data is and then runs the pyhon script. 
Within the script use getenv to find the path.

Or just hard code the path...

Alan G


From kraus at hagen-partner.de  Fri May 26 09:41:55 2006
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Fri, 26 May 2006 09:41:55 +0200
Subject: [Tutor] partial string matching in list comprehension?
In-Reply-To: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
References: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
Message-ID: 

doug shawhan wrote:
> I have a series of lists to compare with a list of exclusionary terms.
> 
> 
> 
> junkList =["interchange",  "ifferen", "thru"]
> 
> The comparison lists have one or more elements, which may or may not 
> contain the junkList elements somewhere within:
> 
> l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
> forte"]
> 
> ... output would be
> 
> ["My skull hurts"]
> 
> I have used list comprehension to match complete elements, how can I do 
> a partial match?
> 
> def removeJunk(reply, junkList):
>         return [x for x in reply if x not in junkList]
> 
> It would be so much prettier than searching through each list element 
> for each term - I tend to get lost in a maze of twisty corridors, all alike.
> 
> Thanks!
> 
> 
Dunno if the performance of this solution is good and if it is more 
readable then RegExps, but here is LC:
[x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]

 >>> l = ["My skull hurts", "Drive the thruway", "Interchangability is 
not my forte"]
 >>> junkList =["interchange",  "ifferen", "thru"]
 >>> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
['My skull hurts', 'Interchangability is not my forte']
                               ^ Is there an "e" missing?

Because I don't like RegExps! ;-)

HTH,
Wolfram


From kent37 at tds.net  Fri May 26 12:47:15 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 May 2006 06:47:15 -0400
Subject: [Tutor] partial string matching in list comprehension?
In-Reply-To: 
References: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>
	
Message-ID: <4476DCB3.20701@tds.net>

Wolfram Kraus wrote:
> doug shawhan wrote:
>> I have a series of lists to compare with a list of exclusionary terms.
>>
>>
>>
>> junkList =["interchange",  "ifferen", "thru"]
>>
>> The comparison lists have one or more elements, which may or may not 
>> contain the junkList elements somewhere within:
>>
>> l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
>> forte"]
>>
>> ... output would be
>>
>> ["My skull hurts"]
>>
>> I have used list comprehension to match complete elements, how can I do 
>> a partial match?
>>
>> def removeJunk(reply, junkList):
>>         return [x for x in reply if x not in junkList]
>>
>> It would be so much prettier than searching through each list element 
>> for each term - I tend to get lost in a maze of twisty corridors, all alike.
>>
>> Thanks!
>>
>>
> Dunno if the performance of this solution is good and if it is more 
> readable then RegExps, but here is LC:
> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
A little cleaner is
    [ j for j in junkList if j not in x.lower() ]

This will compute x.lower() for each element of junkList...

Kent

> 
>  >>> l = ["My skull hurts", "Drive the thruway", "Interchangability is 
> not my forte"]
>  >>> junkList =["interchange",  "ifferen", "thru"]
>  >>> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
> ['My skull hurts', 'Interchangability is not my forte']
>                                ^ Is there an "e" missing?
> 
> Because I don't like RegExps! ;-)
> 
> HTH,
> Wolfram
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From kraus at hagen-partner.de  Fri May 26 13:02:49 2006
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Fri, 26 May 2006 13:02:49 +0200
Subject: [Tutor] partial string matching in list comprehension?
In-Reply-To: <4476DCB3.20701@tds.net>
References: <5e1ceb8a0605251234n28193412j9c5e98500c719b99@mail.gmail.com>	
	<4476DCB3.20701@tds.net>
Message-ID: <4476E059.9070307@hagen-partner.de>

Kent Johnson wrote:
> Wolfram Kraus wrote:
> 
>>doug shawhan wrote:
>>
>>>I have a series of lists to compare with a list of exclusionary terms.
>>>
>>>
>>>
>>>junkList =["interchange",  "ifferen", "thru"]
>>>
>>>The comparison lists have one or more elements, which may or may not 
>>>contain the junkList elements somewhere within:
>>>
>>>l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
>>>forte"]
>>>
>>>... output would be
>>>
>>>["My skull hurts"]
>>>
>>>I have used list comprehension to match complete elements, how can I do 
>>>a partial match?
>>>
>>>def removeJunk(reply, junkList):
>>>        return [x for x in reply if x not in junkList]
>>>
>>>It would be so much prettier than searching through each list element 
>>>for each term - I tend to get lost in a maze of twisty corridors, all alike.
>>>
>>>Thanks!
>>>
>>>
>>
>>Dunno if the performance of this solution is good and if it is more 
>>readable then RegExps, but here is LC:
>>[x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
> 
> A little cleaner is
>     [ j for j in junkList if j not in x.lower() ]
> 
> This will compute x.lower() for each element of junkList...
> 
> Kent
> 

Ahh, yes. Stupid old string methods :-S
But you are not quite correct, it has to be

[x for x in l if not [j for j in junkList if j in x.lower() ]]

See the "not"-ed parts ;-)

Wolfram


From andreas at kostyrka.org  Fri May 26 13:19:35 2006
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 26 May 2006 13:19:35 +0200
Subject: [Tutor] crontab or python mistake
In-Reply-To: <002e01c68096$939038b0$0c01a8c0@XPpro>
References: <6d87ecf40605252124sa4518dtf37f076617287ead@mail.gmail.com>
	<002e01c68096$939038b0$0c01a8c0@XPpro>
Message-ID: <1148642375.13499.1.camel@andi-lap>

Am Freitag, den 26.05.2006, 08:32 +0100 schrieb Alan Gauld:
> 
> > IOError: [Errno 2] No such file or directory: ' emmssg.txt'
> 
> >
> > the emmssg.txt file is in the /root/script directory so i 
> > don't know why it cant find it.
> 
> The file may be there but crontab isn't. It runs the program 
> as root and root's home directory is /.
> 
> For this kind of thing you need to either pass in the 
> data directory as an argument or wrap the python script 
> in a shell script that sets an environment variable to 
> where your data is and then runs the pyhon script. 
> Within the script use getenv to find the path.

Well, he can do the following stuff:
-) wrap it in a shell script that changes to current directory to the
expected one.
-) do that inside the python script.
-) make the file path absolute somehow:
   *) code it as a constant int the script.
   *) make it an argument (see sys.argv or module optparse)
   *) make it an argument via the environment (os.environ, not getenv)

Andreas


> 
> Or just hard code the path...
> 
> Alan G
> 
> _______________________________________________
> 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/20060526/32b42f52/attachment.pgp 

From andreas at kostyrka.org  Fri May 26 13:23:25 2006
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 26 May 2006 13:23:25 +0200
Subject: [Tutor] Unable to import xxx.pyd
In-Reply-To: 
References: 
Message-ID: <1148642605.13499.5.camel@andi-lap>

Well, xxx.pyd -> dynamic binary python module on Windows.
security value "755" suggests that you are trying to install it on a
Linux/Unix host.

Sorry, but dynamic binary modules on Linux end in ".so" (every Unix
treats that a little bit different, HPUX e.g. uses .sl, etc.)

And no, you cannot just copy a .pyd file from a Windows distribution to
a Linux host and expect it to work. (Actually .pyd files are sometimes
incompatible between differently compiled Python versions on Win32)

Andreas

Am Donnerstag, den 25.05.2006, 14:20 -0500 schrieb URBAN LANDREMAN:
> I'm debugging a program where I'm trying to import a file named xxx.pyd.
> 
> I test the logic interactively with IDLE and see that it makes a difference 
> on which directory the file xxx.pyd is located.  That is, I can get it to 
> work when xxx.pyd is on the path.
> 
> However, when I run the program in batch
> #!/usr/local/bin/python
> import cgitb; cgitb.enable()
> print "Content-type: text/html"
> print
> print "
"
> import sys
> print sys.path
> import xxx
> 
> I get the error message: No module named xxx, even though I know that the 
> file xxx.pyd is on the path.  If I put a file xxx.py in the same folder, the 
> system finds that file.
> 
> The file xxx.pyd has security numeric value 755, so the system should be 
> able to find it.
> 
> I'm baffled.
> 
> Any suggestions of what my be causing the system to not find xxx.pyd?
> 
> Thanks.
> 
> 
> Urban Landreman
> 
> 
> _______________________________________________
> 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/20060526/0e6c0468/attachment.pgp 

From samrobertsmith at gmail.com  Fri May 26 14:07:15 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Fri, 26 May 2006 05:07:15 -0700
Subject: [Tutor] How to import a module which was not in the current working
	directory?
Message-ID: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>

Hi,
How to import a module which was not in the current working directory?
Thanks,
Linda
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060526/947bcce3/attachment.html 

From kent37 at tds.net  Fri May 26 14:34:57 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 May 2006 08:34:57 -0400
Subject: [Tutor] How to import a module which was not in the current
 working directory?
In-Reply-To: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
References: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
Message-ID: <4476F5F1.4000300@tds.net>

linda.s wrote:
> Hi,
> How to import a module which was not in the current working directory?

This was just discussed on the list:
http://mail.python.org/pipermail/tutor/2006-May/047053.html

Kent


From andrew.arobert at gmail.com  Fri May 26 16:53:08 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Fri, 26 May 2006 10:53:08 -0400
Subject: [Tutor] How to import a module which was not in the current
 working directory?
In-Reply-To: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
References: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
Message-ID: <44771654.9040403@gmail.com>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Linda,

You can append your path to include the location of the module.

An example of this would be:

sys.path.append(r'\\share\somedirectory')


linda.s wrote:
> Hi,
> How to import a module which was not in the current working directory?
> Thanks,
> Linda
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdxZUDvn/4H0LjDwRAovqAJ99tie7ZVJiFdHF/wnqxYGujBmhuQCdFWEw
fFa4k3xTnxwr/nPmuG8PW1Q=
=IVFd
-----END PGP SIGNATURE-----

From jfabiani at yolo.com  Fri May 26 18:21:37 2006
From: jfabiani at yolo.com (johnf)
Date: Fri, 26 May 2006 09:21:37 -0700
Subject: [Tutor] seg fault from qt
Message-ID: <200605260921.37842.jfabiani@yolo.com>

Hi,
For some reason I have lost qt.  I'd like to know what I have to re-install to 
get python qt lib for SUSE 10.0.  When I use YAST I see nothing like 
python-qt

Right now I do
import qt

I get
seg fault

John

From hokkakada at khmeros.info  Sat May 27 03:50:59 2006
From: hokkakada at khmeros.info (kakada)
Date: Sat, 27 May 2006 08:50:59 +0700
Subject: [Tutor] How to import a module which was not in the current
 working directory?
In-Reply-To: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
References: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
Message-ID: <4477B083.3060906@khmeros.info>

Hi Linda,

Let say you have a tool named convert.py and other module
(processing.py) in modules folder.

In modules folder create an empty file named __init__.py
In convert.py do:
from modules import processing.py

It would work.

da

linda.s wrote:
> Hi,
> How to import a module which was not in the current working directory?
> Thanks,
> Linda
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From wescpy at gmail.com  Sat May 27 07:49:12 2006
From: wescpy at gmail.com (w chun)
Date: Fri, 26 May 2006 22:49:12 -0700
Subject: [Tutor] Download file from the web and store it locally.
In-Reply-To: <004601c67de6$212b1720$0202fea9@XPpro>
References: 
	<004601c67de6$212b1720$0202fea9@XPpro>
Message-ID: <78b3a9580605262249k1dcf63a3r86d184f0c2772a7a@mail.gmail.com>

> You need to step back a bit and get a better understanding of
> variables
> and functions and how to use them. You are trying to run before you
> can walk.
>    :
> You need to sit down and work through which variables you need
> and which functions of urllib you need.
>
> I suspect you only need to use urllib.urlretrieve() and your total
> code should only be 3 or 4 lines long.


matata,

i agree with alan here.  it does not even look like your program
should even get up to the point where you think that it should be
working up to.  i suspect plenty of NameError exceptions.

what you should do is to simplify first: get rid of most variables and
definitely that exception handler (try-except). write down the steps
(in pseudocode) as to what you want to do, what variables you want to
use, etc. after you get things working, you can dress up your code
with the extras.

after that, you should be able to piece together which variables you
really need and be able to construct the proper Python code from
there.  as alan has suggested, what i think you want to do, involves
using urllib.urlretrieve() and should only take a 3-5 lines of code.

good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From alan.gauld at freenet.co.uk  Sat May 27 11:00:06 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 27 May 2006 10:00:06 +0100
Subject: [Tutor] How to import a module which was not in the current
	workingdirectory?
References: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
Message-ID: <002901c6816b$f39db2c0$0c01a8c0@XPpro>

> How to import a module which was not in the current working 
> directory?

Put it in the import path - sys.path

iue the module should be located in a directory thats listed in 
sys.path.
There are several ways of achieving this, including adding the 
directory
to sys.path in your program or adding the directory to the PYTHONPATH
environment variable or modifying python startupo to include your 
directory.
Pick the method that seems most appropriate.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at freenet.co.uk  Sat May 27 11:01:57 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 27 May 2006 10:01:57 +0100
Subject: [Tutor] How to import a module which was not in the
	currentworking directory?
References: <1d987df30605260507s3d692505x223e1fb403ccede@mail.gmail.com>
	<4477B083.3060906@khmeros.info>
Message-ID: <003101c6816c$35a0cea0$0c01a8c0@XPpro>

> In modules folder create an empty file named __init__.py
> In convert.py do:
> from modules import processing.py

from modules import processing

don't include the .py

Also the modules folder still needs to be in sys.path

Alan G




From samrobertsmith at gmail.com  Sun May 28 10:27:04 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Sun, 28 May 2006 01:27:04 -0700
Subject: [Tutor] a question about symbol
Message-ID: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>

When I test the following code,
I got something like (use 80 as argument):
80?F=27?C
Why '?' appear?

# code
import string, sys

# If no arguments were given, print a helpful message
if len(sys.argv)==1:
    print 'Usage: celsius temp1 temp2 ...'
    sys.exit(0)

# Loop over the arguments
for i in sys.argv[1:]:
    try:
        fahrenheit=float(string.atoi(i))
    except string.atoi_error:
print repr(i), "not a numeric value"
    else:
celsius=(fahrenheit-32)*5.0/9.0
print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))

From dyoo at hkn.eecs.berkeley.edu  Sun May 28 17:55:25 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 May 2006 08:55:25 -0700 (PDT)
Subject: [Tutor] a question about symbol
In-Reply-To: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
Message-ID: 



On Sun, 28 May 2006, linda.s wrote:

> When I test the following code,
> I got something like (use 80 as argument):
> 80?F=27?C
> Why '?' appear?


Hi Linda,

Let's compare the output to what we think is producing it.  The very last 
statement in the program looks like the thing we want to watch:

     print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))

One thing that caught me off guard is the '\260' thing.  Can you explain 
what that is for?

From lists at janeden.org  Sun May 28 22:03:31 2006
From: lists at janeden.org (Jan Eden)
Date: Sun, 28 May 2006 22:03:31 +0200
Subject: [Tutor] MySQLdb.converters.escape() type error
Message-ID: 

Hi,

after upgrading to MySQL 5 and MySQLdb 1.2.1_p2, I have the following problem:

self.db=MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, cursorclass=MySQLdb.cursors.DictCursor)
stringel = 'Some string'
stringel = self.db.escape(stringel)

  File "./test.py", line 12, in ?
    stringel = self.db.escape(stringel)
TypeError: no default type converter defined

I checked the documentation for MySQLdb.converters and saw that the escape() function takes a dictionary as an obligatory second argument.

This is odd, because I have always been using escape(string) without a problem.

The changes in MySQLdb 1.2.1_p2 list:

"Mapped a lot of new 4.1 and 5.0 error codes to Python exceptions"

Could someone point me to the problem in the MySQL side? Thanks in advance!

- Jan
--  
Any technology which is distinguishable from magic is insufficiently advanced.

From samrobertsmith at gmail.com  Sun May 28 22:11:57 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Sun, 28 May 2006 13:11:57 -0700
Subject: [Tutor] a question about symbol
In-Reply-To: 
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
	
Message-ID: <1d987df30605281311t79b3b2a5q7f1df2151c53d44a@mail.gmail.com>

On 5/28/06, Danny Yoo  wrote:
>
>
> On Sun, 28 May 2006, linda.s wrote:
>
> > When I test the following code,
> > I got something like (use 80 as argument):
> > 80?F=27?C
> > Why '?' appear?
>
>
> Hi Linda,
>
> Let's compare the output to what we think is producing it.  The very last
> statement in the program looks like the thing we want to watch:
>
>     print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))
>
> One thing that caught me off guard is the '\260' thing.  Can you explain
> what that is for?
It is a sample code i downloaded.
I think it is the symbol put before F or C ( should be a small
circle)...\I do not know why it appeared "?"

From dyoo at hkn.eecs.berkeley.edu  Sun May 28 22:50:27 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 May 2006 13:50:27 -0700 (PDT)
Subject: [Tutor] a question about symbol
In-Reply-To: <1d987df30605281311t79b3b2a5q7f1df2151c53d44a@mail.gmail.com>
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
	
	<1d987df30605281311t79b3b2a5q7f1df2151c53d44a@mail.gmail.com>
Message-ID: 


>> Let's compare the output to what we think is producing it.  The very 
>> last statement in the program looks like the thing we want to watch:
>>
>>     print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))
>>
>> One thing that caught me off guard is the '\260' thing.  Can you explain
>> what that is for?
>
> It is a sample code i downloaded. I think it is the symbol put before F 
> or C ( should be a small circle)...\I do not know why it appeared "?"


Hi Linda,

Ok, let's restate the question then.  The question really seems to be: 
"How do I print a 'degree' symbol on the screen?"  Does that sound right 
to you?


Unfortunately, this is not such a fun problem to solve.  It really depends 
on our output device --- the terminal --- and the support that our output 
device gives us.  Some terminal displays don't provide much graphical 
support at all.  In this case, you're seeing a question mark because the 
terminal has no clue how to render the character we're trying to display. 
Other terminals accept and display Unicode or other extended character 
sets, but it sounds like yours may not.

You may want to read "The Absolute Minimum Every Software Developer 
Absolutely, Positively Must Know About Unicode and Character Sets (No 
Excuses!)" because it gives more background information on this ugly 
mess:

     http://www.joelonsoftware.com/articles/Unicode.html

If it isn't too much of a deal for you, just change '\260' to 'degrees'. 
*grin*


Best of wishes!

From bgailer at alum.rpi.edu  Mon May 29 02:55:06 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 28 May 2006 17:55:06 -0700
Subject: [Tutor] a question about symbol
In-Reply-To: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
Message-ID: <447A466A.8040909@alum.rpi.edu>

linda.s wrote:
> When I test the following code,
> I got something like (use 80 as argument):
> 80?F=27?C
> Why '?' appear?
>
> # code
> import string, sys
>
> # If no arguments were given, print a helpful message
> if len(sys.argv)==1:
>     print 'Usage: celsius temp1 temp2 ...'
>     sys.exit(0)
>
> # Loop over the arguments
> for i in sys.argv[1:]:
>     try:
>         fahrenheit=float(string.atoi(i))
>     except string.atoi_error:
> print repr(i), "not a numeric value"
>     else:
> celsius=(fahrenheit-32)*5.0/9.0
> print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))
>   
On my computer I get the desired result. I paste it here 80?F = 27?C and 
I see degree symbols.

What operating system / terminal hardware are you using?

-- 
Bob Gailer
510-978-4454

Broadband Phone Service for local and long distance $19.95/mo plus 1 mo Free 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060528/77f67651/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: show
Type: image/gif
Size: 43 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060528/77f67651/attachment.gif 

From ccp999 at gmail.com  Mon May 29 04:32:29 2006
From: ccp999 at gmail.com (Brendan Cheng)
Date: Mon, 29 May 2006 12:32:29 +1000
Subject: [Tutor] Enumeration and Constant
Message-ID: <7e27d9ba0605281932ge35ff98mdd35a8b6f345fad7@mail.gmail.com>

 Hi,

I wander how to setup the enumeration type  and constant in Python, which I
couldn't find the topic in the help file.
I'm using python 2.4.3

please give me an example of it as well


Thanks,

Brendan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060529/14e0e554/attachment.htm 

From ccp999 at gmail.com  Mon May 29 04:43:09 2006
From: ccp999 at gmail.com (Brendan Cheng)
Date: Mon, 29 May 2006 12:43:09 +1000
Subject: [Tutor] Enumeration and constant
Message-ID: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>

 Hi,

I wander how to setup the enumeration type  and constant in Python, which I
couldn't find the topic in the help file.
I'm using python 2.4.3

please give me an example of it as well


Thanks,


Brendan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060529/206a6998/attachment.html 

From rondosxx at yahoo.com  Mon May 29 05:14:54 2006
From: rondosxx at yahoo.com (ron)
Date: Sun, 28 May 2006 20:14:54 -0700 (PDT)
Subject: [Tutor] a question about symbol
Message-ID: <20060529031454.31969.qmail@web50106.mail.yahoo.com>

When I run this program using your code on Ubuntu
Linux, I get:

~$ ./c2f.py 44
44\uffffF = 7\uffffC

Please notice that the code you have posted has
indentation block errors.





__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From bgailer at alum.rpi.edu  Mon May 29 06:31:38 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 28 May 2006 21:31:38 -0700
Subject: [Tutor] Enumeration and constant
In-Reply-To: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>
References: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>
Message-ID: <447A792A.2030402@alum.rpi.edu>

Brendan Cheng wrote:
> I wander how to setup the enumeration type  and constant in Python, 
> which I couldn't find the topic in the help file.
There is no built-in enumeration type. See
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67107
for an example of an enumeration class.

-- 
Bob Gailer
510-978-4454

Broadband Phone Service for local and long distance $19.95/mo plus 1 mo Free 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060528/1adc4783/attachment.html 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: show
Type: image/gif
Size: 43 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060528/1adc4783/attachment.gif 

From 3dbernard at gmail.com  Mon May 29 16:59:59 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 29 May 2006 10:59:59 -0400
Subject: [Tutor] how to use the "image" option for Button widget in Tkinter
Message-ID: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>

Hello everyone,

I'm looking for a way to put an image on a button in a Tkinter GUI,
but for the life of me I just can't find any clear directions about
how to do that. No matter where I look, the only documentation I can
find is this (Fred Lundz):

"image (image). The image to display in the widget. If specified, this
takes precedence over the text and bitmap options."


How do you format the image argument value? I have try absolute paths,
I always get a path not found error. Also, what is the file format to
use?


Thanks
Bernard

From alan.gauld at freenet.co.uk  Mon May 29 17:43:32 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 29 May 2006 16:43:32 +0100
Subject: [Tutor] Enumeration and constant
References: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>
Message-ID: <004701c68336$a3c13a20$0a01a8c0@XPpro>

> I wander how to setup the enumeration type  
> and constant in Python, 

These concepts do not exist in Python per se.

The convention is to make constant names uppercase:

PI = 3.1415926

Enums are a little more variable in implementation depending 
on what you want to do with them. If you need to iterate over 
them a tuple might be a choice with strings as values. But if 
you need to use them as indices into a list a dictionary might 
be better.(But you could use them as keys into a dictionary 
instead of course!)

Other more sophisticated options include creating classes.
These can implement restricted ranges etc

In practice I rarely find I need enums in Python because the 
wealth of data types (lists, tupoles, sets, dictionaries, classes)
means I rarely need and extra symbolic values. I usually find 
myself using enums in other languages because I don't have 
quite the right data type available and an enum helps fake it.

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From 3dbernard at gmail.com  Mon May 29 20:41:29 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 29 May 2006 14:41:29 -0400
Subject: [Tutor] how to use the "image" option for Button widget in
	Tkinter
In-Reply-To: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
References: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
Message-ID: <61d0e2b40605291141t65132c21j96faaeef6d0da21e@mail.gmail.com>

After some further googling around, I found the solution. In fact, I
found it in an example on a german web page,
http://home.foni.net/~heikos/tkinter/node56.html (I don't speak
German).

Anyway, here is my working code, for the record:


import Tkinter as tk
import os


# Define constants
sIMAGEROOT = r'\\Linuxserver\ANIMATION\XSI\WORKGROUP_ANIMATION\Data\Scripts\bb_pipeline\bb_filesystem\bb_filesystemimages'
sOPENFOLDER = os.path.join( sIMAGEROOT, 'openfold.gif' )


# Build main frame
oMainFrame = tk.Tk()

# Create image instance
oOPENFOLDER = tk.PhotoImage( file = sOPENFOLDER, master = oMainFrame )

# Create button
oButton = tk.Button( oMainFrame, image = oOPENFOLDER )
oButton.photo = oOPENFOLDER


oButton.pack( side = tk.LEFT )


# Launch GUI
oMainFrame.mainloop()



Cheers
Bernard


On 5/29/06, Bernard Lebel <3dbernard at gmail.com> wrote:
> Hello everyone,
>
> I'm looking for a way to put an image on a button in a Tkinter GUI,
> but for the life of me I just can't find any clear directions about
> how to do that. No matter where I look, the only documentation I can
> find is this (Fred Lundz):
>
> "image (image). The image to display in the widget. If specified, this
> takes precedence over the text and bitmap options."
>
>
> How do you format the image argument value? I have try absolute paths,
> I always get a path not found error. Also, what is the file format to
> use?
>
>
> Thanks
> Bernard
>

From 3dbernard at gmail.com  Mon May 29 20:41:29 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 29 May 2006 14:41:29 -0400
Subject: [Tutor] how to use the "image" option for Button widget in
	Tkinter
In-Reply-To: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
References: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
Message-ID: <61d0e2b40605291141t65132c21j96faaeef6d0da21e@mail.gmail.com>

After some further googling around, I found the solution. In fact, I
found it in an example on a german web page,
http://home.foni.net/~heikos/tkinter/node56.html (I don't speak
German).

Anyway, here is my working code, for the record:


import Tkinter as tk
import os


# Define constants
sIMAGEROOT = r'\\Linuxserver\ANIMATION\XSI\WORKGROUP_ANIMATION\Data\Scripts\bb_pipeline\bb_filesystem\bb_filesystemimages'
sOPENFOLDER = os.path.join( sIMAGEROOT, 'openfold.gif' )


# Build main frame
oMainFrame = tk.Tk()

# Create image instance
oOPENFOLDER = tk.PhotoImage( file = sOPENFOLDER, master = oMainFrame )

# Create button
oButton = tk.Button( oMainFrame, image = oOPENFOLDER )
oButton.photo = oOPENFOLDER


oButton.pack( side = tk.LEFT )


# Launch GUI
oMainFrame.mainloop()



Cheers
Bernard


On 5/29/06, Bernard Lebel <3dbernard at gmail.com> wrote:
> Hello everyone,
>
> I'm looking for a way to put an image on a button in a Tkinter GUI,
> but for the life of me I just can't find any clear directions about
> how to do that. No matter where I look, the only documentation I can
> find is this (Fred Lundz):
>
> "image (image). The image to display in the widget. If specified, this
> takes precedence over the text and bitmap options."
>
>
> How do you format the image argument value? I have try absolute paths,
> I always get a path not found error. Also, what is the file format to
> use?
>
>
> Thanks
> Bernard
>

From 3dbernard at gmail.com  Mon May 29 20:41:29 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 29 May 2006 14:41:29 -0400
Subject: [Tutor] how to use the "image" option for Button widget in
	Tkinter
In-Reply-To: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
References: <61d0e2b40605290759q4fe0c535r2107c1c97120c5e6@mail.gmail.com>
Message-ID: <61d0e2b40605291141t65132c21j96faaeef6d0da21e@mail.gmail.com>

After some further googling around, I found the solution. In fact, I
found it in an example on a german web page,
http://home.foni.net/~heikos/tkinter/node56.html (I don't speak
German).

Anyway, here is my working code, for the record:


import Tkinter as tk
import os


# Define constants
sIMAGEROOT = r'\\Linuxserver\ANIMATION\XSI\WORKGROUP_ANIMATION\Data\Scripts\bb_pipeline\bb_filesystem\bb_filesystemimages'
sOPENFOLDER = os.path.join( sIMAGEROOT, 'openfold.gif' )


# Build main frame
oMainFrame = tk.Tk()

# Create image instance
oOPENFOLDER = tk.PhotoImage( file = sOPENFOLDER, master = oMainFrame )

# Create button
oButton = tk.Button( oMainFrame, image = oOPENFOLDER )
oButton.photo = oOPENFOLDER


oButton.pack( side = tk.LEFT )


# Launch GUI
oMainFrame.mainloop()



Cheers
Bernard


On 5/29/06, Bernard Lebel <3dbernard at gmail.com> wrote:
> Hello everyone,
>
> I'm looking for a way to put an image on a button in a Tkinter GUI,
> but for the life of me I just can't find any clear directions about
> how to do that. No matter where I look, the only documentation I can
> find is this (Fred Lundz):
>
> "image (image). The image to display in the widget. If specified, this
> takes precedence over the text and bitmap options."
>
>
> How do you format the image argument value? I have try absolute paths,
> I always get a path not found error. Also, what is the file format to
> use?
>
>
> Thanks
> Bernard
>

From bgailer at alum.rpi.edu  Tue May 30 01:24:09 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 29 May 2006 16:24:09 -0700
Subject: [Tutor] Enumeration and constant
In-Reply-To: <7e27d9ba0605282138n77be5e05ub3990ae35873aec3@mail.gmail.com>
References: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>	
	<447A792A.2030402@alum.rpi.edu>
	<7e27d9ba0605282138n77be5e05ub3990ae35873aec3@mail.gmail.com>
Message-ID: <447B8299.6040007@alum.rpi.edu>

Please always reply to the list as well as me. Others may be able to 
help, and we all learn from our interactions.

Brendan Cheng wrote:
> how about custom constant type?
> Does python provide?
No. Python tries to be as "light" as possible. There is a convention 
amongst Python programmers to use upper case names to represent 
constants, e.g. RED = 3.

-- 
Bob Gailer
510-978-4454


From wescpy at gmail.com  Tue May 30 01:53:41 2006
From: wescpy at gmail.com (w chun)
Date: Mon, 29 May 2006 16:53:41 -0700
Subject: [Tutor] Enumeration and constant
In-Reply-To: <447B8299.6040007@alum.rpi.edu>
References: <7e27d9ba0605281943w59235da5tcb29c710e39dd42f@mail.gmail.com>
	<447A792A.2030402@alum.rpi.edu>
	<7e27d9ba0605282138n77be5e05ub3990ae35873aec3@mail.gmail.com>
	<447B8299.6040007@alum.rpi.edu>
Message-ID: <78b3a9580605291653k33577708oee312463631aab3d@mail.gmail.com>

> > how about custom constant type?
> > Does python provide?
> No. Python tries to be as "light" as possible. There is a convention
> amongst Python programmers to use upper case names to represent
> constants, e.g. RED = 3.

another aspect of Python numbers that make them "constant" is that all
numeric types are immutable, meaning you cannot change their values
anyway.  the idiom that Bob and Alan described is mostly for the
programmer.  you can, of course, reassign that variable to another
number (which is also immutable), and Python won't stop you.

i have used tuples/lists and dicts as a proxy for enum-type
functionality, and they work just fine.

also, do not get confused between all this and the enumerate()
built-in function.  all that does is for a sequence, return both an
index and the corresponding sequence element so that folks stop doing
stuff like "for i in range(len(seq))".

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From dkuhlman at cutter.rexx.com  Tue May 30 22:20:21 2006
From: dkuhlman at cutter.rexx.com (Dave Kuhlman)
Date: Tue, 30 May 2006 20:20:21 +0000 (UTC)
Subject: [Tutor] =?utf-8?q?=5Fnext?=
References: <20060525013031.73375.qmail@web51606.mail.yahoo.com>
	
Message-ID: 

Roel Schroeven  fastmail.fm> writes:


[good suggestions snipped]

> 
> The _next() method is a generator function as I described above, which 
> creates an iterator object when called.
> The __iter__() method just calls that generator function and returns the 
> result to its caller.
> 
> HTH
> 

Kent Johnson alerted me to this discussion.

And, thanks, Roel, for the comments and improvements on my example.

I agree that my example class being discussed is confused.  I've reworked the 
example, taking hints from this thread.  And, while I was there, I've re-written 
the whole section on iterators.  Hopefully, I've made it less (rather than more) 
confusing.  You can find the new version here:

http://www.rexx.com/~dkuhlman/python_101/python_101.html
http://www.rexx.com/~dkuhlman/python_101/python_101.
html#SECTION004460000000000000000

You may be wondering why I would spend so much time on what seems to be a little 
used and advanced technique.  After all, iterators cannot be too important, 
since they did not even make it into Python until Python 2.2.  The answer I give 
myself is that this Python feature is very powerful and very elegant.  It also 
gives us the ability to write clearer and more maintainable code, for example, 
separating the producer and consumer parts of our code.  But, it does so only if 
we can work out a clear and unconfused way to explain and teach it.  Thanks for 
motivating me to try to do that.

Dave 




From rschroev_nospam_ml at fastmail.fm  Wed May 31 12:15:19 2006
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Wed, 31 May 2006 12:15:19 +0200
Subject: [Tutor] _next
In-Reply-To: 
References: <20060525013031.73375.qmail@web51606.mail.yahoo.com>	
	
Message-ID: 

Dave Kuhlman schreef:
> Roel Schroeven  fastmail.fm> writes:
> Kent Johnson alerted me to this discussion.
> 
> And, thanks, Roel, for the comments and improvements on my example.
> 
> I agree that my example class being discussed is confused.  I've reworked the 
> example, taking hints from this thread.  And, while I was there, I've re-written 
> the whole section on iterators.  Hopefully, I've made it less (rather than more) 
> confusing.  You can find the new version here:
> 
> http://www.rexx.com/~dkuhlman/python_101/python_101.html
> http://www.rexx.com/~dkuhlman/python_101/python_101.
> html#SECTION004460000000000000000

I think it is quite clear now; it certainly gives a nice overview of all 
the different ways of creating iterators. It might be a bit overwhelming 
for beginners though.

> You may be wondering why I would spend so much time on what seems to be a little 
> used and advanced technique.  After all, iterators cannot be too important, 
> since they did not even make it into Python until Python 2.2.  The answer I give 
> myself is that this Python feature is very powerful and very elegant.  It also 
> gives us the ability to write clearer and more maintainable code, for example, 
> separating the producer and consumer parts of our code.  But, it does so only if 
> we can work out a clear and unconfused way to explain and teach it.  Thanks for 
> motivating me to try to do that.

I agree that iterators are an important language feature, but as I said 
it might be a bit too much information to digest at once. I know I 
didn't learn the iterator protocol until after I gained some experience 
in Python. OTOH, that might just be because it wasn't mentioned in the 
tutorial I used (the official one), so maybe it's a good thing that it's 
clearly explained in your tutorial.

I think comments from people who use the tutorial to learn Python are 
more appropriate than mine in this regard.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven